rust-expect 0.1.0

Next-generation Expect-style terminal automation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! PTY backend for local process spawning.
//!
//! This module provides the PTY backend that uses the rust-pty crate
//! to spawn local processes with pseudo-terminal support.

use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};

use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

use crate::config::SessionConfig;
use crate::error::{ExpectError, Result, SpawnError};

/// A PTY-based transport for local process communication.
pub struct PtyTransport {
    /// The PTY reader half.
    reader: Box<dyn AsyncRead + Unpin + Send>,
    /// The PTY writer half.
    writer: Box<dyn AsyncWrite + Unpin + Send>,
    /// Process ID.
    pid: Option<u32>,
}

impl PtyTransport {
    /// Create a new PTY transport from reader and writer.
    pub fn new<R, W>(reader: R, writer: W) -> Self
    where
        R: AsyncRead + Unpin + Send + 'static,
        W: AsyncWrite + Unpin + Send + 'static,
    {
        Self {
            reader: Box::new(reader),
            writer: Box::new(writer),
            pid: None,
        }
    }

    /// Set the process ID.
    pub const fn set_pid(&mut self, pid: u32) {
        self.pid = Some(pid);
    }

    /// Get the process ID.
    #[must_use]
    pub const fn pid(&self) -> Option<u32> {
        self.pid
    }
}

impl AsyncRead for PtyTransport {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.reader).poll_read(cx, buf)
    }
}

impl AsyncWrite for PtyTransport {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.writer).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.writer).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.writer).poll_shutdown(cx)
    }
}

/// Configuration for PTY spawning.
#[derive(Debug, Clone)]
pub struct PtyConfig {
    /// Terminal dimensions (cols, rows).
    pub dimensions: (u16, u16),
    /// Whether to use a login shell.
    pub login_shell: bool,
    /// Environment variable handling.
    pub env_mode: EnvMode,
}

impl Default for PtyConfig {
    fn default() -> Self {
        Self {
            dimensions: (80, 24),
            login_shell: false,
            env_mode: EnvMode::Inherit,
        }
    }
}

impl From<&SessionConfig> for PtyConfig {
    fn from(config: &SessionConfig) -> Self {
        Self {
            dimensions: config.dimensions,
            login_shell: false,
            env_mode: if config.env.is_empty() {
                EnvMode::Inherit
            } else {
                EnvMode::Extend
            },
        }
    }
}

/// Environment variable handling mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnvMode {
    /// Inherit all environment variables from parent.
    Inherit,
    /// Clear environment and only use specified variables.
    Clear,
    /// Inherit and extend with specified variables.
    Extend,
}

/// Spawner for PTY sessions.
pub struct PtySpawner {
    config: PtyConfig,
}

