winpipe2serial 0.1.0

Utility to link a windows named pipe to a serial COM port
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
use std::ffi::OsStr;
use std::io;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::ptr;

use clap::Parser;
use std::io::Write;
use std::thread;
use winapi::ctypes::c_void;
use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE};
use winapi::shared::ntdef::NULL;
use winapi::shared::winerror::ERROR_IO_PENDING;
use winapi::shared::winerror::ERROR_PIPE_BUSY;
use winapi::um::commapi::{SetCommState, SetCommTimeouts};
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::fileapi::{CreateFileW, ReadFile, WriteFile, OPEN_EXISTING};
use winapi::um::handleapi::{CloseHandle, DuplicateHandle, INVALID_HANDLE_VALUE};
use winapi::um::ioapiset::GetOverlappedResult;
use winapi::um::minwinbase::OVERLAPPED;
use winapi::um::namedpipeapi::{SetNamedPipeHandleState, WaitNamedPipeW};
use winapi::um::processthreadsapi::GetCurrentProcess;
use winapi::um::synchapi::CreateEventW;
use winapi::um::winbase::{
    CBR_115200, COMMTIMEOUTS, DCB, FILE_FLAG_OVERLAPPED, NOPARITY, ONESTOPBIT,
};
use winapi::um::winbase::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_WRITE_THROUGH};
use winapi::um::winbase::{PIPE_READMODE_BYTE, PIPE_WAIT};
use winapi::um::winnt::{DUPLICATE_SAME_ACCESS, GENERIC_READ, GENERIC_WRITE, HANDLE};

#[derive(Parser, Debug)]
struct Args {
    /// COM port name. Example --com COM1
    #[arg(short, long)]
    com: String,

    /// pipe name. If the pipe is \\.\pipe\PipeDream, give --pipe PipeDream
    #[arg(short, long)]
    pipe: String,

    /// Baud rate. Example --speed 9600
    #[arg(short, long, default_value_t = CBR_115200)]
    speed: u32,

    /// Byte size
    #[arg(short, long, default_value_t = 8)]
    bytes: u8,

    /// Stop bits
    #[arg(short = 't', long, default_value_t = ONESTOPBIT)]
    stop: u8,

    /// Parity
    #[arg(short = 'i', long, default_value_t = NOPARITY)]
    parity: u8,

    /// Verbose will print messages to and from the COM port
    #[arg(short, long, default_value_t = false)]
    verbose: bool,
}

enum WhichHandle {
    Pipe,
    Serial,
}

pub struct Pipe2Serial {
    comdev: HANDLE,
    comevent: HANDLE,
    pipedev: HANDLE,
    pipeevent: HANDLE,
}

// Windows HANDLEs can be sent across threads
unsafe impl Send for Pipe2Serial {}
unsafe impl Sync for Pipe2Serial {}

