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
|
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::path::PathBuf;
use std::result::Result;
use std::os::windows::io::RawHandle;
use std::ptr::{null, null_mut};
use winpty_sys::*;
use widestring::WideCString;
pub enum ErrorCodes {
Success,
OutOfMemory,
SpawnCreateProcessFailed,
LostConnection,
AgentExeMissing,
Unspecified,
AgentDied,
AgentTimeout,
AgentCreationFailed,
}
pub enum MouseMode {
None,
Auto,
Force,
}
bitflags!(
pub struct SpawnFlags: u64 {
const AUTO_SHUTDOWN = 0x1;
const EXIT_AFTER_SHUTDOWN = 0x2;
}
);
bitflags!(
pub struct ConfigFlags: u64 {
const CONERR = 0x1;
const PLAIN_OUTPUT = 0x2;
const COLOR_ESCAPES = 0x4;
}
);
#[derive(Debug)]
pub struct Err<'a> {
ptr: &'a mut winpty_error_t,
code: u32,
message: String,
}
// Check to see whether winpty gave us an error
fn check_err<'a>(e: *mut winpty_error_t) -> Option<Err<'a>> {
let err = unsafe {
let raw = winpty_error_msg(e);
Err {
ptr: &mut *e,
code: winpty_error_code(e),
message: String::from_utf16_lossy(std::slice::from_raw_parts(raw, wcslen(raw))),
}
};
if err.code == 0 {
None
} else {
Some(err)
}
}
impl<'a> Drop for Err<'a> {
fn drop(&mut self) {
unsafe {
winpty_error_free(self.ptr);
}
}
}
impl<'a> Display for Err<'a> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "Code: {}, Message: {}", self.code, self.message)
}
}
impl<'a> Error for Err<'a> {
fn description(&self) -> &str {
&self.message
}
}
#[derive(Debug)]
/// Winpty agent config
pub struct Config<'a>(&'a mut winpty_config_t);
impl<'a, 'b> Config<'a> {
pub fn new(flags: ConfigFlags) -> Result<Self, Err<'b>> {
let mut err = null_mut() as *mut winpty_error_t;
let config = unsafe { winpty_config_new(flags.bits(), &mut err) };
if let Some(err) = check_err(err) {
Result::Err(err)
} else {
unsafe { Ok(Config(&mut *config)) }
}
}
/// Set the initial size of the console window
pub fn set_initial_size(&mut self, cols: i32, rows: i32) {
unsafe {
winpty_config_set_initial_size(self.0, cols, rows);
}
}
/// Set the mouse mode
pub fn set_mouse_mode(&mut self, mode: &MouseMode) {
let m = match mode {
MouseMode::None => 0,
MouseMode::Auto => 1,
MouseMode::Force => 2,
};
unsafe {
winpty_config_set_mouse_mode(self.0, m);
}
}
/// Amount of time to wait for the agent to startup and to wait for any given
/// agent RPC request. Must be greater than 0. Can be INFINITE.
// Might be a better way to represent this while still retaining infinite capability?
// Enum?
pub fn set_agent_timeout(&mut self, timeout: u32) {
unsafe {
winpty_config_set_agent_timeout(self.0, timeout);
}
}
}
impl<'a> Drop for Config<'a> {
fn drop(&mut self) {
unsafe {
winpty_config_free(self.0);
}
}
}
#[derive(Debug)]
/// A struct representing the winpty agent process
pub struct Winpty<'a>(&'a mut winpty_t);
impl<'a, 'b> Winpty<'a> {
/// Starts the agent. This process will connect to the agent
/// over a control pipe, and the agent will open data pipes
/// (e.g. CONIN and CONOUT).
pub fn open(cfg: &Config) -> Result<Self, Err<'b>> {
let mut err = null_mut() as *mut winpty_error_t;
unsafe {
let winpty = winpty_open(cfg.0, &mut err);
let err = check_err(err);
if let Some(err) = err {
Result::Err(err)
} else {
Ok(Winpty(&mut *winpty))
}
}
}
/// Returns the handle to the winpty agent process
pub fn raw_handle(&mut self) -> RawHandle {
unsafe { winpty_agent_process(self.0) }
}
/// Returns the name of the input pipe.
/// Pipe is half-duplex.
pub fn conin_name(&mut self) -> PathBuf {
unsafe {
let raw = winpty_conin_name(self.0);
PathBuf::from(&String::from_utf16_lossy(std::slice::from_raw_parts(
raw,
wcslen(raw),
)))
}
}
/// Returns the name of the output pipe.
/// Pipe is half-duplex.
pub fn conout_name(&mut self) -> PathBuf {
unsafe {
let raw = winpty_conout_name(self.0);
PathBuf::from(&String::from_utf16_lossy(std::slice::from_raw_parts(
raw,
wcslen(raw),
)))
}
}
/// Returns the name of the error pipe.
/// The name will only be valid if ConfigFlags::CONERR was specified.
/// Pipe is half-duplex.
pub fn conerr_name(&mut self) -> PathBuf {
unsafe {
let raw = winpty_conerr_name(self.0);
PathBuf::from(&String::from_utf16_lossy(std::slice::from_raw_parts(
raw,
wcslen(raw),
)))
}
}
/// Change the size of the Windows console window.
///
/// cols & rows MUST be greater than 0
pub fn set_size(&mut self, cols: u16, rows: u16) -> Result<(), Err> {
assert!(cols > 0 && rows > 0);
let mut err = null_mut() as *mut winpty_error_t;
unsafe {
winpty_set_size(self.0, i32::from(cols), i32::from(rows), &mut err);
}
if let Some(err) = check_err(err) {
Result::Err(err)
} else {
Ok(())
}
}
/// Get the list of processses running in the winpty agent. Returns <= count processes
///
/// `count` must be greater than 0. Larger values cause a larger allocation.
// TODO: This should return Vec<Handle> instead of Vec<i32>
pub fn console_process_list(&mut self, count: usize) -> Result<Vec<i32>, Err> {
assert!(count > 0);
let mut err = null_mut() as *mut winpty_error_t;
let mut process_list = Vec::with_capacity(count);
unsafe {
let len = winpty_get_console_process_list(self.0, process_list.as_mut_ptr(), count as i32, &mut err) as usize;
process_list.set_len(len);
}
if let Some(err) = check_err(err) {
Result::Err(err)
} else {
Ok(process_list)
}
}
/// Spawns the new process.
///
/// spawn can only be called once per Winpty object. If it is called
/// before the output data pipe(s) is/are connected, then collected output is
/// buffered until the pipes are connected, rather than being discarded.
/// (https://blogs.msdn.microsoft.com/oldnewthing/20110107-00/?p=11803)
// TODO: Support getting the process and thread handle of the spawned process (Not the agent)
// TODO: Support returning the error from CreateProcess
pub fn spawn(
&mut self,
cfg: &SpawnConfig,
) -> Result<(), Err> {
let mut err = null_mut() as *mut winpty_error_t;
unsafe {
let ok = winpty_spawn(
self.0,
cfg.0 as *const winpty_spawn_config_s,
null_mut(), // Process handle
null_mut(), // Thread handle
null_mut(), // Create process error
&mut err,
);
if ok == 0 { return Ok(());}
}
if let Some(err) = check_err(err) {
Result::Err(err)
} else {
Ok(())
}
}
}
// winpty_t is thread-safe
unsafe impl<'a> Sync for Winpty<'a> {}
unsafe impl<'a> Send for Winpty<'a> {}
impl<'a> Drop for Winpty<'a> {
fn drop(&mut self) {
unsafe {
winpty_free(self.0);
}
}
}
#[derive(Debug)]
/// Information about a process for winpty to spawn
pub struct SpawnConfig<'a>(&'a mut winpty_spawn_config_t);
impl<'a, 'b> SpawnConfig<'a> {
/// Creates a new spawnconfig
pub fn new(
spawnflags: SpawnFlags,
appname: Option<&str>,
cmdline: Option<&str>,
cwd: Option<&str>,
end: Option<&str>,
) -> Result<Self, Err<'b>> {
let mut err = null_mut() as *mut winpty_error_t;
let (appname, cmdline, cwd, end) = (
appname.map_or(null(), |s| WideCString::from_str(s).unwrap().into_raw()),
cmdline.map_or(null(), |s| WideCString::from_str(s).unwrap().into_raw()),
cwd.map_or(null(), |s| WideCString::from_str(s).unwrap().into_raw()),
end.map_or(null(), |s| WideCString::from_str(s).unwrap().into_raw()),
);
let spawn_config = unsafe {
winpty_spawn_config_new(spawnflags.bits(), appname, cmdline, cwd, end, &mut err)
};
// Required to free the strings
unsafe {
if !appname.is_null() {
WideCString::from_raw(appname as *mut u16);
}
if !cmdline.is_null() {
WideCString::from_raw(cmdline as *mut u16);
}
if !cwd.is_null() {
WideCString::from_raw(cwd as *mut u16);
}
if !end.is_null() {
WideCString::from_raw(end as *mut u16);
}
}
if let Some(err) = check_err(err) {
Result::Err(err)
} else {
unsafe { Ok(SpawnConfig(&mut *spawn_config)) }
}
}
}
impl<'a> Drop for SpawnConfig<'a> {
fn drop(&mut self) {
unsafe {
winpty_spawn_config_free(self.0);
}
}
}
#[cfg(test)]
mod tests {
extern crate named_pipe;
extern crate winapi;
use self::named_pipe::PipeClient;
use self::winapi::um::processthreadsapi::OpenProcess;
use self::winapi::um::winnt::READ_CONTROL;
use {Config, ConfigFlags, SpawnConfig, SpawnFlags, Winpty};
#[test]
// Test that we can start a process in winpty
fn spawn_process() {
let mut winpty = Winpty::open(
&Config::new(ConfigFlags::empty()).expect("failed to create config")
).expect("failed to create winpty instance");
winpty.spawn(
&SpawnConfig::new(
SpawnFlags::empty(),
None,
Some("cmd"),
None,
None
).expect("failed to create spawn config")
).unwrap();
}
#[test]
// Test that pipes connected before winpty is spawned can be connected to
fn valid_pipe_connect_before() {
let mut winpty = Winpty::open(
&Config::new(ConfigFlags::empty()).expect("failed to create config")
).expect("failed to create winpty instance");
// Check we can connect to both pipes
PipeClient::connect_ms(winpty.conout_name(), 1000).expect("failed to connect to conout pipe");
PipeClient::connect_ms(winpty.conin_name(), 1000).expect("failed to connect to conin pipe");
winpty.spawn(
&SpawnConfig::new(
SpawnFlags::empty(),
None,
Some("cmd"),
None,
None
).expect("failed to create spawn config")
).unwrap();
}
#[test]
// Test that pipes connected after winpty is spawned can be connected to
fn valid_pipe_connect_after() {
let mut winpty = Winpty::open(
&Config::new(ConfigFlags::empty()).expect("failed to create config")
).expect("failed to create winpty instance");
winpty.spawn(
&SpawnConfig::new(
SpawnFlags::empty(),
None,
Some("cmd"),
None,
None
).expect("failed to create spawn config")
).unwrap();
// Check we can connect to both pipes
PipeClient::connect_ms(winpty.conout_name(), 1000).expect("failed to connect to conout pipe");
PipeClient::connect_ms(winpty.conin_name(), 1000).expect("failed to connect to conin pipe");
}
#[test]
fn resize() {
let mut winpty = Winpty::open(
&Config::new(ConfigFlags::empty()).expect("failed to create config")
).expect("failed to create winpty instance");
winpty.spawn(
&SpawnConfig::new(
SpawnFlags::empty(),
None,
Some("cmd"),
None,
None
).expect("failed to create spawn config")
).unwrap();
winpty.set_size(1, 1).unwrap();
}
#[test]
#[ignore]
// Test that each id returned by cosole_process_list points to an actual process
fn console_process_list_valid() {
let mut winpty = Winpty::open(
&Config::new(ConfigFlags::empty()).expect("failed to create config")
).expect("failed to create winpty instance");
winpty.spawn(
&SpawnConfig::new(
SpawnFlags::empty(),
None,
Some("cmd"),
None,
None
).expect("failed to create spawn config")
).unwrap();
let processes = winpty.console_process_list(1000).expect("failed to get console process list");
// Check that each id is valid
processes.iter().for_each(|id| {
let handle = unsafe {
OpenProcess(
READ_CONTROL, // permissions
false as i32, // inheret
*id as u32
)
};
assert!(!handle.is_null());
});
}
}
|