impl PtySpawner {
    /// Create a new PTY spawner with default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: PtyConfig::default(),
        }
    }

    /// Create a new PTY spawner with custom configuration.
    #[must_use]
    pub const fn with_config(config: PtyConfig) -> Self {
        Self { config }
    }

    /// Set the terminal dimensions.
    pub const fn set_dimensions(&mut self, cols: u16, rows: u16) {
        self.config.dimensions = (cols, rows);
    }

    /// Spawn a command.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The command or arguments contain null bytes
    /// - PTY allocation fails
    /// - Fork fails
    /// - Exec fails (child exits with code 1)
    #[cfg(unix)]
    #[allow(unsafe_code)]
    #[allow(clippy::unused_async)]
    pub async fn spawn(&self, command: &str, args: &[String]) -> Result<PtyHandle> {
        use std::ffi::CString;

        // Validate and create CStrings BEFORE forking so we can return proper errors
        let cmd_cstring = CString::new(command).map_err(|_| {
            ExpectError::Spawn(SpawnError::InvalidArgument {
                kind: "command".to_string(),
                value: command.to_string(),
                reason: "command contains null byte".to_string(),
            })
        })?;

        let mut argv_cstrings: Vec<CString> = Vec::with_capacity(args.len() + 1);
        argv_cstrings.push(cmd_cstring.clone());

        for (idx, arg) in args.iter().enumerate() {
            let arg_cstring = CString::new(arg.as_str()).map_err(|_| {
                ExpectError::Spawn(SpawnError::InvalidArgument {
                    kind: format!("argument[{idx}]"),
                    value: arg.clone(),
                    reason: "argument contains null byte".to_string(),
                })
            })?;
            argv_cstrings.push(arg_cstring);
        }

        // Create PTY pair
        // SAFETY: openpty() is called with valid pointers to stack-allocated integers.
        // The null pointers for name, termp, and winp are explicitly allowed per POSIX.
        // We check the return value and handle errors appropriately.
        let pty_result = unsafe {
            let mut master: libc::c_int = 0;
            let mut slave: libc::c_int = 0;

            // Open PTY
            if libc::openpty(
                &raw mut master,
                &raw mut slave,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ) != 0
            {
                return Err(ExpectError::Spawn(SpawnError::PtyAllocation {
                    reason: "Failed to open PTY".to_string(),
                }));
            }

            (master, slave)
        };

        let (master_fd, slave_fd) = pty_result;

        // Fork the process
        // SAFETY: fork() is safe to call at this point as we have no threads running
        // that could hold locks. The child process will immediately set up its
        // environment and exec into the target program.
        let pid = unsafe { libc::fork() };

        match pid {
            -1 => Err(ExpectError::Spawn(SpawnError::Io(
                io::Error::last_os_error(),
            ))),
            0 => {
                // Child process
                // SAFETY: This runs in the forked child process only. We:
                // - Close the master fd (not needed in child)
                // - Create a new session with setsid()
                // - Set the slave as the controlling terminal via TIOCSCTTY
                // - Redirect stdin/stdout/stderr to the slave pty
                // - Close the original slave fd if it's not 0, 1, or 2
                // - Execute the target command (never returns on success)
                // - Exit with code 1 if exec fails
                // All file descriptors are valid and owned by this process.
                unsafe {
                    libc::close(master_fd);
                    libc::setsid();
                    // Cast TIOCSCTTY to c_ulong for macOS compatibility (u32 -> u64)
                    libc::ioctl(slave_fd, libc::TIOCSCTTY as libc::c_ulong, 0);

                    libc::dup2(slave_fd, 0);
                    libc::dup2(slave_fd, 1);
                    libc::dup2(slave_fd, 2);

                    if slave_fd > 2 {
                        libc::close(slave_fd);
                    }

                    // Use pre-validated CStrings (validated before fork)
                    let argv_ptrs: Vec<*const libc::c_char> = argv_cstrings
                        .iter()
                        .map(|s| s.as_ptr())
                        .chain(std::iter::once(std::ptr::null()))
                        .collect();

                    libc::execvp(cmd_cstring.as_ptr(), argv_ptrs.as_ptr());
                    libc::_exit(1);
                }
            }
            child_pid => {
                // Parent process
                // SAFETY: slave_fd is a valid file descriptor obtained from openpty().
                // The parent doesn't need the slave end; only the child uses it.
                unsafe {
                    libc::close(slave_fd);
                }

                // Set non-blocking
                // SAFETY: master_fd is a valid file descriptor from openpty().
                // F_GETFL and F_SETFL with O_NONBLOCK are standard operations
                // that don't violate any safety invariants.
                unsafe {
                    let flags = libc::fcntl(master_fd, libc::F_GETFL);
                    libc::fcntl(master_fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
                }

                Ok(PtyHandle {
                    master_fd,
                    pid: child_pid as u32,
                    dimensions: self.config.dimensions,
                })
            }
        }
    }

    /// Spawn a command on Windows using ConPTY.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - ConPTY is not available (Windows version too old)
    /// - PTY allocation fails
    /// - Process spawning fails
    #[cfg(windows)]
    pub async fn spawn(&self, command: &str, args: &[String]) -> Result<WindowsPtyHandle> {
        use rust_pty::{PtySystem, WindowsPtySystem};

        // Create configuration for rust-pty
        let pty_config = rust_pty::PtyConfig {
            window_size: self.config.dimensions,
            // If env_mode is Clear, use empty env; otherwise inherit (env: None)
            env: match self.config.env_mode {
                EnvMode::Clear => Some(std::collections::HashMap::new()),
                _ => None,
            },
            ..Default::default()
        };

        // Spawn using rust-pty's Windows implementation
        let (master, child) =
            WindowsPtySystem::spawn(command, args.iter().map(|s| s.as_str()), &pty_config)
                .await
                .map_err(|e| {
                    ExpectError::Spawn(SpawnError::PtyAllocation {
                        reason: format!("Windows ConPTY spawn failed: {e}"),
                    })
                })?;

        Ok(WindowsPtyHandle {
            master,
            child,
            dimensions: self.config.dimensions,
        })
    }
}

impl Default for PtySpawner {
    fn default() -> Self {
        Self::new()
    }
}

