windows-erg 0.1.0

Ergonomic, idiomatic Rust wrappers for Windows APIs
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
use std::borrow::Cow;
use std::io;
use std::path::PathBuf;
use std::time::Duration;

use windows::Win32::Foundation::{
    ERROR_IO_PENDING, ERROR_OPERATION_ABORTED, ERROR_PIPE_CONNECTED, GetLastError, WAIT_FAILED,
    WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows::Win32::Storage::FileSystem::{
    FILE_FLAG_OVERLAPPED, FILE_FLAGS_AND_ATTRIBUTES, PIPE_ACCESS_DUPLEX, PIPE_ACCESS_INBOUND,
    PIPE_ACCESS_OUTBOUND, ReadFile, WriteFile,
};
use windows::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED};
use windows::Win32::System::Pipes::{
    ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, GetNamedPipeClientProcessId,
    NAMED_PIPE_MODE, PIPE_READMODE_BYTE, PIPE_READMODE_MESSAGE, PIPE_REJECT_REMOTE_CLIENTS,
    PIPE_TYPE_BYTE, PIPE_TYPE_MESSAGE, PIPE_UNLIMITED_INSTANCES, PIPE_WAIT,
};
use windows::Win32::System::Threading::WaitForMultipleObjects;
use windows::core::PCWSTR;

use crate::error::{
    AccessDeniedError, InvalidParameterError, PipeConnectError, PipeError, PipeTimeoutError,
};
use crate::process::{Process, ProcessId};
use crate::utils::to_utf16_nul;
use crate::wait::Wait;
use crate::{Error, Result};

use super::error_map::map_pipe_windows_error;
use super::security_attrs::NativePipeSecurityAttributes;
use super::types::{
    NamedPipeOpenMode, NamedPipeType, PipeName, PipeSecurityOptions, PipeServerEndpoint,
};

/// Builder for creating a named pipe server configuration.
#[derive(Debug, Clone)]
pub struct NamedPipeServerBuilder {
    pipe_name: Option<PipeName>,
    open_mode: NamedPipeOpenMode,
    pipe_type: NamedPipeType,
    max_instances: u8,
    out_buffer_size: u32,
    in_buffer_size: u32,
    default_timeout: Duration,
    security: PipeSecurityOptions,
    allowed_executables: Vec<PathBuf>,
}

impl NamedPipeServerBuilder {
    /// Create a new named pipe server builder.
    pub fn new() -> Self {
        Self {
            pipe_name: None,
            open_mode: NamedPipeOpenMode::Duplex,
            pipe_type: NamedPipeType::Byte,
            max_instances: 1,
            out_buffer_size: 4096,
            in_buffer_size: 4096,
            default_timeout: Duration::from_secs(5),
            security: PipeSecurityOptions::default(),
            allowed_executables: Vec::new(),
        }
    }

    /// Set the named pipe path.
    pub fn pipe_name(mut self, pipe_name: PipeName) -> Self {
        self.pipe_name = Some(pipe_name);
        self
    }

    /// Set the open direction.
    pub fn open_mode(mut self, open_mode: NamedPipeOpenMode) -> Self {
        self.open_mode = open_mode;
        self
    }

    /// Set byte/message semantics.
    pub fn pipe_type(mut self, pipe_type: NamedPipeType) -> Self {
        self.pipe_type = pipe_type;
        self
    }

    /// Set number of server instances for this pipe name.
    pub fn max_instances(mut self, max_instances: u8) -> Self {
        self.max_instances = max_instances;
        self
    }

    /// Set outbound buffer size.
    pub fn out_buffer_size(mut self, out_buffer_size: u32) -> Self {
        self.out_buffer_size = out_buffer_size;
        self
    }

    /// Set inbound buffer size.
    pub fn in_buffer_size(mut self, in_buffer_size: u32) -> Self {
        self.in_buffer_size = in_buffer_size;
        self
    }

