tcrm-task 0.4.2

Task execution unit for TCRM project
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
use tokio::process::Command;

use crate::tasks::process::group::error::ProcessGroupError;

/// A cross-platform wrapper for managing process groups/jobs.
///
/// On Unix systems, this uses process groups with `setsid()`.
/// On Windows, this uses Job Objects for full process tree termination.
///
/// # Platform Support
/// - **Unix/Linux**: Full process group support using `setsid()` and `killpg()`
/// - **Windows**: Full process tree support using Job Objects
/// - **Other platforms**: No special handling
#[derive(Debug)]
pub struct ProcessGroup {
    pub(crate) inner: ProcessGroupInner,
}

#[derive(Debug)]
pub(crate) struct ProcessGroupInner {
    #[cfg(unix)]
    pub(crate) process_group_id: Option<i32>,
    #[cfg(windows)]
    pub(crate) job_handle: Option<SendHandle>,
    #[cfg(not(any(unix, windows)))]
    _phantom: (),
}

#[cfg(windows)]
#[derive(Debug)]
pub(crate) struct SendHandle(pub(crate) windows::Win32::Foundation::HANDLE);

#[cfg(windows)]
unsafe impl Send for SendHandle {}

#[cfg(windows)]
unsafe impl Sync for SendHandle {}

impl ProcessGroup {
    /// Create a new, inactive process group
    ///
    /// # Returns
    ///
    /// A new `ProcessGroup` instance that is not yet active
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tcrm_task::tasks::process::group::builder::ProcessGroup;
    ///
    /// let group = ProcessGroup::new();
    /// assert!(!group.is_active());
    /// ```
    pub fn new() -> Self {
        Self {
            inner: ProcessGroupInner {
                #[cfg(unix)]
                process_group_id: None,
                #[cfg(windows)]
                job_handle: None,
                #[cfg(not(any(unix, windows)))]
                _phantom: (),
            },
        }
    }