/// Handle to a spawned PTY process (Unix).
#[cfg(unix)]
#[derive(Debug)]
pub struct PtyHandle {
    /// Master PTY file descriptor.
    master_fd: i32,
    /// Process ID.
    pid: u32,
    /// Terminal dimensions (cols, rows).
    dimensions: (u16, u16),
}

/// Handle to a spawned PTY process (Windows).
#[cfg(windows)]
pub struct WindowsPtyHandle {
    /// The PTY master from rust-pty.
    pub(crate) master: rust_pty::WindowsPtyMaster,
    /// The child process handle.
    pub(crate) child: rust_pty::WindowsPtyChild,
    /// Terminal dimensions (cols, rows).
    dimensions: (u16, u16),
}

#[cfg(windows)]
impl std::fmt::Debug for WindowsPtyHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowsPtyHandle")
            .field("dimensions", &self.dimensions)
            .finish_non_exhaustive()
    }
}

#[cfg(unix)]
impl PtyHandle {
    /// Get the process ID.
    #[must_use]
    pub const fn pid(&self) -> u32 {
        self.pid
    }

    /// Get the terminal dimensions.
    #[must_use]
    pub const fn dimensions(&self) -> (u16, u16) {
        self.dimensions
    }

    /// Resize the terminal.
    #[allow(unsafe_code)]
    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
        let winsize = libc::winsize {
            ws_row: rows,
            ws_col: cols,
            ws_xpixel: 0,
            ws_ypixel: 0,
        };

        // SAFETY: master_fd is a valid PTY file descriptor stored in self.
        // TIOCSWINSZ is a valid ioctl command for PTYs that sets the window size.
        // winsize is a valid pointer to a properly initialized struct on the stack.
        // Cast to c_ulong for macOS compatibility (u32 -> u64).
        let result =
            unsafe { libc::ioctl(self.master_fd, libc::TIOCSWINSZ as libc::c_ulong, &winsize) };

        if result != 0 {
            Err(ExpectError::Io(io::Error::last_os_error()))
        } else {
            self.dimensions = (cols, rows);
            Ok(())
        }
    }

    /// Wait for the process to exit.
    #[allow(unsafe_code)]
    pub fn wait(&self) -> Result<i32> {
        let mut status: libc::c_int = 0;
        // SAFETY: self.pid is a valid process ID from fork().
        // status is a valid pointer to a stack-allocated integer.
        // The options argument (0) means blocking wait, which is valid.
        let result = unsafe { libc::waitpid(self.pid as i32, &raw mut status, 0) };

        if result == -1 {
            Err(ExpectError::Io(io::Error::last_os_error()))
        } else if libc::WIFEXITED(status) {
            Ok(libc::WEXITSTATUS(status))
        } else if libc::WIFSIGNALED(status) {
            Ok(128 + libc::WTERMSIG(status))
        } else {
            Ok(-1)
        }
    }

    /// Send a signal to the process.
    #[allow(unsafe_code)]
    pub fn signal(&self, signal: i32) -> Result<()> {
        // SAFETY: self.pid is a valid process ID from fork().
        // The signal is passed from the caller and must be a valid signal number.
        // kill() is safe to call with any PID; it returns an error for invalid PIDs.
        let result = unsafe { libc::kill(self.pid as i32, signal) };
        if result != 0 {
            Err(ExpectError::Io(io::Error::last_os_error()))
        } else {
            Ok(())
        }
    }

    /// Kill the process.
    pub fn kill(&self) -> Result<()> {
        self.signal(libc::SIGKILL)
    }
}

#[cfg(windows)]
impl WindowsPtyHandle {
    /// Get the process ID.
    #[must_use]
    pub fn pid(&self) -> u32 {
        self.child.pid()
    }

    /// Get the terminal dimensions.
    #[must_use]
    pub const fn dimensions(&self) -> (u16, u16) {
        self.dimensions
    }

    /// Resize the terminal.
    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
        use rust_pty::{PtyMaster, WindowSize};
        let size = WindowSize::new(cols, rows);
        self.master
            .resize(size)
            .map_err(|e| ExpectError::Io(io::Error::other(format!("resize failed: {e}"))))?;
        self.dimensions = (cols, rows);
        Ok(())
    }

    /// Check if the child process is still running.
    #[must_use]
    pub fn is_running(&self) -> bool {
        self.child.is_running()
    }

    /// Kill the process.
    pub fn kill(&mut self) -> Result<()> {
        self.child
            .kill()
            .map_err(|e| ExpectError::Io(io::Error::other(format!("kill failed: {e}"))))
    }
}