    /// Set default timeout.
    pub fn default_timeout(mut self, default_timeout: Duration) -> Self {
        self.default_timeout = default_timeout;
        self
    }

    /// Set raw security options.
    pub fn security(mut self, security: PipeSecurityOptions) -> Self {
        self.security = security;
        self
    }

    /// Restrict connections to processes whose executable path matches one of the given paths.
    ///
    /// The comparison is case-insensitive. If no paths are added (the default), all processes
    /// are allowed to connect.
    pub fn allow_executable(mut self, path: impl Into<PathBuf>) -> Self {
        self.allowed_executables.push(path.into());
        self
    }

    /// Remove a previously added executable path from the allow-list.
    ///
    /// The comparison is case-insensitive. Does nothing if the path is not present.
    pub fn remove_executable(mut self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        self.allowed_executables.retain(|p| {
            !p.as_os_str()
                .to_string_lossy()
                .eq_ignore_ascii_case(&path.as_os_str().to_string_lossy())
        });
        self
    }

    /// Build a named pipe server configuration.
    pub fn build(self) -> Result<NamedPipeServerConfig> {
        let pipe_name = self.pipe_name.ok_or_else(|| {
            Error::InvalidParameter(InvalidParameterError::new(
                "pipe_name",
                "Pipe name must be specified",
            ))
        })?;

        if self.max_instances == 0 {
            return Err(Error::InvalidParameter(InvalidParameterError::new(
                "max_instances",
                "max_instances must be at least 1",
            )));
        }

        Ok(NamedPipeServerConfig {
            pipe_name,
            open_mode: self.open_mode,
            pipe_type: self.pipe_type,
            max_instances: self.max_instances,
            out_buffer_size: self.out_buffer_size,
            in_buffer_size: self.in_buffer_size,
            default_timeout: self.default_timeout,
            security: self.security,
            allowed_executables: self.allowed_executables,
        })
    }
}

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

/// Named pipe server runtime configuration.
#[derive(Debug)]
pub struct NamedPipeServerConfig {
    pipe_name: PipeName,
    open_mode: NamedPipeOpenMode,
    pipe_type: NamedPipeType,
    max_instances: u8,
    out_buffer_size: u32,
    in_buffer_size: u32,
    default_timeout: Duration,
    security: PipeSecurityOptions,
    allowed_executables: Vec<PathBuf>,
}

impl NamedPipeServerConfig {
    /// Create a new builder.
    pub fn builder() -> NamedPipeServerBuilder {
        NamedPipeServerBuilder::new()
    }

    /// Create a named pipe server instance.
    pub fn create(&self) -> Result<NamedPipeServer> {
        let name_wide = to_utf16_nul(self.pipe_name.as_str());
        let open_mode = to_server_open_mode(self.open_mode);
        let pipe_mode = to_pipe_mode(self.pipe_type);
        let max_instances = if self.max_instances == u8::MAX {
            PIPE_UNLIMITED_INSTANCES
        } else {
            self.max_instances as u32
        };

        let default_timeout_ms = self.default_timeout.as_millis().min(u32::MAX as u128) as u32;
        let security_attributes =
            NativePipeSecurityAttributes::from_options(&self.security, self.pipe_name.as_str())?;

        let raw_handle = unsafe {
            CreateNamedPipeW(
                PCWSTR(name_wide.as_ptr()),
                open_mode,
                pipe_mode,
                max_instances,
                self.out_buffer_size,
                self.in_buffer_size,
                default_timeout_ms,
                security_attributes.as_option_ptr(),
            )
        };

        if raw_handle.is_invalid() {
            let code = unsafe { GetLastError().0 as i32 };
            return Err(map_pipe_windows_error(
                "create",
                Some(&self.pipe_name),
                code,
            ));
        }

        Ok(NamedPipeServer {
            endpoint: PipeServerEndpoint::from_raw(
                raw_handle,
                true,
                self.pipe_name.clone(),
                self.open_mode,
                self.pipe_type,
            ),
            default_timeout: self.default_timeout,
            allowed_executables: self.allowed_executables.clone(),
        })
    }