    /// Check if the process group is active
    ///
    /// # Returns
    ///
    /// `true` if the process group has been created and is active, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tcrm_task::tasks::process::group::builder::ProcessGroup;
    ///
    /// let group = ProcessGroup::new();
    /// assert!(!group.is_active());
    /// ```
    pub fn is_active(&self) -> bool {
        #[cfg(unix)]
        {
            self.inner.process_group_id.is_some()
        }
        #[cfg(windows)]
        {
            self.inner.job_handle.is_some()
        }
        #[cfg(not(any(unix, windows)))]
        {
            false
        }
    }
    /// Creates a new process group and configures the command to use it.
    ///
    /// This method prepares a Command to run as part of this process group. On Unix systems,
    /// it configures the command to create a new session and process group using setsid().
    /// On Windows, it configures the command to run in a new job object with appropriate
    /// creation flags and enables CREATE_SUSPENDED to avoid race conditions.
    ///
    /// # Arguments
    ///
    /// * `command` - The Command to configure for process group execution
    ///
    /// # Returns
    ///
    /// * `Ok(Command)` - The configured command ready for execution
    /// * `Err(ProcessGroupError)` - If process group configuration fails
    ///
    /// # Platform-Specific Behavior
    ///
    /// ## Windows Race Condition Mitigation
    /// On Windows, the process is configured to start in a suspended state (CREATE_SUSPENDED).
    /// After spawning, you must call `assign_child()` and then manually resume the process
    /// to avoid the race condition where child processes can escape the job before assignment.
    ///
    /// ## Unix Behavior  
    /// On Unix, the process starts normally in its own process group via setsid().
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use tcrm_task::tasks::process::group::builder::ProcessGroup;
    /// use tokio::process::Command;
    ///
    /// let mut group = ProcessGroup::new();
    /// let mut cmd = Command::new("echo");
    /// cmd.arg("hello");
    ///
    /// let configured_cmd = group.create_with_command(cmd).unwrap();
    /// // Command is now configured to run in the process group
    /// ```
    pub fn create_with_command(
        &mut self,
        #[allow(unused_mut)] mut command: Command,
    ) -> Result<Command, ProcessGroupError> {
        #[cfg(unix)]
        {
            // Configure the command to create a new session and process group
            unsafe {
                command.pre_exec(|| {
                    use nix::unistd::setsid;
                    if setsid().is_err() {
                        return Err(std::io::Error::last_os_error());
                    }
                    Ok(())
                });
            }
            Ok(command)
        }
        #[cfg(windows)]
        {
            use windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
            use windows::Win32::System::JobObjects::{
                CreateJobObjectW, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
                JobObjectExtendedLimitInformation, SetInformationJobObject,
            };
            use windows::Win32::System::Threading::CREATE_SUSPENDED;
            use windows::core::PCWSTR;

            // Create a Job Object for the process group
            let job_handle = unsafe { CreateJobObjectW(None, PCWSTR::null()) }.map_err(|e| {
                ProcessGroupError::CreationFailed(format!("Failed to create Job Object: {}", e))
            })?;

            // Configure the job to kill all processes when the job handle is closed
            let mut job_info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
            job_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

            let set_info_result = unsafe {
                SetInformationJobObject(
                    job_handle,
                    JobObjectExtendedLimitInformation,
                    &job_info as *const _ as *const std::ffi::c_void,
                    std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
                )
            };

            if let Err(e) = set_info_result {
                unsafe {
                    let _ = windows::Win32::Foundation::CloseHandle(job_handle);
                }
                return Err(ProcessGroupError::CreationFailed(format!(
                    "Failed to configure Job Object: {}",
                    e
                )));
            }

            self.inner.job_handle = Some(SendHandle(job_handle));

            // Configure the command to start suspended to avoid race conditions
            // This is essential to prevent child processes from escaping the job
            command.creation_flags(CREATE_SUSPENDED.0);

            Ok(command)
        }
        #[cfg(not(any(unix, windows)))]
        {
            Err(ProcessGroupError::UnsupportedPlatform(
                "Process group management not available on this platform".to_string(),
            ))
        }
    }

    /// Assigns a spawned child process to this process group/job.
    ///
    /// On Unix systems, this stores the process group ID.
    ///
    /// On Windows, this assigns the process to the job object.
    ///
    /// After assignment, all future children of the process will be contained in the job, unless the process has
    /// breakaway privileges (which are not enabled by default in this implementation).
    ///
    /// # Arguments
    ///
    /// * `child_id` - The process ID of the child to assign to this group
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the assignment was successful
    /// * `Err(ProcessGroupError)` - If assignment fails or the platform is unsupported
    ///
    /// # Example
    ///
    /// ```rust
    /// use tcrm_task::tasks::process::group::builder::ProcessGroup;
    /// use std::process::Command;
    ///
    /// let mut group = ProcessGroup::new();
    ///
    /// // After spawning a process, assign it to the group
    /// // let child = Command::new("echo").spawn()?;
    /// // group.assign_child(child.id())?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Windows Race Condition Note
    /// On Windows, there is a well-known race condition: if a spawned process creates child processes
    /// before it is assigned to the job object, those children will not be part of the job
    /// and can escape containment.
    ///
    /// See: <https://devblogs.microsoft.com/oldnewthing/20130405-00/?p=4743>
    ///
    /// To avoid this issue, the process needs to be spawned in a suspended state,
    /// assigned to the job object, and only then resuming it. This ensures that no
    /// child processes can escape the job before assignment.
    pub fn assign_child(&mut self, child_id: u32) -> Result<(), ProcessGroupError> {
        #[cfg(unix)]
        {
            self.inner.process_group_id = Some(child_id as i32);
            Ok(())
        }
        #[cfg(windows)]
        {
            use windows::Win32::Foundation::CloseHandle;
            use windows::Win32::System::JobObjects::AssignProcessToJobObject;
            use windows::Win32::System::Threading::{
                OpenProcess, PROCESS_SET_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
            };

            let process_handle = unsafe {
                OpenProcess(
                    PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_SET_INFORMATION,
                    false,
                    child_id,
                )
            }
            .map_err(|e| {
                ProcessGroupError::AssignmentFailed(format!("Failed to open process handle: {}", e))
            })?;

            let result = if let Some(SendHandle(job_handle)) = &self.inner.job_handle {
                unsafe { AssignProcessToJobObject(*job_handle, process_handle) }
            } else {
                unsafe {
                    let _ = CloseHandle(process_handle);
                }
                return Err(ProcessGroupError::AssignmentFailed(
                    "No Job Object handle available".to_string(),
                ));
            };

            unsafe {
                let _ = CloseHandle(process_handle);
            }

            result.map_err(|e| {
                ProcessGroupError::AssignmentFailed(format!(
                    "Failed to assign process to Job Object: {}",
                    e
                ))
            })?;
            Ok(())
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = child_id;
            Err(ProcessGroupError::UnsupportedPlatform(
                "Process group assignment not available on this platform".to_string(),
            ))
        }
    }