#[cfg(unix)]
impl Drop for PtyHandle {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        // Close the master fd
        // SAFETY: master_fd is a valid file descriptor obtained from openpty()
        // and stored in this struct. It has not been closed elsewhere as we own it.
        // Closing in Drop ensures the fd is released when the handle is dropped.
        unsafe {
            libc::close(self.master_fd);
        }
    }
}

/// Async wrapper around a PTY file descriptor for use with Tokio.
///
/// This provides `AsyncRead` and `AsyncWrite` implementations that
/// integrate with the Tokio runtime.
#[cfg(unix)]
pub struct AsyncPty {
    /// The async file descriptor wrapper.
    inner: tokio::io::unix::AsyncFd<std::os::unix::io::RawFd>,
    /// Process ID.
    pid: u32,
    /// Terminal dimensions.
    dimensions: (u16, u16),
}

#[cfg(unix)]
impl AsyncPty {
    /// Create a new async PTY wrapper from a `PtyHandle`.
    ///
    /// Takes ownership of the `PtyHandle`'s file descriptor.
    ///
    /// # Errors
    ///
    /// Returns an error if the `AsyncFd` cannot be created.
    pub fn from_handle(handle: PtyHandle) -> io::Result<Self> {
        let fd = handle.master_fd;
        let pid = handle.pid;
        let dimensions = handle.dimensions;

        // Prevent the original handle from closing the fd
        std::mem::forget(handle);

        let inner = tokio::io::unix::AsyncFd::new(fd)?;
        Ok(Self {
            inner,
            pid,
            dimensions,
        })
    }

    /// Get the process ID.
    #[must_use]
    pub const fn pid(&self) -> u32 {
        self.pid
    }

    /// Get the terminal dimensions.
    #[must_use]
    pub const fn dimensions(&self) -> (u16, u16) {
        self.dimensions
    }

    /// Resize the terminal.
    #[allow(unsafe_code)]
    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
        let winsize = libc::winsize {
            ws_row: rows,
            ws_col: cols,
            ws_xpixel: 0,
            ws_ypixel: 0,
        };

        // SAFETY: The fd is valid and TIOCSWINSZ is a valid ioctl for PTYs.
        // Cast to c_ulong for macOS compatibility (u32 -> u64).
        let result = unsafe {
            libc::ioctl(
                *self.inner.get_ref(),
                libc::TIOCSWINSZ as libc::c_ulong,
                &winsize,
            )
        };

        if result != 0 {
            Err(ExpectError::Io(io::Error::last_os_error()))
        } else {
            self.dimensions = (cols, rows);
            Ok(())
        }
    }

    /// Send a signal to the child process.
    #[allow(unsafe_code)]
    pub fn signal(&self, signal: i32) -> Result<()> {
        // SAFETY: pid is a valid process ID from fork().
        let result = unsafe { libc::kill(self.pid as i32, signal) };
        if result != 0 {
            Err(ExpectError::Io(io::Error::last_os_error()))
        } else {
            Ok(())
        }
    }

    /// Kill the child process.
    pub fn kill(&self) -> Result<()> {
        self.signal(libc::SIGKILL)
    }
}

#[cfg(unix)]
impl AsyncRead for AsyncPty {
    #[allow(unsafe_code)]
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        loop {
            let mut guard = match self.inner.poll_read_ready(cx) {
                Poll::Ready(Ok(guard)) => guard,
                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                Poll::Pending => return Poll::Pending,
            };

            let fd = *self.inner.get_ref();
            let unfilled = buf.initialize_unfilled();

            // SAFETY: fd is a valid file descriptor, unfilled is a valid buffer.
            let result = unsafe {
                libc::read(
                    fd,
                    unfilled.as_mut_ptr().cast::<libc::c_void>(),
                    unfilled.len(),
                )
            };

            if result >= 0 {
                buf.advance(result as usize);
                return Poll::Ready(Ok(()));
            }

            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::WouldBlock {
                guard.clear_ready();
                continue;
            }
            return Poll::Ready(Err(err));
        }
    }
}