    /// Return pipe name.
    pub fn pipe_name(&self) -> &PipeName {
        &self.pipe_name
    }

    /// Return open mode.
    pub fn open_mode(&self) -> NamedPipeOpenMode {
        self.open_mode
    }

    /// Return pipe type.
    pub fn pipe_type(&self) -> NamedPipeType {
        self.pipe_type
    }

    /// Return configured max instances.
    pub fn max_instances(&self) -> u8 {
        self.max_instances
    }

    /// Return configured outbound buffer size.
    pub fn out_buffer_size(&self) -> u32 {
        self.out_buffer_size
    }

    /// Return configured inbound buffer size.
    pub fn in_buffer_size(&self) -> u32 {
        self.in_buffer_size
    }

    /// Return default timeout.
    pub fn default_timeout(&self) -> Duration {
        self.default_timeout
    }

    /// Return security options.
    pub fn security(&self) -> PipeSecurityOptions {
        self.security.clone()
    }
}

/// A connected or connectable named pipe server instance.
#[derive(Debug)]
pub struct NamedPipeServer {
    endpoint: PipeServerEndpoint,
    default_timeout: Duration,
    allowed_executables: Vec<PathBuf>,
}

impl NamedPipeServer {
    /// Return the underlying endpoint.
    pub fn endpoint(&self) -> &PipeServerEndpoint {
        &self.endpoint
    }

    /// Return the configured default timeout.
    pub fn default_timeout(&self) -> Duration {
        self.default_timeout
    }

    /// Add an executable path to the allow-list.
    ///
    /// The comparison is case-insensitive. If no paths are in the allow-list (the default),
    /// all processes are allowed to connect.
    pub fn allow_executable(&mut self, path: impl Into<PathBuf>) {
        self.allowed_executables.push(path.into());
    }

    /// Remove an executable path from the allow-list.
    ///
    /// The comparison is case-insensitive. Does nothing if the path is not present.
    pub fn remove_executable(&mut self, path: impl Into<PathBuf>) {
        let path = path.into();
        self.allowed_executables.retain(|p| {
            !p.as_os_str()
                .to_string_lossy()
                .eq_ignore_ascii_case(&path.as_os_str().to_string_lossy())
        });
    }

    /// Block until a client connects to this instance.
    ///
    /// If an executable allow-list was configured via [`NamedPipeServerBuilder::allow_executable`],
    /// the connecting process's image path is checked against the list. If it does not match,
    /// the connection is immediately disconnected and an [`Error::AccessDenied`] error is returned.
    /// An empty allow-list (the default) permits all processes to connect.
    pub fn connect(&self) -> Result<()> {
        let result = unsafe { ConnectNamedPipe(self.endpoint.raw_handle(), None) };
        if result.is_err() {
            let code = unsafe { GetLastError().0 as i32 };
            if code != ERROR_PIPE_CONNECTED.0 as i32 {
                return Err(map_pipe_windows_error(
                    "connect",
                    Some(self.endpoint.pipe_name()),
                    code,
                ));
            }
        }

        self.validate_connected_client()?;
        Ok(())
    }

    /// Block until a client connects to this instance or the timeout elapses.
    ///
    /// This method returns [`Error::Pipe(PipeError::Timeout)`] if no client connection is
    /// completed within the provided timeout.
    pub fn connect_with_timeout(&self, timeout: Duration) -> Result<()> {
        let wait = Wait::manual_reset(false)?;
        self.connect_with_wait_timeout(&wait, timeout)
    }

    /// Block until a client connects or an external wait handle is signaled
    ///
    /// If `wait` is signaled first, this method cancels the pending connect operation and
    /// returns [`Error::Pipe(PipeError::Connect)`] with interruption context.
    pub fn connect_with_wait(&self, wait: &Wait) -> Result<()> {
        self.connect_with_wait_timeout(wait, Duration::MAX)
    }