impl Pipe2Serial {
    fn open(args: &Args) -> io::Result<Self> {
        let mut port_name_utf16 = Vec::<u16>::new();
        port_name_utf16.extend(OsStr::new("\\\\.\\").encode_wide());
        port_name_utf16.extend(OsStr::new(&args.com).encode_wide());
        port_name_utf16.push(0);

        let comdev = unsafe {
            CreateFileW(
                port_name_utf16.as_ptr(),
                GENERIC_READ | GENERIC_WRITE,
                0,
                ptr::null_mut(),
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
                ptr::null_mut(),
            )
        };
        if comdev == INVALID_HANDLE_VALUE {
            return Err(io::Error::last_os_error());
        }
        let comevent = unsafe { CreateEventW(ptr::null_mut(), FALSE, FALSE, ptr::null_mut()) };
        if comevent == NULL {
            _ = unsafe { CloseHandle(comdev) };
            return Err(io::Error::last_os_error());
        }
        let mut dcb: DCB = unsafe { mem::zeroed() };
        dcb.DCBlength = mem::size_of::<DCB>() as u32;
        dcb.set_fBinary(TRUE as u32);
        dcb.BaudRate = args.speed;
        dcb.ByteSize = args.bytes;
        dcb.StopBits = args.stop;
        dcb.Parity = args.parity;
        if unsafe { SetCommState(comdev, &mut dcb) } == FALSE {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            return Err(io::Error::last_os_error());
        }

        // What on earth is this microsoft !? One needs to read the doc a dozen times
        // to understand what the hell this means. Right now the setting of "1" below
        // means that if we get one byte, wait one more millisecond for the next byte
        // and if the next byte doesnt come in the next 1msec just return that byte.
        // I dont need any wait-for-next-byte, so ideally I would expect a zero as the
        // setting for that, but no, zero means "wait indefinitely". Wierd
        let mut timeouts = COMMTIMEOUTS {
            ReadIntervalTimeout: 1,
            ReadTotalTimeoutMultiplier: 0,
            ReadTotalTimeoutConstant: 0,
            WriteTotalTimeoutMultiplier: 0,
            WriteTotalTimeoutConstant: 0,
        };
        if unsafe { SetCommTimeouts(comdev, &mut timeouts) } == FALSE {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            return Err(io::Error::last_os_error());
        }

        let mut pipe_name_utf16 = Vec::<u16>::new();
        pipe_name_utf16.extend(OsStr::new("\\\\.\\pipe\\").encode_wide());
        pipe_name_utf16.extend(OsStr::new(&args.pipe).encode_wide());
        pipe_name_utf16.push(0);

        let pipedev = loop {
            let pipedev = unsafe {
                CreateFileW(
                    pipe_name_utf16.as_ptr(),
                    GENERIC_READ | GENERIC_WRITE,
                    0,
                    ptr::null_mut(),
                    OPEN_EXISTING,
                    FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
                    ptr::null_mut(),
                )
            };
            if pipedev != INVALID_HANDLE_VALUE {
                break pipedev;
            }

            let err = unsafe { GetLastError() };
            if err != ERROR_PIPE_BUSY {
                println!("Could not open pipe, error {err:}");
                break INVALID_HANDLE_VALUE;
            }

            if unsafe { WaitNamedPipeW(pipe_name_utf16.as_ptr(), 20000) } == FALSE {
                let err = unsafe { GetLastError() };
                println!("Could not open pipe: 20 second wait timed out, {err:}");
                break INVALID_HANDLE_VALUE;
            }
        };
        if pipedev == INVALID_HANDLE_VALUE {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            return Err(io::Error::last_os_error());
        }
        let pipeevent = unsafe { CreateEventW(ptr::null_mut(), FALSE, FALSE, ptr::null_mut()) };
        if pipeevent == NULL {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            _ = unsafe { CloseHandle(pipedev) };
            return Err(io::Error::last_os_error());
        }
        let mut dw_mode: DWORD = PIPE_READMODE_BYTE | PIPE_WAIT;
        let res = unsafe {
            SetNamedPipeHandleState(pipedev, &mut dw_mode, ptr::null_mut(), ptr::null_mut())
        };
        if res == FALSE {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            _ = unsafe { CloseHandle(pipedev) };
            _ = unsafe { CloseHandle(pipeevent) };
            return Err(io::Error::last_os_error());
        }

        Ok(Self {
            comdev,
            comevent,
            pipedev,
            pipeevent,
        })
    }

    fn try_clone(&self) -> io::Result<Self> {
        let mut comdev = INVALID_HANDLE_VALUE;
        let process = unsafe { GetCurrentProcess() };
        let res = unsafe {
            DuplicateHandle(
                process,
                self.comdev,
                process,
                &mut comdev,
                0,
                FALSE,
                DUPLICATE_SAME_ACCESS,
            )
        };
        if res == FALSE {
            return Err(io::Error::last_os_error());
        }
        let comevent = unsafe { CreateEventW(ptr::null_mut(), FALSE, FALSE, ptr::null_mut()) };
        if comevent == NULL {
            _ = unsafe { CloseHandle(comdev) };
            return Err(io::Error::last_os_error());
        }

        let mut pipedev = INVALID_HANDLE_VALUE;
        let process = unsafe { GetCurrentProcess() };
        let res = unsafe {
            DuplicateHandle(
                process,
                self.pipedev,
                process,
                &mut pipedev,
                0,
                FALSE,
                DUPLICATE_SAME_ACCESS,
            )
        };
        if res == FALSE {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            return Err(io::Error::last_os_error());
        }
        let pipeevent = unsafe { CreateEventW(ptr::null_mut(), FALSE, FALSE, ptr::null_mut()) };
        if pipeevent == NULL {
            _ = unsafe { CloseHandle(comdev) };
            _ = unsafe { CloseHandle(comevent) };
            _ = unsafe { CloseHandle(pipedev) };
            return Err(io::Error::last_os_error());
        }

        Ok(Self {
            comdev,
            comevent,
            pipedev,
            pipeevent,
        })
    }