#[cfg(unix)]
impl AsyncWrite for AsyncPty {
    #[allow(unsafe_code)]
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        loop {
            let mut guard = match self.inner.poll_write_ready(cx) {
                Poll::Ready(Ok(guard)) => guard,
                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                Poll::Pending => return Poll::Pending,
            };

            let fd = *self.inner.get_ref();

            // SAFETY: fd is a valid file descriptor, buf is a valid buffer.
            let result = unsafe { libc::write(fd, buf.as_ptr().cast::<libc::c_void>(), buf.len()) };

            if result >= 0 {
                return Poll::Ready(Ok(result as usize));
            }

            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::WouldBlock {
                guard.clear_ready();
                continue;
            }
            return Poll::Ready(Err(err));
        }
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        // PTY doesn't need explicit flushing
        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        // Shutdown is handled by Drop
        Poll::Ready(Ok(()))
    }
}

#[cfg(unix)]
impl Drop for AsyncPty {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        // SAFETY: The fd is valid and owned by us.
        unsafe {
            libc::close(*self.inner.get_ref());
        }
    }
}

#[cfg(unix)]
impl std::fmt::Debug for AsyncPty {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncPty")
            .field("fd", self.inner.get_ref())
            .field("pid", &self.pid)
            .field("dimensions", &self.dimensions)
            .finish()
    }
}

/// Async wrapper around Windows ConPTY for use with Tokio.
///
/// This wraps the rust-pty WindowsPtyMaster and provides the same interface
/// as the Unix AsyncPty for consistent cross-platform Session usage.
#[cfg(windows)]
pub struct WindowsAsyncPty {
    /// The underlying Windows PTY master.
    master: rust_pty::WindowsPtyMaster,
    /// The child process handle.
    child: rust_pty::WindowsPtyChild,
    /// Process ID.
    pid: u32,
    /// Terminal dimensions.
    dimensions: (u16, u16),
}

#[cfg(windows)]
impl WindowsAsyncPty {
    /// Create a new Windows async PTY wrapper from a WindowsPtyHandle.
    ///
    /// Takes ownership of the handle.
    pub fn from_handle(handle: WindowsPtyHandle) -> Self {
        let pid = handle.child.pid();
        let dimensions = handle.dimensions;
        Self {
            master: handle.master,
            child: handle.child,
            pid,
            dimensions,
        }
    }

    /// Get the process ID.
    #[must_use]
    pub const fn pid(&self) -> u32 {
        self.pid
    }

    /// Get the terminal dimensions.
    #[must_use]
    pub const fn dimensions(&self) -> (u16, u16) {
        self.dimensions
    }

    /// Resize the terminal.
    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
        use rust_pty::{PtyMaster, WindowSize};
        let size = WindowSize::new(cols, rows);
        self.master
            .resize(size)
            .map_err(|e| ExpectError::Io(io::Error::other(format!("resize failed: {e}"))))?;
        self.dimensions = (cols, rows);
        Ok(())
    }

    /// Check if the child process is still running.
    #[must_use]
    pub fn is_running(&self) -> bool {
        self.child.is_running()
    }

    /// Kill the child process.
    pub fn kill(&mut self) -> Result<()> {
        self.child
            .kill()
            .map_err(|e| ExpectError::Io(io::Error::other(format!("kill failed: {e}"))))
    }
}

#[cfg(windows)]
impl AsyncRead for WindowsAsyncPty {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        // Delegate to the underlying WindowsPtyMaster which implements AsyncRead
        Pin::new(&mut self.master).poll_read(cx, buf)
    }
}

#[cfg(windows)]
impl AsyncWrite for WindowsAsyncPty {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.master).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.master).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.master).poll_shutdown(cx)
    }
}

#[cfg(windows)]
impl std::fmt::Debug for WindowsAsyncPty {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowsAsyncPty")
            .field("pid", &self.pid)
            .field("dimensions", &self.dimensions)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pty_config_default() {
        let config = PtyConfig::default();
        assert_eq!(config.dimensions.0, 80);
        assert_eq!(config.dimensions.1, 24);
        assert_eq!(config.env_mode, EnvMode::Inherit);
    }

    #[test]
    fn pty_config_from_session() {
        let session_config = SessionConfig {
            dimensions: (120, 40),
            ..Default::default()
        };

        let pty_config = PtyConfig::from(&session_config);
        assert_eq!(pty_config.dimensions.0, 120);
        assert_eq!(pty_config.dimensions.1, 40);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn spawn_rejects_null_byte_in_command() {
        let spawner = PtySpawner::new();
        let result = spawner.spawn("test\0command", &[]).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("null byte"),
            "Expected error about null byte, got: {err_str}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn spawn_rejects_null_byte_in_args() {
        let spawner = PtySpawner::new();
        let result = spawner
            .spawn("/bin/echo", &["hello\0world".to_string()])
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("null byte"),
            "Expected error about null byte, got: {err_str}"
        );
    }
}