    /// Resumes a suspended process (Windows only).
    ///
    /// This method should be called after `assign_child()` when using processes
    /// spawned with CREATE_SUSPENDED to complete the race-condition-safe setup.
    ///
    /// # Arguments
    ///
    /// * `child_id` - The process ID of the child to resume
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the process was resumed successfully
    /// * `Err(ProcessGroupError)` - If resuming fails or the platform is unsupported
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use tcrm_task::tasks::process::group::builder::ProcessGroup;
    /// use tokio::process::Command;
    ///
    /// let mut group = ProcessGroup::new();
    /// let mut cmd = group.create_with_command(Command::new("echo")).unwrap();
    /// let child = cmd.spawn().unwrap();
    /// let pid = child.id().expect("Failed to get process ID");
    /// group.assign_child(pid).unwrap();
    /// group.resume_process(pid).unwrap(); // Windows only
    /// ```
    #[cfg(windows)]
    pub fn resume_process(&self, child_id: u32) -> Result<(), ProcessGroupError> {
        use windows::Win32::Foundation::CloseHandle;
        use windows::Win32::System::Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
        };
        use windows::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};

        unsafe {
            // Take a snapshot of all threads in the system
            let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0).map_err(|e| {
                ProcessGroupError::SignalFailed(format!("Failed to create thread snapshot: {}", e))
            })?;

            let mut thread_entry = THREADENTRY32 {
                dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
                ..Default::default()
            };

            let mut resumed_count = 0;

            // Iterate through all threads and resume those belonging to the process
            if Thread32First(snapshot, &mut thread_entry).is_ok() {
                loop {
                    if thread_entry.th32OwnerProcessID == child_id {
                        let thread_handle =
                            OpenThread(THREAD_SUSPEND_RESUME, false, thread_entry.th32ThreadID);
                        if let Ok(handle) = thread_handle {
                            ResumeThread(handle);
                            let _ = CloseHandle(handle);
                            resumed_count += 1;
                        }
                    }

                    if Thread32Next(snapshot, &mut thread_entry).is_err() {
                        break;
                    }
                }
            }

            let _ = CloseHandle(snapshot);

            if resumed_count == 0 {
                Err(ProcessGroupError::SignalFailed(format!(
                    "No threads found to resume for process with PID {}",
                    child_id
                )))
            } else {
                Ok(())
            }
        }
    }

    /// No-op on non-Windows platforms.
    #[cfg(not(windows))]
    pub fn resume_process(&self, _child_id: u32) -> Result<(), ProcessGroupError> {
        Ok(()) // No-op on Unix systems
    }
}

impl Drop for ProcessGroupInner {
    fn drop(&mut self) {
        #[cfg(windows)]
        {
            if let Some(SendHandle(job_handle)) = self.job_handle.take() {
                unsafe {
                    let _ = windows::Win32::Foundation::CloseHandle(job_handle);
                }
            }
        }
    }
}