    /// Block until a client connects, an external wait handle is signaled, or timeout elapses.
    ///
    /// If `wait` is signaled first, this method cancels the pending connect operation and
    /// returns [`Error::Pipe(PipeError::Connect)`] with interruption context.
    pub fn connect_with_wait_timeout(&self, wait: &Wait, timeout: Duration) -> Result<()> {
        let connect_event = Wait::manual_reset(false)?;
        let mut overlapped = OVERLAPPED {
            hEvent: connect_event.raw_handle(),
            ..Default::default()
        };

        let mut connect_code: Option<i32> = None;
        let result = unsafe { ConnectNamedPipe(self.endpoint.raw_handle(), Some(&mut overlapped)) };
        if result.is_err() {
            let code = unsafe { GetLastError().0 as i32 };
            connect_code = Some(code);
            if code != ERROR_IO_PENDING.0 as i32 && code != ERROR_PIPE_CONNECTED.0 as i32 {
                return Err(map_pipe_windows_error(
                    "connect",
                    Some(self.endpoint.pipe_name()),
                    code,
                ));
            }
        }

        if result.is_ok() || connect_code == Some(ERROR_PIPE_CONNECTED.0 as i32) {
            self.validate_connected_client()?;
            return Ok(());
        }

        let handles = [connect_event.raw_handle(), wait.raw_handle()];
        let wait_result =
            unsafe { WaitForMultipleObjects(&handles, false, duration_to_wait_ms(timeout)) };

        if wait_result == WAIT_OBJECT_0 {
            let mut transferred = 0u32;
            unsafe {
                GetOverlappedResult(
                    self.endpoint.raw_handle(),
                    &overlapped,
                    &mut transferred,
                    false,
                )
            }
            .map_err(|_| {
                let code = unsafe { GetLastError().0 as i32 };
                map_pipe_windows_error("connect", Some(self.endpoint.pipe_name()), code)
            })?;

            self.validate_connected_client()?;
            return Ok(());
        }

        if wait_result == windows::Win32::Foundation::WAIT_EVENT(WAIT_OBJECT_0.0 + 1) {
            let _ = unsafe { CancelIoEx(self.endpoint.raw_handle(), Some(&overlapped)) };
            return Err(Error::Pipe(PipeError::Connect(
                PipeConnectError::new(Cow::Owned(self.endpoint.pipe_name().as_str().to_owned()))
                    .with_context("connect interrupted by wait handle signal")
                    .with_code(ERROR_OPERATION_ABORTED.0 as i32),
            )));
        }

        if wait_result == WAIT_TIMEOUT {
            let _ = unsafe { CancelIoEx(self.endpoint.raw_handle(), Some(&overlapped)) };
            return Err(Error::Pipe(PipeError::Timeout(PipeTimeoutError::new(
                Cow::Owned(self.endpoint.pipe_name().as_str().to_owned()),
                Cow::Borrowed("connect"),
            ))));
        }

        let _ = unsafe { CancelIoEx(self.endpoint.raw_handle(), Some(&overlapped)) };
        if wait_result == WAIT_FAILED {
            let code = unsafe { GetLastError().0 as i32 };
            return Err(map_pipe_windows_error(
                "connect",
                Some(self.endpoint.pipe_name()),
                code,
            ));
        }

        Err(map_pipe_windows_error(
            "connect",
            Some(self.endpoint.pipe_name()),
            wait_result.0 as i32,
        ))
    }

    fn validate_connected_client(&self) -> Result<()> {
        if !self.allowed_executables.is_empty()
            && let Err(e) = self.check_client_executable()
        {
            let _ = self.disconnect();
            return Err(e);
        }
        Ok(())
    }

