Debian Codegraph @

debian/rust-vendor/filedescriptor/src/windows.rs

raw
1 use crate::{
2 AsRawFileDescriptor, AsRawSocketDescriptor, Error, FileDescriptor, FromRawFileDescriptor,
3 FromRawSocketDescriptor, IntoRawFileDescriptor, IntoRawSocketDescriptor, OwnedHandle, Pipe,
4 Result, StdioDescriptor,
5 };
6 use std::io::{self, Error as IoError};
7 use std::os::windows::prelude::*;
8 use std::ptr;
9 use std::sync::Once;
10 use std::time::Duration;
11 use winapi::shared::ws2def::{AF_INET, INADDR_LOOPBACK, SOCKADDR_IN};
12 use winapi::um::fileapi::*;
13 use winapi::um::handleapi::*;
14 use winapi::um::minwinbase::SECURITY_ATTRIBUTES;
15 use winapi::um::namedpipeapi::{CreatePipe, GetNamedPipeInfo};
16 use winapi::um::processenv::{GetStdHandle, SetStdHandle};
17 use winapi::um::processthreadsapi::*;
18 use winapi::um::winbase::{FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE};
19 use winapi::um::winnt::HANDLE;
20 use winapi::um::winsock2::{
21 accept, bind, closesocket, connect, getsockname, getsockopt, htonl, ioctlsocket, listen, recv,
22 send, WSAGetLastError, WSAPoll, WSASocketW, WSAStartup, INVALID_SOCKET, SOCKET, SOCK_STREAM,
23 SOL_SOCKET, SO_ERROR, WSADATA, WSAENOTSOCK, WSA_FLAG_NO_HANDLE_INHERIT,
24 };
25 pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd};
26
27 /// `RawFileDescriptor` is a platform independent type alias for the
28 /// underlying platform file descriptor type. It is primarily useful
29 /// for avoiding using `cfg` blocks in platform independent code.
30 pub type RawFileDescriptor = RawHandle;
31
32 /// `SocketDescriptor` is a platform independent type alias for the
33 /// underlying platform socket descriptor type. It is primarily useful
34 /// for avoiding using `cfg` blocks in platform independent code.
35 pub type SocketDescriptor = SOCKET;
36
37 const STD_INPUT_HANDLE: u32 = 4294967286; // -10
38 const STD_OUTPUT_HANDLE: u32 = 4294967285; // -11
39 const STD_ERROR_HANDLE: u32 = 4294967284; // -12
40
41 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
42 pub(crate) enum HandleType {
43 Char,
44 Disk,
45 Pipe,
46 Socket,
47 Unknown,
48 }
49
50 impl Default for HandleType {
51 fn default() -> Self {
52 HandleType::Unknown
53 }
54 }
55
56 impl<T: AsRawHandle> AsRawFileDescriptor for T {
57 fn as_raw_file_descriptor(&self) -> RawFileDescriptor {
58 self.as_raw_handle()
59 }
60 }
61
62 impl<T: IntoRawHandle> IntoRawFileDescriptor for T {
63 fn into_raw_file_descriptor(self) -> RawFileDescriptor {
64 self.into_raw_handle()
65 }
66 }
67
68 impl<T: FromRawHandle> FromRawFileDescriptor for T {
69 unsafe fn from_raw_file_descriptor(handle: RawHandle) -> Self {
70 Self::from_raw_handle(handle)
71 }
72 }
73
74 impl<T: AsRawSocket> AsRawSocketDescriptor for T {
75 fn as_socket_descriptor(&self) -> SocketDescriptor {
76 self.as_raw_socket() as SocketDescriptor
77 }
78 }
79
80 impl<T: IntoRawSocket> IntoRawSocketDescriptor for T {
81 fn into_socket_descriptor(self) -> SocketDescriptor {
82 self.into_raw_socket() as SocketDescriptor
83 }
84 }
85
86 impl<T: FromRawSocket> FromRawSocketDescriptor for T {
87 unsafe fn from_socket_descriptor(handle: SocketDescriptor) -> Self {
88 Self::from_raw_socket(handle as _)
89 }
90 }
91
92 unsafe impl Send for OwnedHandle {}
93 unsafe impl Sync for OwnedHandle {}
94
95 impl OwnedHandle {
96 fn probe_handle_type_if_unknown(handle: RawHandle, handle_type: HandleType) -> HandleType {
97 match handle_type {
98 HandleType::Unknown => Self::probe_handle_type(handle),
99 t => t,
100 }
101 }
102
103 pub(crate) fn probe_handle_type(handle: RawHandle) -> HandleType {
104 let handle = handle as HANDLE;
105 match unsafe { GetFileType(handle) } {
106 FILE_TYPE_CHAR => HandleType::Char,
107 FILE_TYPE_DISK => HandleType::Disk,
108 FILE_TYPE_PIPE => {
109 // Could be a pipe or a socket. Test if for pipeness
110 let mut flags = 0;
111 let mut out_buf = 0;
112 let mut in_buf = 0;
113 let mut inst = 0;
114 if unsafe {
115 GetNamedPipeInfo(handle, &mut flags, &mut out_buf, &mut in_buf, &mut inst)
116 } != 0
117 {
118 HandleType::Pipe
119 } else {
120 // It's probably a socket, but it may be a special device used
121 // when piping between WSL and native win32 apps.
122 let mut err = 0;
123 let mut errsize = std::mem::size_of_val(&err) as _;
124 if unsafe {
125 getsockopt(
126 handle as _,
127 SOL_SOCKET,
128 SO_ERROR,
129 &mut err as *mut _ as *mut i8,
130 &mut errsize,
131 ) != 0
132 && WSAGetLastError() == WSAENOTSOCK
133 } {
134 HandleType::Pipe
135 } else {
136 HandleType::Socket
137 }
138 }
139 }
140 _ => HandleType::Unknown,
141 }
142 }
143
144 fn is_socket_handle(&self) -> bool {
145 match self.handle_type {
146 HandleType::Socket => true,
147 HandleType::Unknown => Self::probe_handle_type(self.handle) == HandleType::Socket,
148 _ => false,
149 }
150 }
151 }
152
153 impl Drop for OwnedHandle {
154 fn drop(&mut self) {
155 if self.handle != INVALID_HANDLE_VALUE as _ && !self.handle.is_null() {
156 unsafe {
157 if self.is_socket_handle() {
158 closesocket(self.handle as _);
159 } else {
160 CloseHandle(self.handle as _);
161 }
162 };
163 }
164 }
165 }
166
167 impl FromRawHandle for OwnedHandle {
168 unsafe fn from_raw_handle(handle: RawHandle) -> Self {
169 OwnedHandle {
170 handle,
171 handle_type: Self::probe_handle_type(handle),
172 }
173 }
174 }
175
176 impl OwnedHandle {
177 #[inline]
178 pub(crate) fn dup_impl<F: AsRawFileDescriptor>(f: &F, handle_type: HandleType) -> Result<Self> {
179 let handle = f.as_raw_file_descriptor();
180 if handle == INVALID_HANDLE_VALUE as _ || handle.is_null() {
181 return Ok(OwnedHandle {
182 handle,
183 handle_type,
184 });
185 }
186
187 let handle_type = Self::probe_handle_type_if_unknown(handle, handle_type);
188
189 let proc = unsafe { GetCurrentProcess() };
190 let mut duped = INVALID_HANDLE_VALUE;
191 let ok = unsafe {
192 DuplicateHandle(
193 proc,
194 handle as *mut _,
195 proc,
196 &mut duped,
197 0,
198 0, // not inheritable
199 winapi::um::winnt::DUPLICATE_SAME_ACCESS,
200 )
201 };
202 if ok == 0 {
203 Err(IoError::last_os_error().into())
204 } else {
205 Ok(OwnedHandle {
206 handle: duped as *mut _,
207 handle_type,
208 })
209 }
210 }
211 }
212
213 impl AsRawHandle for OwnedHandle {
214 fn as_raw_handle(&self) -> RawHandle {
215 self.handle
216 }
217 }
218
219 impl IntoRawHandle for OwnedHandle {
220 fn into_raw_handle(self) -> RawHandle {
221 let handle = self.handle;
222 std::mem::forget(self);
223 handle
224 }
225 }
226
227 impl FileDescriptor {
228 #[inline]
229 pub(crate) fn as_stdio_impl(&self) -> Result<std::process::Stdio> {
230 let duped = self.handle.try_clone()?;
231 let handle = duped.into_raw_handle();
232 let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) };
233 Ok(stdio)
234 }
235
236 #[inline]
237 pub(crate) fn as_file_impl(&self) -> Result<std::fs::File> {
238 let duped = self.handle.try_clone()?;
239 let handle = duped.into_raw_handle();
240 let stdio = unsafe { std::fs::File::from_raw_handle(handle) };
241 Ok(stdio)
242 }
243
244 #[inline]
245 pub(crate) fn set_non_blocking_impl(&mut self, non_blocking: bool) -> Result<()> {
246 if !self.handle.is_socket_handle() {
247 return Err(Error::OnlySocketsNonBlocking);
248 }
249
250 let mut on = if non_blocking { 1 } else { 0 };
251 let res = unsafe {
252 ioctlsocket(
253 self.as_raw_socket() as SOCKET,
254 winapi::um::winsock2::FIONBIO,
255 &mut on,
256 )
257 };
258 if res != 0 {
259 Err(Error::FionBio(std::io::Error::last_os_error()))
260 } else {
261 Ok(())
262 }
263 }
264
265 pub(crate) fn redirect_stdio_impl<F: AsRawFileDescriptor>(
266 f: &F,
267 stdio: StdioDescriptor,
268 ) -> Result<Self> {
269 let std_handle = match stdio {
270 StdioDescriptor::Stdin => STD_INPUT_HANDLE,
271 StdioDescriptor::Stdout => STD_OUTPUT_HANDLE,
272 StdioDescriptor::Stderr => STD_ERROR_HANDLE,
273 };
274
275 let raw_std_handle = unsafe { GetStdHandle(std_handle) } as *mut _;
276 let std_original = unsafe { FileDescriptor::from_raw_handle(raw_std_handle) };
277
278 let cloned_handle = OwnedHandle::dup(f)?;
279 if unsafe { SetStdHandle(std_handle, cloned_handle.into_raw_handle() as *mut _) } == 0 {
280 Err(Error::SetStdHandle(std::io::Error::last_os_error()))
281 } else {
282 Ok(std_original)
283 }
284 }
285 }
286
287 impl IntoRawHandle for FileDescriptor {
288 fn into_raw_handle(self) -> RawHandle {
289 self.handle.into_raw_handle()
290 }
291 }
292
293 impl AsRawHandle for FileDescriptor {
294 fn as_raw_handle(&self) -> RawHandle {
295 self.handle.as_raw_handle()
296 }
297 }
298
299 impl FromRawHandle for FileDescriptor {
300 unsafe fn from_raw_handle(handle: RawHandle) -> FileDescriptor {
301 Self {
302 handle: OwnedHandle::from_raw_handle(handle),
303 }
304 }
305 }
306
307 impl IntoRawSocket for FileDescriptor {
308 fn into_raw_socket(self) -> RawSocket {
309 // FIXME: this isn't a guaranteed conversion!
310 debug_assert!(self.handle.is_socket_handle());
311 self.handle.into_raw_handle() as RawSocket
312 }
313 }
314
315 impl AsRawSocket for FileDescriptor {
316 fn as_raw_socket(&self) -> RawSocket {
317 // FIXME: this isn't a guaranteed conversion!
318 debug_assert!(self.handle.is_socket_handle());
319 self.handle.as_raw_handle() as RawSocket
320 }
321 }
322
323 impl AsSocket for FileDescriptor {
324 fn as_socket(&self) -> BorrowedSocket {
325 unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
326 }
327 }
328
329 impl FromRawSocket for FileDescriptor {
330 unsafe fn from_raw_socket(handle: RawSocket) -> FileDescriptor {
331 Self {
332 handle: OwnedHandle::from_raw_handle(handle as RawHandle),
333 }
334 }
335 }
336
337 impl io::Read for FileDescriptor {
338 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
339 if self.handle.is_socket_handle() {
340 // It's important to use the winsock functions to read/write
341 // even though ReadFile and WriteFile technically work; only
342 // the winsock functions respect non-blocking mode.
343 let num_read = unsafe {
344 recv(
345 self.as_socket_descriptor(),
346 buf.as_mut_ptr() as *mut _,
347 buf.len() as _,
348 0,
349 )
350 };
351 if num_read < 0 {
352 Err(IoError::last_os_error())
353 } else {
354 Ok(num_read as usize)
355 }
356 } else {
357 let mut num_read = 0;
358 let ok = unsafe {
359 ReadFile(
360 self.handle.as_raw_handle() as *mut _,
361 buf.as_mut_ptr() as *mut _,
362 buf.len() as _,
363 &mut num_read,
364 ptr::null_mut(),
365 )
366 };
367 if ok == 0 {
368 let err = IoError::last_os_error();
369 if err.kind() == std::io::ErrorKind::BrokenPipe {
370 Ok(0)
371 } else {
372 Err(err)
373 }
374 } else {
375 Ok(num_read as usize)
376 }
377 }
378 }
379 }
380
381 impl io::Write for FileDescriptor {
382 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
383 if self.handle.is_socket_handle() {
384 let num_wrote = unsafe {
385 send(
386 self.as_socket_descriptor(),
387 buf.as_ptr() as *const _,
388 buf.len() as _,
389 0,
390 )
391 };
392 if num_wrote < 0 {
393 Err(IoError::last_os_error())
394 } else {
395 Ok(num_wrote as usize)
396 }
397 } else {
398 let mut num_wrote = 0;
399 let ok = unsafe {
400 WriteFile(
401 self.handle.as_raw_handle() as *mut _,
402 buf.as_ptr() as *const _,
403 buf.len() as u32,
404 &mut num_wrote,
405 ptr::null_mut(),
406 )
407 };
408 if ok == 0 {
409 Err(IoError::last_os_error())
410 } else {
411 Ok(num_wrote as usize)
412 }
413 }
414 }
415 fn flush(&mut self) -> std::io::Result<()> {
416 Ok(())
417 }
418 }
419
420 impl Pipe {
421 pub fn new() -> Result<Pipe> {
422 let mut sa = SECURITY_ATTRIBUTES {
423 nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
424 lpSecurityDescriptor: ptr::null_mut(),
425 bInheritHandle: 0,
426 };
427 let mut read: HANDLE = INVALID_HANDLE_VALUE as _;
428 let mut write: HANDLE = INVALID_HANDLE_VALUE as _;
429 if unsafe { CreatePipe(&mut read, &mut write, &mut sa, 0) } == 0 {
430 Err(Error::Pipe(IoError::last_os_error()))
431 } else {
432 Ok(Pipe {
433 read: FileDescriptor {
434 handle: OwnedHandle {
435 handle: read as _,
436 handle_type: HandleType::Pipe,
437 },
438 },
439 write: FileDescriptor {
440 handle: OwnedHandle {
441 handle: write as _,
442 handle_type: HandleType::Pipe,
443 },
444 },
445 })
446 }
447 }
448 }
449
450 fn init_winsock() {
451 static START: Once = Once::new();
452 START.call_once(|| unsafe {
453 let mut data: WSADATA = std::mem::zeroed();
454 let ret = WSAStartup(
455 0x202, // version 2.2
456 &mut data,
457 );
458 assert_eq!(ret, 0, "failed to initialize winsock");
459 });
460 }
461
462 fn socket(af: i32, sock_type: i32, proto: i32) -> Result<FileDescriptor> {
463 let s = unsafe {
464 WSASocketW(
465 af,
466 sock_type,
467 proto,
468 ptr::null_mut(),
469 0,
470 WSA_FLAG_NO_HANDLE_INHERIT,
471 )
472 };
473 if s == INVALID_SOCKET {
474 Err(Error::Socket(IoError::last_os_error()))
475 } else {
476 Ok(FileDescriptor {
477 handle: OwnedHandle {
478 handle: s as _,
479 handle_type: HandleType::Socket,
480 },
481 })
482 }
483 }
484
485 #[doc(hidden)]
486 pub fn socketpair_impl() -> Result<(FileDescriptor, FileDescriptor)> {
487 init_winsock();
488
489 let s = socket(AF_INET, SOCK_STREAM, 0)?;
490
491 let mut in_addr: SOCKADDR_IN = unsafe { std::mem::zeroed() };
492 in_addr.sin_family = AF_INET as _;
493 unsafe {
494 *in_addr.sin_addr.S_un.S_addr_mut() = htonl(INADDR_LOOPBACK);
495 }
496
497 unsafe {
498 if bind(
499 s.as_raw_handle() as _,
500 std::mem::transmute(&in_addr),
501 std::mem::size_of_val(&in_addr) as _,
502 ) != 0
503 {
504 return Err(Error::Bind(IoError::last_os_error()));
505 }
506 }
507
508 let mut addr_len = std::mem::size_of_val(&in_addr) as i32;
509
510 unsafe {
511 if getsockname(
512 s.as_raw_handle() as _,
513 std::mem::transmute(&mut in_addr),
514 &mut addr_len,
515 ) != 0
516 {
517 return Err(Error::Getsockname(IoError::last_os_error()));
518 }
519 }
520
521 unsafe {
522 if listen(s.as_raw_handle() as _, 1) != 0 {
523 return Err(Error::Listen(IoError::last_os_error()));
524 }
525 }
526
527 let client = socket(AF_INET, SOCK_STREAM, 0)?;
528
529 unsafe {
530 if connect(
531 client.as_raw_handle() as _,
532 std::mem::transmute(&in_addr),
533 addr_len,
534 ) != 0
535 {
536 return Err(Error::Connect(IoError::last_os_error()));
537 }
538 }
539
540 let server = unsafe { accept(s.as_raw_handle() as _, ptr::null_mut(), ptr::null_mut()) };
541 if server == INVALID_SOCKET {
542 return Err(Error::Accept(IoError::last_os_error()));
543 }
544 let server = FileDescriptor {
545 handle: OwnedHandle {
546 handle: server as _,
547 handle_type: HandleType::Socket,
548 },
549 };
550
551 Ok((server, client))
552 }
553
554 #[doc(hidden)]
555 pub fn poll_impl(pfd: &mut [pollfd], duration: Option<Duration>) -> Result<usize> {
556 let poll_result = unsafe {
557 WSAPoll(
558 pfd.as_mut_ptr(),
559 pfd.len() as _,
560 duration
561 .map(|wait| wait.as_millis() as libc::c_int)
562 .unwrap_or(-1),
563 )
564 };
565 if poll_result < 0 {
566 Err(std::io::Error::last_os_error().into())
567 } else {
568 Ok(poll_result as usize)
569 }
570 }
571
572 #[cfg(test)]
573 mod test {
574 use std::io::{Read, Write};
575
576 #[test]
577 fn socketpair() {
578 let (mut a, mut b) = super::socketpair_impl().unwrap();
579 a.write_all(b"hello").unwrap();
580 let mut buf = [0u8; 5];
581 assert_eq!(b.read(&mut buf).unwrap(), 5);
582 assert_eq!(&buf, b"hello");
583 }
584 }