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
use super::{Result, OnCleanup, Handle};
use std::path::Path;
use std::io::{self, Read, Write};
use std::os::windows::prelude::*;
use std::ffi::OsString;
use std::sync::Arc;
use winapi::
{
um::winbase::*,
um::fileapi::*,
um::handleapi::*,
um::namedpipeapi::*,
um::winnt::{GENERIC_READ, GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL},
shared::winerror::{ERROR_PIPE_NOT_CONNECTED, ERROR_NO_DATA},
shared::minwindef::{DWORD, LPCVOID, LPVOID}
};
#[cfg(feature="rand")]
use rand::{thread_rng, Rng, distributions::Alphanumeric};
/// Abstraction over a named pipe
#[derive(Debug, Clone)]
pub struct Pipe
{
handle: Option<Handle>,
pub(super) path: std::path::PathBuf,
}
impl Pipe
{
/// Open a pipe at an existing path. Note that this function is not
/// platform-agnostic as unix pipe paths and Windows pipe paths are are
/// formatted differently. The second parameter is unused on Windows.
pub fn open(path: &Path, _: OnCleanup) -> Result<Self>
{
Ok(Pipe
{
handle: None,
path: path.to_path_buf()
})
}
/// Open a pipe with the given name. Note that this is just a string name,
/// not a path.
pub fn with_name(name: &str) -> Result<Self>
{
let path_string = format!(r"\\.\pipe\{}", name);
Pipe::open(&Path::new(&path_string), OnCleanup::Delete)
}
/// Open a pipe with a randomly generated name.
#[cfg(feature="rand")]
pub fn create() -> Result<Self>
{
// Generate a random path name
let path_string = format!(r"\\.\pipe\pipe_{}_{}", std::process::id(),thread_rng()
.sample_iter(&Alphanumeric)
.take(15)
.collect::<String>());
Pipe::open(&Path::new(&path_string), OnCleanup::Delete)
}
/// Close a named pipe
pub fn close(self) -> Result<()>
{
if let Some(mut handle) = self.handle
{
if handle.handle_type() == HandleType::Server
{
if let Some(raw) = handle.raw()
{
unsafe
{
if DisconnectNamedPipe(raw) == 0
{
Err(io::Error::last_os_error())?;
}
}
}
// Server handles are disconnected when dropped, while client
// handles are not. This line prevents a double-disconnect.
handle.set_type(HandleType::Client);
}
}
Ok(())
}
/// Creates a new pipe handle
fn create_pipe(path: &Path) -> io::Result<Handle>
{
let mut os_str: OsString = path.as_os_str().into();
os_str.push("\x00");
let u16_slice = os_str.encode_wide().collect::<Vec<u16>>();
unsafe
{
while WaitNamedPipeW(u16_slice.as_ptr(), 0xffffffff) == 0
{
let error = io::Error::last_os_error();
match error.raw_os_error()
{
None => { break; }
Some(2) => {}
Some(_) => Err(error)?
}
}
}
let handle = unsafe
{
CreateFileW(u16_slice.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
0,
std::ptr::null_mut(),
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
std::ptr::null_mut())
};
if handle != INVALID_HANDLE_VALUE
{
Ok(Handle::Arc(Arc::new(handle), HandleType::Client))
}
else
{
Err(io::Error::last_os_error())
}
}
/// Creates a pipe listener
fn create_listener(path: &Path, first: bool) -> io::Result<Handle>
{
let mut os_str: OsString = path.as_os_str().into();
os_str.push("\x00");
let u16_slice = os_str.encode_wide().collect::<Vec<u16>>();
let access_flags = if first
{
PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE
}
else
{
PIPE_ACCESS_DUPLEX
};
let handle = unsafe
{
CreateNamedPipeW(u16_slice.as_ptr(),
access_flags,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
65536,
65536,
50,
std::ptr::null_mut())
};
if handle != INVALID_HANDLE_VALUE
{
Ok(Handle::Arc(Arc::new(handle), HandleType::Server))
}
else
{
Err(io::Error::last_os_error())
}
}
/// Initializes the pipe for writing
fn init_writer(&mut self) -> Result<()>
{
if self.handle.is_none()
{
self.handle = Some(Pipe::create_pipe(&self.path)?);
}
Ok(())
}
}
impl std::io::Write for Pipe
{
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize>
{
self.init_writer()?;
let result = match &mut self.handle
{
None => unreachable!(),
Some(handle) => handle.write(bytes)
};
// Try again if pipe is closed
match result
{
Ok(r) => {return Ok(r);}
Err(e) if e.raw_os_error().unwrap() as u32 == ERROR_NO_DATA =>
{
self.handle = None;
self.init_writer()?;
match &mut self.handle
{
None => unreachable!(),
Some(handle) => handle.write(bytes)
}
}
Err(e) => { Err(e)? }
}
}
fn flush(&mut self) -> std::io::Result<()>
{
match &mut self.handle
{
None => self.init_writer().map_err(std::io::Error::from),
Some(handle) =>
{
handle.flush()?;
self.handle = None;
Ok(())
}
}
}
}
impl std::io::Read for Pipe
{
fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize>
{
loop
{
let handle = match &mut self.handle
{
None =>
{
let listener = Pipe::create_listener(&self.path, true)?;
// Unwrap is safe because handle was just created
if unsafe { ConnectNamedPipe(listener.raw().unwrap(), std::ptr::null_mut()) } == 0
{
match io::Error::last_os_error().raw_os_error().map(|x| x as u32)
{
Some(ERROR_PIPE_NOT_CONNECTED) => {},
Some(err) => Err(io::Error::from_raw_os_error(err as i32))?,
_ => unreachable!(),
}
}
self.handle = Some(listener);
self.handle.as_mut().unwrap()
}
Some(read_handle) =>
{
if let None = read_handle.raw()
{
let listener = Pipe::create_listener(&self.path, false)?;
// Unwrap is safe because handle was just created
if unsafe { ConnectNamedPipe(listener.raw().unwrap(), std::ptr::null_mut()) } == 0
{
match io::Error::last_os_error().raw_os_error().map(|x| x as u32)
{
Some(ERROR_PIPE_NOT_CONNECTED) => {},
Some(err) => Err(io::Error::from_raw_os_error(err as i32))?,
_ => unreachable!(),
}
}
self.handle = Some(listener);
self.handle.as_mut().unwrap()
}
else
{
read_handle
}
}
};
match handle.read(bytes)
{
Err(e) =>
{
if let Some(err) = e.raw_os_error()
{
if err as u32 != 109
{
Err(std::io::Error::from(e))?;
}
else
{
continue;
}
}
else
{
break Ok(0);
}
},
bytes_read => { break bytes_read; }
}
}
}
}
impl Read for Handle
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
{
if let Some(raw) = self.raw()
{
let mut bytes_read = 0;
let ok = unsafe
{
ReadFile(raw,
buf.as_mut_ptr() as LPVOID,
buf.len() as DWORD,
&mut bytes_read,
std::ptr::null_mut())
};
if ok != 0
{
Ok(bytes_read as usize)
}
else
{
match io::Error::last_os_error().raw_os_error().map(|x| x as u32)
{
Some(ERROR_PIPE_NOT_CONNECTED) => Ok(0),
Some(err) => Err(io::Error::from_raw_os_error(err as i32)),
_ => unreachable!(),
}
}
}
else
{
Ok(0)
}
}
}
impl Write for Handle
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize>
{
if let Some(raw) = self.raw()
{
let mut bytes_written = 0;
let status = unsafe
{
WriteFile(raw,
buf.as_ptr() as LPCVOID,
buf.len() as DWORD,
&mut bytes_written,
std::ptr::null_mut())
};
if status != 0
{
Ok(bytes_written as usize)
}
else
{
Err(io::Error::last_os_error())
}
}
else
{
Err(io::Error::from_raw_os_error(ERROR_PIPE_NOT_CONNECTED as i32))
}
}
fn flush(&mut self) -> io::Result<()>
{
if let Some(raw) = self.raw()
{
if unsafe { FlushFileBuffers(raw) } != 0
{
Ok(())
}
else
{
Err(io::Error::last_os_error())
}
}
else
{
Err(io::Error::from_raw_os_error(ERROR_PIPE_NOT_CONNECTED as i32))
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub(crate) enum HandleType
{
Server, Client
}
impl Drop for Handle
{
fn drop(&mut self)
{
if let Self::Arc(arc, ty) = self
{
let deref = **arc;
unsafe { FlushFileBuffers(deref); }
if *ty == HandleType::Server
{
unsafe { DisconnectNamedPipe(deref); }
}
unsafe { CloseHandle(deref); }
}
}
}