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
#![cfg(windows)] extern crate kernel32; extern crate winapi; use kernel32::*; use winapi::*; use std::borrow::Cow; use std::io::{self, Read, Write}; use std::os::windows::prelude::*; use std::path::Path; use std::ffi::OsString; #[derive(Debug)] pub struct PipeStream { server_half: bool, handle: Handle, } impl PipeStream { 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>>(); let _ = unsafe { WaitNamedPipeW(u16_slice.as_ptr(), 0) }; 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) } else { Err(io::Error::last_os_error()) } } pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<PipeStream> { let handle = PipeStream::create_pipe(path.as_ref())?; Ok(PipeStream { handle: Handle { inner: handle }, server_half: false, }) } } impl Drop for PipeStream { fn drop(&mut self) { let _ = unsafe { FlushFileBuffers(self.handle.inner) }; if self.server_half { let _ = unsafe { DisconnectNamedPipe(self.handle.inner) }; } } } impl Read for PipeStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut bytes_read = 0; let ok = unsafe { ReadFile(self.handle.inner, 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)), _ => panic!(""), } } } } impl Write for PipeStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut bytes_written = 0; let ok = unsafe { WriteFile(self.handle.inner, buf.as_ptr() as LPCVOID, buf.len() as DWORD, &mut bytes_written, std::ptr::null_mut()) }; if ok != 0 { Ok(bytes_written as usize) } else { Err(io::Error::last_os_error()) } } fn flush(&mut self) -> io::Result<()> { let ok = unsafe { FlushFileBuffers(self.handle.inner) }; if ok != 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } } impl AsRawHandle for PipeStream { fn as_raw_handle(&self) -> RawHandle { self.handle.inner } } impl IntoRawHandle for PipeStream { fn into_raw_handle(self) -> RawHandle { self.handle.inner } } impl FromRawHandle for PipeStream { unsafe fn from_raw_handle(handle: RawHandle) -> Self { PipeStream { handle: Handle { inner: handle }, server_half: false, } } } #[derive(Debug)] pub struct PipeListener<'a> { path: Cow<'a, Path>, next_pipe: Handle, } impl<'a> PipeListener<'a> { fn create_pipe(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 mut access_flags = PIPE_ACCESS_DUPLEX; if first { access_flags |= FILE_FLAG_FIRST_PIPE_INSTANCE; } 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 { inner: handle }) } else { Err(io::Error::last_os_error()) } } fn connect_pipe(handle: &Handle) -> io::Result<()> { let result = unsafe { ConnectNamedPipe(handle.inner, std::ptr::null_mut()) }; if result != 0 { Ok(()) } else { match io::Error::last_os_error().raw_os_error().map(|x| x as u32) { Some(ERROR_PIPE_CONNECTED) => Ok(()), Some(err) => Err(io::Error::from_raw_os_error(err as i32)), _ => panic!(""), } } } pub fn bind<P: Into<Cow<'a, Path>>>(path: P) -> io::Result<Self> { let path = path.into(); let handle = PipeListener::create_pipe(&path, true)?; Ok(PipeListener { path: path, next_pipe: handle, }) } pub fn accept(&mut self) -> io::Result<PipeStream> { let handle = std::mem::replace(&mut self.next_pipe, PipeListener::create_pipe(&self.path, false)?); PipeListener::connect_pipe(&handle)?; Ok(PipeStream { handle: handle, server_half: true, }) } pub fn incoming<'b>(&'b mut self) -> Incoming<'b, 'a> { Incoming { listener: self } } } pub struct Incoming<'a, 'b> where 'b: 'a { listener: &'a mut PipeListener<'b>, } impl<'a, 'b> IntoIterator for &'a mut PipeListener<'b> { type Item = io::Result<PipeStream>; type IntoIter = Incoming<'a, 'b>; fn into_iter(self) -> Incoming<'a, 'b> { self.incoming() } } impl<'a, 'b> Iterator for Incoming<'a, 'b> { type Item = io::Result<PipeStream>; fn next(&mut self) -> Option<Self::Item> { Some(self.listener.accept()) } } #[cfg(test)] mod test { use std::thread; use super::*; macro_rules! or_panic { ($e:expr) => { match $e { Ok(e) => e, Err(e) => { panic!("{}", e); }, } } } #[test] fn basic() { let socket_path = Path::new("//./pipe/basicsock"); println!("{:?}", socket_path); let msg1 = b"hello"; let msg2 = b"world!"; let mut listener = or_panic!(PipeListener::bind(socket_path)); let thread = thread::spawn(move || { let mut stream = or_panic!(listener.accept()); let mut buf = [0; 5]; or_panic!(stream.read(&mut buf)); assert_eq!(&msg1[..], &buf[..]); or_panic!(stream.write_all(msg2)); }); let mut stream = or_panic!(PipeStream::connect(socket_path)); or_panic!(stream.write_all(msg1)); let mut buf = vec![]; or_panic!(stream.read_to_end(&mut buf)); assert_eq!(&msg2[..], &buf[..]); drop(stream); thread.join().unwrap(); } #[test] fn iter() { let socket_path = Path::new("//./pipe/itersock"); let mut listener = or_panic!(PipeListener::bind(socket_path)); let thread = thread::spawn(move || for stream in listener.incoming().take(2) { let mut stream = or_panic!(stream); let mut buf = [0]; or_panic!(stream.read(&mut buf)); }); for _ in 0..2 { let mut stream = or_panic!(PipeStream::connect(socket_path)); or_panic!(stream.write_all(&[0])); } thread.join().unwrap(); } } #[derive(Debug)] struct Handle { inner: HANDLE, } impl Drop for Handle { fn drop(&mut self) { let _ = unsafe { CloseHandle(self.inner) }; } } unsafe impl Sync for Handle {} unsafe impl Send for Handle {}