    fn read(&mut self, which: WhichHandle, buf: &mut [u8]) -> io::Result<usize> {
        let (handle, event) = match which {
            WhichHandle::Pipe => (self.pipedev, self.pipeevent),
            WhichHandle::Serial => (self.comdev, self.comevent),
        };
        let mut overlapped: OVERLAPPED = unsafe { mem::zeroed() };
        overlapped.hEvent = event;
        let res: BOOL = unsafe {
            ReadFile(
                handle,
                buf.as_mut_ptr() as *mut c_void,
                buf.len() as DWORD,
                ptr::null_mut(),
                &mut overlapped,
            )
        };
        // async read request may succeed immediately, queue successfully, or fail.
        // even if it returns TRUE, the number of bytes read should be retrieved via
        // GetOverlappedResult().
        if res == FALSE && unsafe { GetLastError() } != ERROR_IO_PENDING {
            return Err(io::Error::last_os_error());
        }
        let mut len: DWORD = 0;
        let res: BOOL =
            unsafe { GetOverlappedResult(self.comdev, &mut overlapped, &mut len, TRUE) };
        if res == FALSE {
            return Err(io::Error::last_os_error());
        }
        match len {
            0 if buf.len() == 0 => Ok(0),
            0 => Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "ReadFile() timed out (0 bytes read)",
            )),
            _ => Ok(len as usize),
        }
    }

    fn write(&mut self, which: WhichHandle, buf: &[u8]) -> io::Result<usize> {
        let (handle, event) = match which {
            WhichHandle::Pipe => (self.pipedev, self.pipeevent),
            WhichHandle::Serial => (self.comdev, self.comevent),
        };
        let mut overlapped: OVERLAPPED = unsafe { mem::zeroed() };
        overlapped.hEvent = event;
        let res: BOOL = unsafe {
            WriteFile(
                handle,
                buf.as_ptr() as *const c_void,
                buf.len() as DWORD,
                ptr::null_mut(),
                &mut overlapped,
            )
        };
        // async write request may succeed immediately, queue successfully, or fail.
        // even if it returns TRUE, the number of bytes written should be retrieved
        // via GetOverlappedResult().
        if res == FALSE && unsafe { GetLastError() } != ERROR_IO_PENDING {
            return Err(io::Error::last_os_error());
        }
        let mut len: DWORD = 0;
        let res: BOOL =
            unsafe { GetOverlappedResult(self.comdev, &mut overlapped, &mut len, TRUE) };
        if res == FALSE {
            return Err(io::Error::last_os_error());
        }
        match len {
            0 if buf.len() == 0 => Ok(0),
            0 => Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "WriteFile() timed out (0 bytes written)",
            )),
            _ => Ok(len as usize),
        }
    }
}

impl Drop for Pipe2Serial {
    fn drop(&mut self) {
        let _ = unsafe { CloseHandle(self.comdev) };
        let _ = unsafe { CloseHandle(self.pipedev) };
    }
}

fn main() {
    let args = Args::parse();
    let verbose = args.verbose;
    let mut p2s = Pipe2Serial::open(&args).expect("Opening COM/pipe failed");
    let mut p2s_clone = p2s.try_clone().expect("Cloning COM/pipe failed");

    thread::spawn(move || {
        let mut buf = [0u8; 4096];
        loop {
            let res = p2s.read(WhichHandle::Serial, &mut buf);
            match res {
                Ok(res) => {
                    if verbose {
                        if let Ok(buf_str) = std::str::from_utf8(&buf[0..res]) {
                            print!("{}", buf_str);
                            io::stdout().flush().ok();
                        }
                    }
                    let mut written = 0;
                    loop {
                        if written == res {
                            break;
                        }
                        match p2s.write(WhichHandle::Pipe, &buf[written..res]) {
                            Ok(wrote) => {
                                written += wrote;
                            }
                            Err(err) => println!("Error writing to pipe {err:}"),
                        }
                    }
                }
                Err(err) => println!("Error reading from serial {err:}"),
            }
        }
    });

    let mut buf = [0u8; 4096];
    loop {
        match p2s_clone.read(WhichHandle::Pipe, &mut buf) {
            Ok(res) => {
                if verbose {
                    if let Ok(buf_str) = std::str::from_utf8(&buf[0..res]) {
                        print!("{}", buf_str);
                        io::stdout().flush().ok();
                    }
                }
                let mut written = 0;
                loop {
                    if written == res {
                        break;
                    }
                    match p2s_clone.write(WhichHandle::Serial, &buf[written..res]) {
                        Ok(wrote) => {
                            written += wrote;
                        }
                        Err(err) => println!("Error writing to pipe {err:}"),
                    }
                }
            }
            Err(err) => println!("Error reading from pipe {err:}"),
        }
    }
}