    /// Retrieve the connecting client's executable path and verify it is on the allow-list.
    fn check_client_executable(&self) -> Result<()> {
        let pipe_name = Cow::Owned(self.endpoint.pipe_name().as_str().to_owned());
        let mut pid: u32 = 0;
        let ok = unsafe { GetNamedPipeClientProcessId(self.endpoint.raw_handle(), &mut pid) };
        if ok.is_err() {
            return Err(Error::AccessDenied(AccessDeniedError::with_reason(
                pipe_name,
                "connect",
                "could not determine client process id",
            )));
        }

        let client_path = match Process::open(ProcessId::new(pid)) {
            Ok(proc) => match proc.path() {
                Ok(p) => p,
                Err(_) => {
                    return Err(Error::AccessDenied(AccessDeniedError::with_reason(
                        pipe_name,
                        "connect",
                        "could not retrieve client executable path",
                    )));
                }
            },
            Err(_) => {
                return Err(Error::AccessDenied(AccessDeniedError::with_reason(
                    pipe_name,
                    "connect",
                    "could not open client process",
                )));
            }
        };

        let allowed = self.allowed_executables.iter().any(|allowed| {
            allowed
                .as_os_str()
                .to_string_lossy()
                .eq_ignore_ascii_case(&client_path.as_os_str().to_string_lossy())
        });

        if allowed {
            Ok(())
        } else {
            Err(Error::AccessDenied(AccessDeniedError::with_reason(
                pipe_name,
                "connect",
                Cow::Owned(format!(
                    "client executable '{}' is not in the allow-list",
                    client_path.display()
                )),
            )))
        }
    }

    /// Disconnect the currently connected client.
    pub fn disconnect(&self) -> Result<()> {
        unsafe { DisconnectNamedPipe(self.endpoint.raw_handle()) }.map_err(|_| {
            let code = unsafe { GetLastError().0 as i32 };
            map_pipe_windows_error("disconnect", Some(self.endpoint.pipe_name()), code)
        })
    }
}

fn duration_to_wait_ms(timeout: Duration) -> u32 {
    timeout.as_millis().min(u32::MAX as u128) as u32
}

impl io::Read for NamedPipeServer {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut read = 0u32;
        unsafe { ReadFile(self.endpoint.raw_handle(), Some(buf), Some(&mut read), None) }
            .map_err(|e| io::Error::from_raw_os_error(e.code().0))?;
        Ok(read as usize)
    }
}

impl io::Write for NamedPipeServer {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let mut written = 0u32;
        unsafe {
            WriteFile(
                self.endpoint.raw_handle(),
                Some(buf),
                Some(&mut written),
                None,
            )
        }
        .map_err(|e| io::Error::from_raw_os_error(e.code().0))?;
        Ok(written as usize)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn to_server_open_mode(open_mode: NamedPipeOpenMode) -> FILE_FLAGS_AND_ATTRIBUTES {
    match open_mode {
        NamedPipeOpenMode::Inbound => {
            FILE_FLAGS_AND_ATTRIBUTES(PIPE_ACCESS_INBOUND.0 | FILE_FLAG_OVERLAPPED.0)
        }
        NamedPipeOpenMode::Outbound => {
            FILE_FLAGS_AND_ATTRIBUTES(PIPE_ACCESS_OUTBOUND.0 | FILE_FLAG_OVERLAPPED.0)
        }
        NamedPipeOpenMode::Duplex => {
            FILE_FLAGS_AND_ATTRIBUTES(PIPE_ACCESS_DUPLEX.0 | FILE_FLAG_OVERLAPPED.0)
        }
    }
}

fn to_pipe_mode(pipe_type: NamedPipeType) -> NAMED_PIPE_MODE {
    match pipe_type {
        NamedPipeType::Byte => NAMED_PIPE_MODE(
            PIPE_TYPE_BYTE.0 | PIPE_READMODE_BYTE.0 | PIPE_WAIT.0 | PIPE_REJECT_REMOTE_CLIENTS.0,
        ),
        NamedPipeType::Message => NAMED_PIPE_MODE(
            PIPE_TYPE_MESSAGE.0
                | PIPE_READMODE_MESSAGE.0
                | PIPE_WAIT.0
                | PIPE_REJECT_REMOTE_CLIENTS.0,
        ),
    }
}