Skip to main content

shell/
cmd.rs

1//! The cmd shell (Windows Command Prompt).
2//!
3//! cmd.exe is the Windows peer of Bash/PowerShell: a real command language
4//! over the same Windows OS. It implements the classic prompt's builtins
5//! (`echo`, `dir`, `cd`, `type`, `set`, `copy`, ...), `%VAR%` expansion,
6//! `&`/`&&`/`||` sequencing, `|` pipelines, and `>`/`>>`/`2>` redirection,
7//! and resolves external commands through the Windows command table like
8//! PowerShell does — so `tasklist`, `ipconfig`, and `whoami` behave
9//! identically in either shell.
10//!
11//! The two shells coexist on one machine: `powershell` and `cmd` are both
12//! launchable on Windows, exactly as on a real system.
13
14use engine::{BytesInput, BytesOutput, Input, Output, Pipe, Terminal, Timestamp, VirtualPath};
15use os::ExitStatus;
16use os::OperatingSystem as _;
17use os::environment::Environment;
18use os::windows::Windows;
19
20/// The cmd shell.
21pub struct Cmd<'os> {
22    /// The Windows OS this shell runs on.
23    os: &'os Windows,
24    /// The invoking account.
25    actor: engine::ActorId,
26    /// The current working directory.
27    cwd: VirtualPath,
28    /// The environment (`%VAR%` state, including `errorlevel`).
29    environment: Environment,
30    /// A pending `exit` request (`exit [N]`).
31    exit_request: Option<ExitStatus>,
32    /// The session's command history, recorded by the application.
33    history: Vec<String>,
34}
35
36/// The version string `ver` reports and the banner echoes.
37const WINDOWS_VERSION: &str = "Microsoft Windows [Version 10.0.22631.4317]";
38
39impl<'os> Cmd<'os> {
40    /// Creates a cmd session.
41    ///
42    /// Sessions start in the account's profile directory (or the filesystem
43    /// root if the profile is not materialized).
44    pub fn new(
45        os: &'os Windows,
46        actor: engine::ActorId,
47        environment: Environment,
48    ) -> Result<Self, os::OsError> {
49        let user_name = os
50            .users()
51            .get(actor.get() as u32)
52            .map(|user| user.name().to_owned())
53            .unwrap_or_else(|| "Administrator".to_owned());
54        let home: VirtualPath = format!("/Users/{user_name}").parse().expect("valid path");
55        let cwd = if os.engine().lookup(Some(actor), &home).is_ok() {
56            home
57        } else {
58            VirtualPath::root()
59        };
60        Ok(Self {
61            os,
62            actor,
63            cwd,
64            environment,
65            exit_request: None,
66            history: Vec::new(),
67        })
68    }
69
70    /// The invoking account.
71    pub fn actor(&self) -> engine::ActorId {
72        self.actor
73    }
74
75    /// Resolves a path against the working directory, accepting Windows
76    /// path syntax: backslashes, drive prefixes (`C:\Users\Rey`), forward
77    /// slashes, and trailing separators are all normalized to the engine's
78    /// slash form.
79    fn resolve_path(&self, argument: &str) -> Result<VirtualPath, os::OsError> {
80        crate::windows_core::resolve_path(&self.cwd, argument)
81    }
82
83    /// The Windows display form of an engine path: `C:\Users\Rey`.
84    fn display_path(&self, path: &VirtualPath) -> String {
85        crate::windows_core::display_path(path)
86    }
87
88    /// Executes one statement: possibly several `|`-joined stages.
89    fn run_pipeline(
90        &mut self,
91        stages: &[String],
92        stdin: &mut dyn Input,
93        stdout: &mut dyn Output,
94        stderr: &mut dyn Output,
95    ) -> ExitStatus {
96        if stages.len() == 1 {
97            return self.run_command(&stages[0], stdin, stdout, stderr);
98        }
99        // Pipelines connect stages through engine pipes: each stage reads
100        // its predecessor's pipe and writes the next one.
101        let pipes: Vec<Pipe> = (0..stages.len() - 1).map(|_| Pipe::new()).collect();
102        let mut last_status = ExitStatus::SUCCESS;
103        for (index, stage) in stages.iter().enumerate() {
104            let is_last = index == stages.len() - 1;
105            if is_last {
106                let mut pipe_in = pipes[index - 1].input();
107                last_status = self.run_command(stage, &mut pipe_in, stdout, stderr);
108            } else {
109                let mut pipe_out = pipes[index].output();
110                let pipe_in = if index == 0 {
111                    &mut *stdin
112                } else {
113                    &mut pipes[index - 1].input()
114                };
115                last_status = self.run_command(stage, pipe_in, &mut pipe_out, stderr);
116            }
117        }
118        last_status
119    }
120
121    /// Executes one command: redirects, builtin, or external.
122    fn run_command(
123        &mut self,
124        text: &str,
125        stdin: &mut dyn Input,
126        stdout: &mut dyn Output,
127        stderr: &mut dyn Output,
128    ) -> ExitStatus {
129        // Parse redirections (`>`, `>>`, `2>`, `2>>`, `<`) outside quotes.
130        let (command_text, redirects) = parse_redirects(text);
131        let mut captured = BytesOutput::new();
132        let mut captured_stderr = BytesOutput::new();
133        let mut stdout_redirect: Option<(String, bool)> = None;
134        let mut stderr_redirect: Option<(String, bool)> = None;
135        let mut stdin_redirect: Option<String> = None;
136        for redirect in redirects {
137            match redirect.0 {
138                OutputStream::Stdout => stdout_redirect = Some((redirect.1, redirect.2)),
139                OutputStream::Stderr => stderr_redirect = Some((redirect.1, redirect.2)),
140                OutputStream::Stdin => stdin_redirect = Some(redirect.1),
141            }
142        }
143        let effective_stdout: &mut dyn Output = if stdout_redirect.is_some() {
144            &mut captured
145        } else {
146            stdout
147        };
148        let effective_stderr: &mut dyn Output = if stderr_redirect.is_some() {
149            &mut captured_stderr
150        } else {
151            stderr
152        };
153
154        let words = split_words(&command_text);
155        if words.is_empty() {
156            return ExitStatus::SUCCESS;
157        }
158        // `@` prefixes suppress the echo of the line (only meaningful in
159        // batch files); strip it.
160        let mut words: Vec<String> = words.into_iter().map(|word| self.expand(&word)).collect();
161        if words[0].starts_with('@') && words[0].len() > 1 {
162            words[0] = words[0][1..].to_owned();
163        }
164        // cmd does not require a space between a builtin name and its
165        // argument: `echo.`, `cd..`, `dir /b` glue them into one word.
166        if let Some((name, rest)) = split_glued_name(&words[0]) {
167            words[0] = name.to_owned();
168            if !rest.is_empty() {
169                words.insert(1, rest);
170            }
171        }
172        let name = words[0].clone();
173        // Hold a redirect input alive across the command, so the effective
174        // stdin binding below can borrow it.
175        let mut redirect_input: Option<BytesInput> = match &stdin_redirect {
176            Some(path) => self.read_redirect(path).map(BytesInput::new),
177            None => None,
178        };
179        if stdin_redirect.is_some() && redirect_input.is_none() {
180            let _ = stderr.write(b"The system cannot find the file specified.\n");
181            return ExitStatus::FAILURE;
182        }
183        let effective_stdin: &mut dyn Input = match &mut redirect_input {
184            Some(input) => input,
185            None => stdin,
186        };
187
188        // `echo` prints its raw remainder (`echo a   b` preserves the spaces,
189        // `echo.` prints a blank line), so the original command text is
190        // handed along with the split words. The single separating space
191        // after the command name is consumed, as in real cmd.
192        let echo_remainder =
193            if words[0].eq_ignore_ascii_case("echo") || words[0].eq_ignore_ascii_case("@echo") {
194                let mut remainder = &command_text[words[0].len()..];
195                if remainder.starts_with(' ') {
196                    remainder = &remainder[1..];
197                }
198                Some(self.expand(remainder))
199            } else {
200                None
201            };
202
203        // Builtins first; external commands fall through to resolution.
204        if let Some(status) = self.try_builtin(
205            &name,
206            &words,
207            echo_remainder.as_deref(),
208            effective_stdin,
209            effective_stdout,
210            effective_stderr,
211        ) {
212            let _ = self.flush_redirects(
213                stdout_redirect,
214                stderr_redirect,
215                &captured,
216                &captured_stderr,
217                stdout,
218                stderr,
219                &name,
220            );
221            return status;
222        }
223
224        // External resolution and execution through the shared Windows
225        // machinery (resolve → record process → execute → finish).
226        let status = match crate::windows_core::run_external(
227            self.os,
228            self.actor,
229            &self.cwd,
230            &self.environment,
231            &name,
232            &words,
233            effective_stdin,
234            effective_stdout,
235            effective_stderr,
236        ) {
237            Some(status) => status,
238            None => {
239                let _ = effective_stderr.write(
240                    format!("'{name}' is not recognized as an internal or external command, operable program or batch file.\n")
241                        .as_bytes(),
242                );
243                ExitStatus::NOT_FOUND
244            }
245        };
246        let _ = self.flush_redirects(
247            stdout_redirect,
248            stderr_redirect,
249            &captured,
250            &captured_stderr,
251            stdout,
252            stderr,
253            &name,
254        );
255        status
256    }
257
258    /// Writes captured redirect output to the virtual filesystem.
259    #[allow(clippy::too_many_arguments)]
260    fn flush_redirects(
261        &self,
262        stdout_redirect: Option<(String, bool)>,
263        stderr_redirect: Option<(String, bool)>,
264        captured: &BytesOutput,
265        captured_stderr: &BytesOutput,
266        _stdout: &mut dyn Output,
267        stderr: &mut dyn Output,
268        name: &str,
269    ) -> Result<(), ()> {
270        if let Some((path, append)) = stdout_redirect
271            && let Err(error) = self.write_redirect(&path, captured.bytes(), append)
272        {
273            let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
274            return Err(());
275        }
276        if let Some((path, append)) = stderr_redirect
277            && let Err(error) = self.write_redirect(&path, captured_stderr.bytes(), append)
278        {
279            let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
280            return Err(());
281        }
282        Ok(())
283    }
284
285    /// Writes redirect output to the virtual filesystem, creating the file
286    /// if needed.
287    fn write_redirect(
288        &self,
289        path_str: &str,
290        bytes: &[u8],
291        append: bool,
292    ) -> Result<(), os::OsError> {
293        crate::windows_core::write_redirect(self.os, self.actor, &self.cwd, path_str, bytes, append)
294    }
295
296    /// Reads a redirect input file's bytes.
297    fn read_redirect(&self, path_str: &str) -> Option<Vec<u8>> {
298        crate::windows_core::read_redirect(self.os, self.actor, &self.cwd, path_str)
299    }
300
301    /// Expands `%VAR%` references (case-insensitive), including the
302    /// dynamic variables `%cd%` and `%errorlevel%`.
303    fn expand(&self, text: &str) -> String {
304        let mut out = String::new();
305        let mut rest = text;
306        while let Some(start) = rest.find('%') {
307            out.push_str(&rest[..start]);
308            let remainder = &rest[start + 1..];
309            let Some(end) = remainder.find('%') else {
310                out.push('%');
311                out.push_str(remainder);
312                return out;
313            };
314            let name = &remainder[..end];
315            let value = match name.to_ascii_lowercase().as_str() {
316                "cd" => Some(self.display_path(&self.cwd)),
317                "errorlevel" => Some(self.environment.get("errorlevel").unwrap_or("0").to_owned()),
318                _ => {
319                    // cmd variables are case-insensitive.
320                    let name_lower = name.to_ascii_lowercase();
321                    self.environment
322                        .iter()
323                        .find(|(key, _)| key.to_ascii_lowercase() == name_lower)
324                        .map(|(_, value)| value.to_owned())
325                }
326            };
327            match value {
328                Some(value) => out.push_str(&value),
329                None => out.push_str(&format!("%{name}%")),
330            }
331            rest = &remainder[end + 1..];
332        }
333        out.push_str(rest);
334        out
335    }
336
337    /// Handles cmd builtins.
338    fn try_builtin(
339        &mut self,
340        name: &str,
341        argv: &[String],
342        echo_remainder: Option<&str>,
343        stdin: &mut dyn Input,
344        stdout: &mut dyn Output,
345        stderr: &mut dyn Output,
346    ) -> Option<ExitStatus> {
347        match name.to_ascii_lowercase().as_str() {
348            "echo" => Some(self.builtin_echo(echo_remainder, stdout)),
349            "cd" | "chdir" => Some(self.builtin_cd(argv, stdout, stderr)),
350            "dir" => Some(self.builtin_dir(argv, stdout, stderr)),
351            "type" => Some(self.builtin_type(argv, stdout, stderr)),
352            "cls" => Some(self.builtin_cls(stdout)),
353            "set" => Some(self.builtin_set(argv, stdout, stderr)),
354            "del" | "erase" => Some(self.builtin_del(argv, stderr)),
355            "mkdir" | "md" => Some(self.builtin_mkdir(argv, stderr)),
356            "rmdir" | "rd" => Some(self.builtin_rmdir(argv, stderr)),
357            "copy" => Some(self.builtin_copy(argv, stdout, stderr)),
358            "ren" | "rename" => Some(self.builtin_ren(argv, stderr)),
359            "ver" => Some(self.builtin_ver(stdout)),
360            "date" => Some(self.builtin_date(stdout)),
361            "time" => Some(self.builtin_time(stdout)),
362            "title" | "color" => Some(ExitStatus::SUCCESS),
363            "pause" => Some(self.builtin_pause(stdout, stdin)),
364            "more" => Some(self.builtin_more(stdin, stdout)),
365            "exit" => Some(self.builtin_exit(argv)),
366            _ => None,
367        }
368    }
369
370    fn builtin_echo(&self, remainder: Option<&str>, stdout: &mut dyn Output) -> ExitStatus {
371        // `echo` with no argument (or only trailing space) reports the
372        // echo state, like cmd.
373        let Some(remainder) = remainder else {
374            let _ = stdout.write(b"ECHO is on.\n");
375            return ExitStatus::SUCCESS;
376        };
377        let mut text = remainder.to_owned();
378        if text.is_empty() {
379            let _ = stdout.write(b"ECHO is on.\n");
380            return ExitStatus::SUCCESS;
381        }
382        // `echo.` and `echo:` print a blank line; everything else prints
383        // its raw text, preserving the spaces cmd preserves.
384        if text == "." || text == ":" {
385            text.clear();
386        }
387        let _ = stdout.write(format!("{text}\n").as_bytes());
388        ExitStatus::SUCCESS
389    }
390
391    fn builtin_cd(
392        &mut self,
393        argv: &[String],
394        stdout: &mut dyn Output,
395        stderr: &mut dyn Output,
396    ) -> ExitStatus {
397        let Some(target) = argv.get(1) else {
398            let _ = stdout.write(format!("{}\n", self.display_path(&self.cwd)).as_bytes());
399            return ExitStatus::SUCCESS;
400        };
401        let path = match self.resolve_path(target) {
402            Ok(path) => path,
403            Err(_) => {
404                let _ = stderr.write(b"The system cannot find the path specified.\n");
405                return ExitStatus::FAILURE;
406            }
407        };
408        if self.os.engine().lookup(Some(self.actor), &path).is_err() {
409            let _ = stderr.write(b"The system cannot find the path specified.\n");
410            return ExitStatus::FAILURE;
411        }
412        self.cwd = path;
413        ExitStatus::SUCCESS
414    }
415
416    fn builtin_dir(
417        &self,
418        argv: &[String],
419        stdout: &mut dyn Output,
420        stderr: &mut dyn Output,
421    ) -> ExitStatus {
422        let mut bare = false;
423        let mut target: Option<&str> = None;
424        for argument in argv.iter().skip(1) {
425            if argument == "/b" || argument == "/B" {
426                bare = true;
427            } else if argument.starts_with('/') {
428                let _ = stderr.write(format!("Invalid switch - {argument}.\n").as_bytes());
429                return ExitStatus::FAILURE;
430            } else {
431                target = Some(argument);
432            }
433        }
434        let path = match target {
435            Some(target) => match self.resolve_path(target) {
436                Ok(path) => path,
437                Err(_) => {
438                    let _ = stderr.write(b"The system cannot find the path specified.\n");
439                    return ExitStatus::FAILURE;
440                }
441            },
442            None => self.cwd.clone(),
443        };
444        let actor = Some(self.actor);
445        let engine = self.os.engine();
446        let Ok(object) = engine.lookup(actor, &path) else {
447            let _ = stderr.write(b"The system cannot find the path specified.\n");
448            return ExitStatus::FAILURE;
449        };
450        if !bare {
451            let _ = stdout.write(b" Volume in drive C has no label\n");
452            let _ =
453                stdout.write(format!(" Directory of {}\n\n", self.display_path(&path)).as_bytes());
454        }
455        let mut files = 0u64;
456        let mut dirs = 0u64;
457        let Ok(children) = engine.children(actor, object) else {
458            return ExitStatus::SUCCESS;
459        };
460        for child in children {
461            let Ok(metadata) = engine.metadata(actor, child) else {
462                continue;
463            };
464            let is_dir = engine.children(actor, child).is_ok();
465            let name = metadata.name().as_str().to_owned();
466            let size = engine.size(actor, child).unwrap_or(0);
467            let date = os::datetime::format_timestamp(metadata.modified(), "%m/%d/%Y");
468            let hour = metadata.modified().as_nanos() / 3_600_000_000_000 % 12;
469            let minute = (metadata.modified().as_nanos() / 60_000_000_000) % 60;
470            let ampm = if metadata.modified().as_nanos() / 3_600_000_000_000 % 24 < 12 {
471                "AM"
472            } else {
473                "PM"
474            };
475            let hour = if hour == 0 { 12 } else { hour };
476            if bare {
477                let _ = stdout.write(format!("{name}\n").as_bytes());
478            } else if is_dir {
479                dirs += 1;
480                let _ = stdout.write(
481                    format!("{date}  {hour:02}:{minute:02} {ampm}    <DIR>          {name}\n")
482                        .as_bytes(),
483                );
484            } else {
485                files += 1;
486                let _ = stdout.write(
487                    format!("{date}  {hour:02}:{minute:02} {ampm}       {size:>14}  {name}\n")
488                        .as_bytes(),
489                );
490            }
491        }
492        let _ = stdout
493            .write(format!("\n               {files} File(s)          {files} bytes\n").as_bytes());
494        let _ = stdout.write(format!("               {dirs} Dir(s)   \n").as_bytes());
495        ExitStatus::SUCCESS
496    }
497
498    fn builtin_type(
499        &self,
500        argv: &[String],
501        stdout: &mut dyn Output,
502        stderr: &mut dyn Output,
503    ) -> ExitStatus {
504        let Some(target) = argv.get(1) else {
505            let _ = stderr.write(b"The syntax of the command is incorrect.\n");
506            return ExitStatus::FAILURE;
507        };
508        let path = match self.resolve_path(target) {
509            Ok(path) => path,
510            Err(_) => {
511                let _ = stderr.write(b"The system cannot find the file specified.\n");
512                return ExitStatus::FAILURE;
513            }
514        };
515        let actor = Some(self.actor);
516        let Ok(object) = self.os.engine().lookup(actor, &path) else {
517            let _ = stderr.write(b"The system cannot find the file specified.\n");
518            return ExitStatus::FAILURE;
519        };
520        match self.os.engine().read(actor, object) {
521            Ok(Some(bytes)) => {
522                let _ = stdout.write(&bytes);
523                ExitStatus::SUCCESS
524            }
525            _ => {
526                let _ = stderr.write(b"The system cannot find the file specified.\n");
527                ExitStatus::FAILURE
528            }
529        }
530    }
531
532    fn builtin_cls(&self, stdout: &mut dyn Output) -> ExitStatus {
533        let _ = stdout.write(b"\x1b[3J\x1b[H\x1b[2J");
534        ExitStatus::SUCCESS
535    }
536
537    fn builtin_set(
538        &mut self,
539        argv: &[String],
540        stdout: &mut dyn Output,
541        stderr: &mut dyn Output,
542    ) -> ExitStatus {
543        if argv.len() == 1 {
544            // `set` alone lists the environment.
545            let mut entries: Vec<(String, String)> = self
546                .environment
547                .iter()
548                .map(|(key, value)| (key.to_owned(), value.to_owned()))
549                .collect();
550            entries.sort();
551            for (key, value) in entries {
552                let _ = stdout.write(format!("{key}={value}\n").as_bytes());
553            }
554            return ExitStatus::SUCCESS;
555        }
556        let assignment = &argv[1];
557        let Some((name, value)) = assignment.split_once('=') else {
558            // `set NAME` prints every variable whose name starts with NAME.
559            let prefix = assignment.to_ascii_lowercase();
560            let mut found = false;
561            let mut entries: Vec<(String, String)> = self
562                .environment
563                .iter()
564                .filter(|(key, _)| key.to_ascii_lowercase().starts_with(&prefix))
565                .map(|(key, value)| (key.to_owned(), value.to_owned()))
566                .collect();
567            entries.sort();
568            for (key, value) in entries {
569                found = true;
570                let _ = stdout.write(format!("{key}={value}\n").as_bytes());
571            }
572            if !found {
573                let _ = stderr
574                    .write(format!("Environment variable {assignment} not defined\n").as_bytes());
575                return ExitStatus::FAILURE;
576            }
577            return ExitStatus::SUCCESS;
578        };
579        if name.is_empty() {
580            let _ = stderr.write(b"The syntax of the command is incorrect.\n");
581            return ExitStatus::FAILURE;
582        }
583        if value.is_empty() {
584            self.environment.remove(name);
585        } else {
586            self.environment.set(name, value);
587        }
588        ExitStatus::SUCCESS
589    }
590
591    fn builtin_del(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
592        let mut exit_status = ExitStatus::SUCCESS;
593        for target in argv.iter().skip(1).filter(|arg| !arg.starts_with('/')) {
594            let path = match self.resolve_path(target) {
595                Ok(path) => path,
596                Err(_) => {
597                    let _ = stderr.write(b"The system cannot find the file specified.\n");
598                    exit_status = ExitStatus::FAILURE;
599                    continue;
600                }
601            };
602            let actor = Some(self.actor);
603            match self.os.engine().lookup(actor, &path) {
604                Ok(object) => {
605                    let _ = self.os.engine().delete(actor, object);
606                }
607                Err(_) => {
608                    let _ = stderr.write(b"The system cannot find the file specified.\n");
609                    exit_status = ExitStatus::FAILURE;
610                }
611            }
612        }
613        exit_status
614    }
615
616    fn builtin_mkdir(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
617        let Some(target) = argv.iter().skip(1).find(|arg| !arg.starts_with('/')) else {
618            let _ = stderr.write(b"The syntax of the command is incorrect.\n");
619            return ExitStatus::FAILURE;
620        };
621        let path = match self.resolve_path(target) {
622            Ok(path) => path,
623            Err(_) => {
624                let _ = stderr.write(b"The system cannot find the path specified.\n");
625                return ExitStatus::FAILURE;
626            }
627        };
628        let actor = Some(self.actor);
629        let engine = self.os.engine();
630        // Create each missing component in turn.
631        let mut current = VirtualPath::root();
632        for segment in path.segments() {
633            current = current.join(&engine::Name::new(segment).expect("valid name"));
634            if engine.lookup(actor, &current).is_err() {
635                let parent = current
636                    .parent()
637                    .and_then(|parent| engine.lookup(actor, &parent).ok())
638                    .unwrap_or(engine.root());
639                let name = engine::Name::new(segment).expect("valid name");
640                if let Err(error) = engine.create_directory(actor, parent, name) {
641                    let _ = stderr.write(format!("mkdir: {error}\n").as_bytes());
642                    return ExitStatus::FAILURE;
643                }
644            }
645        }
646        ExitStatus::SUCCESS
647    }
648
649    fn builtin_rmdir(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
650        let Some(target) = argv.iter().skip(1).find(|arg| !arg.starts_with('/')) else {
651            let _ = stderr.write(b"The syntax of the command is incorrect.\n");
652            return ExitStatus::FAILURE;
653        };
654        let path = match self.resolve_path(target) {
655            Ok(path) => path,
656            Err(_) => {
657                let _ = stderr.write(b"The system cannot find the path specified.\n");
658                return ExitStatus::FAILURE;
659            }
660        };
661        let actor = Some(self.actor);
662        let Ok(object) = self.os.engine().lookup(actor, &path) else {
663            let _ = stderr.write(b"The system cannot find the path specified.\n");
664            return ExitStatus::FAILURE;
665        };
666        if self.os.engine().children(actor, object).is_ok()
667            && !self.os.engine().children(actor, object).unwrap().is_empty()
668        {
669            let _ = stderr.write(b"The directory is not empty.\n");
670            return ExitStatus::FAILURE;
671        }
672        match self.os.engine().delete(actor, object) {
673            Ok(()) => ExitStatus::SUCCESS,
674            Err(_) => {
675                let _ = stderr.write(b"The system cannot find the path specified.\n");
676                ExitStatus::FAILURE
677            }
678        }
679    }
680
681    fn builtin_copy(
682        &self,
683        argv: &[String],
684        stdout: &mut dyn Output,
685        stderr: &mut dyn Output,
686    ) -> ExitStatus {
687        let operands: Vec<&String> = argv
688            .iter()
689            .skip(1)
690            .filter(|argument| !argument.starts_with('/'))
691            .collect();
692        if operands.len() < 2 {
693            let _ = stderr.write(b"The syntax of the command is incorrect.\n");
694            return ExitStatus::FAILURE;
695        }
696        let source = match self.resolve_path(operands[0]) {
697            Ok(path) => path,
698            Err(_) => {
699                let _ = stderr.write(b"The system cannot find the file specified.\n");
700                return ExitStatus::FAILURE;
701            }
702        };
703        let destination = match self.resolve_path(operands[1]) {
704            Ok(path) => path,
705            Err(_) => {
706                let _ = stderr.write(b"The system cannot find the file specified.\n");
707                return ExitStatus::FAILURE;
708            }
709        };
710        let actor = Some(self.actor);
711        let engine = self.os.engine();
712        let Ok(source_object) = engine.lookup(actor, &source) else {
713            let _ = stderr.write(b"The system cannot find the file specified.\n");
714            return ExitStatus::FAILURE;
715        };
716        let Some(bytes) = engine.read(actor, source_object).ok().flatten() else {
717            let _ = stderr.write(b"The system cannot find the file specified.\n");
718            return ExitStatus::FAILURE;
719        };
720        let result = if let Ok(destination_object) = engine.lookup(actor, &destination) {
721            engine.write(actor, destination_object, bytes)
722        } else {
723            let parent_path = destination.parent().expect("path has parent").clone();
724            match engine.lookup(actor, &parent_path) {
725                Ok(parent) => {
726                    let name = engine::Name::new(destination.name().expect("path has name"));
727                    match name {
728                        Ok(name) => engine
729                            .create_file(actor, parent, name, Some(bytes))
730                            .map(|_| ()),
731                        Err(_) => Err(engine::Error::PathNotFound(destination.clone())),
732                    }
733                }
734                Err(_) => Err(engine::Error::PathNotFound(destination.clone())),
735            }
736        };
737        match result {
738            Ok(()) => {
739                let _ = stdout.write(b"        1 file(s) copied.\n");
740                ExitStatus::SUCCESS
741            }
742            Err(_) => {
743                let _ = stderr.write(b"The system cannot find the file specified.\n");
744                ExitStatus::FAILURE
745            }
746        }
747    }
748
749    fn builtin_ren(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
750        let operands: Vec<&String> = argv
751            .iter()
752            .skip(1)
753            .filter(|argument| !argument.starts_with('/'))
754            .collect();
755        if operands.len() != 2 {
756            let _ = stderr.write(b"The syntax of the command is incorrect.\n");
757            return ExitStatus::FAILURE;
758        }
759        let path = match self.resolve_path(operands[0]) {
760            Ok(path) => path,
761            Err(_) => {
762                let _ = stderr.write(b"The system cannot find the file specified.\n");
763                return ExitStatus::FAILURE;
764            }
765        };
766        let new_name = match engine::Name::new(operands[1]) {
767            Ok(name) => name,
768            Err(_) => {
769                let _ = stderr.write(b"The syntax of the command is incorrect.\n");
770                return ExitStatus::FAILURE;
771            }
772        };
773        let actor = Some(self.actor);
774        let engine = self.os.engine();
775        let Ok(object) = engine.lookup(actor, &path) else {
776            let _ = stderr.write(b"The system cannot find the file specified.\n");
777            return ExitStatus::FAILURE;
778        };
779        let parent = engine
780            .parent(actor, object)
781            .ok()
782            .flatten()
783            .unwrap_or(engine.root());
784        match engine.move_object(actor, object, parent, Some(new_name)) {
785            Ok(()) => ExitStatus::SUCCESS,
786            Err(_) => {
787                let _ =
788                    stderr.write(b"A duplicate file name exists, or the file cannot be found.\n");
789                ExitStatus::FAILURE
790            }
791        }
792    }
793
794    fn builtin_ver(&self, stdout: &mut dyn Output) -> ExitStatus {
795        let _ = stdout.write(format!("{WINDOWS_VERSION}\n").as_bytes());
796        ExitStatus::SUCCESS
797    }
798
799    fn builtin_date(&self, stdout: &mut dyn Output) -> ExitStatus {
800        let now = self.os.engine().time();
801        let _ = stdout.write(
802            format!(
803                "The current date is: {}\n",
804                os::datetime::format_timestamp(now, "%a %m/%d/%Y")
805            )
806            .as_bytes(),
807        );
808        ExitStatus::SUCCESS
809    }
810
811    fn builtin_time(&self, stdout: &mut dyn Output) -> ExitStatus {
812        let now = self.os.engine().time();
813        let seconds = now.as_nanos() / 1_000_000_000;
814        let hour24 = (seconds / 3600) % 24;
815        let minute = (seconds % 3600) / 60;
816        let second = seconds % 60;
817        let hour12 = hour24 % 12;
818        let hour12 = if hour12 == 0 { 12 } else { hour12 };
819        let ampm = if hour24 < 12 { "AM" } else { "PM" };
820        let _ = stdout.write(
821            format!("The current time is: {hour12:02}:{minute:02}:{second:02}.00 {ampm}\n")
822                .as_bytes(),
823        );
824        ExitStatus::SUCCESS
825    }
826
827    fn builtin_pause(&self, stdout: &mut dyn Output, stdin: &mut dyn Input) -> ExitStatus {
828        let _ = stdout.write(b"Press any key to continue . . .");
829        let mut line = String::new();
830        let _ = stdin.read_line(&mut line);
831        let _ = stdout.write(b"\n");
832        ExitStatus::SUCCESS
833    }
834
835    /// `more`: passes standard input through (the non-interactive form;
836    /// real `more` paginates on a terminal, and piping the virtual
837    /// terminal's paging is a later refinement).
838    fn builtin_more(&self, stdin: &mut dyn Input, stdout: &mut dyn Output) -> ExitStatus {
839        let mut buffer = [0u8; 4096];
840        loop {
841            match stdin.read(&mut buffer) {
842                Ok(0) => break,
843                Ok(count) => {
844                    if stdout.write(&buffer[..count]).is_err() {
845                        return ExitStatus::FAILURE;
846                    }
847                }
848                Err(_) => return ExitStatus::FAILURE,
849            }
850        }
851        ExitStatus::SUCCESS
852    }
853
854    fn builtin_exit(&mut self, argv: &[String]) -> ExitStatus {
855        // `exit [N]` ends the session; `exit /b [N]` is accepted for
856        // batch compatibility.
857        let argument = argv
858            .iter()
859            .skip(1)
860            .find(|argument| !argument.eq_ignore_ascii_case("/b"));
861        let code = argument
862            .and_then(|value| value.trim().parse::<i64>().ok())
863            .map_or(0, |value| u8::try_from(value & 0xFF).unwrap_or(0));
864        let status = ExitStatus::new(code);
865        self.exit_request = Some(status);
866        status
867    }
868}
869
870/// Splits a glued builtin invocation like `echo.` or `cd..` into its
871/// command name and the remainder (cmd does not require a space).
872fn split_glued_name(word: &str) -> Option<(String, String)> {
873    let lower = word.to_ascii_lowercase();
874    for name in [
875        "echo", "cd", "chdir", "dir", "type", "cls", "set", "del", "erase", "mkdir", "md", "rmdir",
876        "rd", "copy", "ren", "rename", "ver", "date", "time", "title", "color", "pause", "exit",
877        "more",
878    ] {
879        if lower.starts_with(name) && lower.len() > name.len() {
880            return Some((word[..name.len()].to_owned(), word[name.len()..].to_owned()));
881        }
882    }
883    None
884}
885
886/// Which stream a redirection targets.
887#[derive(Clone, Copy, PartialEq, Eq)]
888enum OutputStream {
889    Stdout,
890    Stderr,
891    Stdin,
892}
893
894/// Splits a command line into words, respecting double quotes (cmd does
895/// not treat single quotes specially). `@` prefixes and `%VAR%` expansion
896/// are handled by the caller.
897fn split_words(text: &str) -> Vec<String> {
898    let mut words = Vec::new();
899    let mut current = String::new();
900    let mut quoted = false;
901    for ch in text.chars() {
902        match ch {
903            '"' => quoted = !quoted,
904            ' ' | '\t' if !quoted => {
905                if !current.is_empty() {
906                    words.push(std::mem::take(&mut current));
907                }
908            }
909            _ => current.push(ch),
910        }
911    }
912    if !current.is_empty() {
913        words.push(current);
914    }
915    words
916}
917
918/// Parses `>` / `>>` / `2>` / `2>>` / `<` redirections from a command
919/// line, returning the command text and the parsed redirections.
920fn parse_redirects(text: &str) -> (String, Vec<(OutputStream, String, bool)>) {
921    let mut command = String::new();
922    let mut redirects = Vec::new();
923    let mut chars = text.chars().peekable();
924    let mut quoted = false;
925    while let Some(ch) = chars.next() {
926        match ch {
927            '"' => {
928                quoted = !quoted;
929                command.push(ch);
930            }
931            '>' | '<' | '2' if !quoted => {
932                // Handle `2>` (stderr) — only when `2` is followed by a
933                // redirect operator.
934                if ch == '2' {
935                    if matches!(chars.peek(), Some('>')) {
936                        chars.next();
937                        let append = chars.peek() == Some(&'>');
938                        if append {
939                            chars.next();
940                        }
941                        let target = read_redirect_target(&mut chars);
942                        redirects.push((OutputStream::Stderr, target, append));
943                        continue;
944                    }
945                    command.push(ch);
946                    continue;
947                }
948                let stream = if ch == '<' {
949                    OutputStream::Stdin
950                } else {
951                    OutputStream::Stdout
952                };
953                let append = if stream == OutputStream::Stdout {
954                    chars.peek() == Some(&'>')
955                } else {
956                    false
957                };
958                if append {
959                    chars.next();
960                }
961                let target = read_redirect_target(&mut chars);
962                redirects.push((stream, target, append));
963            }
964            _ => command.push(ch),
965        }
966    }
967    (command.trim().to_owned(), redirects)
968}
969
970/// Reads the target filename after a redirect operator: the next word.
971fn read_redirect_target(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
972    // Skip the whitespace between the operator and the target.
973    while chars.peek().is_some_and(|ch| matches!(ch, ' ' | '\t')) {
974        chars.next();
975    }
976    let mut target = String::new();
977    while let Some(&ch) = chars.peek() {
978        match ch {
979            '"' => {
980                chars.next();
981            }
982            ' ' | '\t' => break,
983            '>' | '<' => break,
984            _ => {
985                chars.next();
986                target.push(ch);
987            }
988        }
989    }
990    target
991}
992
993/// Splits a line into `|`-joined pipeline stages and `&`/`&&`/`||`
994/// statement separators.
995///
996/// Returns the stages of the first statement, then the separator before
997/// each following statement and its stages.
998fn split_line(line: &str) -> Vec<(Option<Separator>, Vec<String>)> {
999    let mut statements: Vec<(Option<Separator>, Vec<String>)> = Vec::new();
1000    let mut stages: Vec<String> = Vec::new();
1001    let mut current = String::new();
1002    let mut quoted = false;
1003    let mut pending: Option<Separator> = None;
1004    let mut chars = line.chars().peekable();
1005    while let Some(ch) = chars.next() {
1006        match ch {
1007            '"' => {
1008                quoted = !quoted;
1009                current.push(ch);
1010            }
1011            '&' | '|' if !quoted => {
1012                // `&&`, `||` are the operators; a bare `&` or `|` is
1013                // their single-char form.
1014                let next = chars.peek();
1015                let (separator, consumed) = match (ch, next) {
1016                    ('&', Some('&')) => (Separator::AndAnd, true),
1017                    ('|', Some('|')) => (Separator::OrOr, true),
1018                    ('&', _) => (Separator::Always, false),
1019                    ('|', _) => (Separator::Pipe, false),
1020                    _ => unreachable!(),
1021                };
1022                if consumed {
1023                    chars.next();
1024                }
1025                if !current.trim().is_empty() {
1026                    stages.push(current.trim().to_owned());
1027                }
1028                current.clear();
1029                if separator == Separator::Pipe {
1030                    continue;
1031                }
1032                if !stages.is_empty() {
1033                    statements.push((pending.take(), std::mem::take(&mut stages)));
1034                }
1035                pending = Some(separator);
1036            }
1037            _ => current.push(ch),
1038        }
1039    }
1040    if !current.trim().is_empty() {
1041        stages.push(current.trim().to_owned());
1042    }
1043    if !stages.is_empty() {
1044        statements.push((pending.take(), stages));
1045    }
1046    statements
1047}
1048
1049/// A statement separator between pipeline groups.
1050#[derive(Clone, Copy, PartialEq, Eq)]
1051enum Separator {
1052    /// `&&`: run only when the previous statement succeeded.
1053    AndAnd,
1054    /// `||`: run only when the previous statement failed.
1055    OrOr,
1056    /// `&`: run unconditionally.
1057    Always,
1058    /// `|`: joins stages within one statement (never appears as a
1059    /// statement separator; it is consumed while grouping stages).
1060    Pipe,
1061}
1062
1063impl<'os> crate::Shell for Cmd<'os> {
1064    fn name(&self) -> &'static str {
1065        "cmd"
1066    }
1067
1068    fn engine(&self) -> &engine::Engine {
1069        self.os.engine()
1070    }
1071
1072    fn actor(&self) -> engine::ActorId {
1073        self.actor
1074    }
1075
1076    fn environment(&self) -> &os::Environment {
1077        &self.environment
1078    }
1079
1080    fn boot_time(&self) -> Timestamp {
1081        self.os.boot_time()
1082    }
1083
1084    fn hostname(&self) -> String {
1085        self.environment
1086            .get("COMPUTERNAME")
1087            .unwrap_or("vce")
1088            .to_owned()
1089    }
1090
1091    fn cwd(&self) -> &VirtualPath {
1092        &self.cwd
1093    }
1094
1095    fn prompt(&self, _hostname: &str) -> String {
1096        format!("{}>", self.display_path(&self.cwd))
1097    }
1098
1099    fn banner(&self) -> Option<String> {
1100        // The classic cmd startup banner.
1101        Some(format!(
1102            "{WINDOWS_VERSION}\n(c) Microsoft Corporation. All rights reserved.\n"
1103        ))
1104    }
1105
1106    fn set_terminal_size(&mut self, rows: u16, cols: u16) {
1107        self.environment.set("COLUMNS", cols.to_string());
1108        self.environment.set("LINES", rows.to_string());
1109    }
1110
1111    fn execute(
1112        &mut self,
1113        line: &str,
1114        stdin: &mut dyn Input,
1115        stdout: &mut dyn Output,
1116        stderr: &mut dyn Output,
1117    ) -> ExitStatus {
1118        self.run_line(line, stdin, stdout, stderr)
1119    }
1120
1121    fn execute_with_terminal(
1122        &mut self,
1123        line: &str,
1124        stdin: &mut dyn Input,
1125        stdout: &mut dyn Output,
1126        stderr: &mut dyn Output,
1127        _terminal: Option<&mut dyn Terminal>,
1128    ) -> ExitStatus {
1129        self.run_line(line, stdin, stdout, stderr)
1130    }
1131
1132    fn take_exit_status(&mut self) -> Option<ExitStatus> {
1133        self.exit_request.take()
1134    }
1135
1136    fn history(&self) -> &[String] {
1137        &self.history
1138    }
1139
1140    fn record_history(&mut self, line: &str) {
1141        if line.trim().is_empty() {
1142            return;
1143        }
1144        self.history.push(line.to_owned());
1145        if self.history.len() > crate::HISTORY_LIMIT {
1146            self.history.remove(0);
1147        }
1148    }
1149
1150    fn needs_continuation(&self, _input: &str) -> bool {
1151        // cmd has no multi-line constructs at the prompt.
1152        false
1153    }
1154}
1155
1156impl<'os> Cmd<'os> {
1157    /// Executes one line: statements joined by `&`, `&&`, `||`, with
1158    /// `|` pipelines within them. `%errorlevel%` follows each command.
1159    fn run_line(
1160        &mut self,
1161        line: &str,
1162        stdin: &mut dyn Input,
1163        stdout: &mut dyn Output,
1164        stderr: &mut dyn Output,
1165    ) -> ExitStatus {
1166        let line = line.trim();
1167        if line.is_empty() {
1168            return ExitStatus::SUCCESS;
1169        }
1170        let statements = split_line(line);
1171        let mut last_status = ExitStatus::SUCCESS;
1172        for (separator, stages) in statements {
1173            let should_run = match separator {
1174                None | Some(Separator::Always) => true,
1175                Some(Separator::AndAnd) => last_status.is_success(),
1176                Some(Separator::OrOr) => !last_status.is_success(),
1177                // A trailing `|` never ends a line in practice; a pipeline
1178                // group always runs.
1179                _ => true,
1180            };
1181            if !should_run {
1182                continue;
1183            }
1184            last_status = self.run_pipeline(&stages, stdin, stdout, stderr);
1185            self.environment
1186                .set("errorlevel", last_status.code().to_string());
1187        }
1188        last_status
1189    }
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    use super::*;
1195    use crate::Shell as _;
1196
1197    fn session() -> (Box<Cmd<'static>>, &'static Windows) {
1198        let windows = Box::leak(Box::new(
1199            Windows::with_identity(
1200                &os::HostIdentity::new("demo", "demo-host"),
1201                Timestamp::from_nanos(1_000_000),
1202            )
1203            .unwrap(),
1204        ));
1205        let actor = windows.authenticate("demo", "demo").unwrap();
1206        let shell = Box::new(Cmd::new(windows, actor, windows.environment().clone()).unwrap());
1207        (shell, windows)
1208    }
1209
1210    fn run(shell: &mut Cmd<'_>, line: &str) -> (ExitStatus, String, String) {
1211        let mut stdin = BytesInput::new(Vec::new());
1212        let mut stdout = BytesOutput::new();
1213        let mut stderr = BytesOutput::new();
1214        let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
1215        (
1216            status,
1217            String::from_utf8_lossy(&stdout.into_bytes()).into_owned(),
1218            String::from_utf8_lossy(&stderr.into_bytes()).into_owned(),
1219        )
1220    }
1221
1222    #[test]
1223    fn echo_prints_and_joins_arguments() {
1224        let (mut shell, _windows) = session();
1225        let (status, out, _) = run(&mut shell, "echo hello world");
1226        assert!(status.is_success());
1227        assert_eq!(out, "hello world\n");
1228    }
1229
1230    #[test]
1231    fn echo_blank_line_and_bare_echo() {
1232        let (mut shell, _windows) = session();
1233        let (_, out, _) = run(&mut shell, "echo.");
1234        assert_eq!(out, "\n");
1235        let (_, out, _) = run(&mut shell, "echo");
1236        assert_eq!(out, "ECHO is on.\n");
1237    }
1238
1239    #[test]
1240    fn percent_variables_expand() {
1241        let (mut shell, _windows) = session();
1242        run(&mut shell, "set GREETING=Hello");
1243        let (_, out, _) = run(&mut shell, "echo %GREETING% world");
1244        assert_eq!(out, "Hello world\n");
1245        let (_, out, _) = run(&mut shell, "echo %greeting%");
1246        assert_eq!(out, "Hello\n", "expansion is case-insensitive");
1247    }
1248
1249    #[test]
1250    fn errorlevel_follows_the_last_command() {
1251        let (mut shell, _windows) = session();
1252        let (_, out, _) = run(&mut shell, "type does-not-exist.txt & echo %errorlevel%");
1253        assert_eq!(out, "1\n");
1254        let (_, out, _) = run(&mut shell, "echo ok & echo %errorlevel%");
1255        assert_eq!(out, "ok\n0\n");
1256    }
1257
1258    #[test]
1259    fn andand_and_oror_conditionals() {
1260        let (mut shell, _windows) = session();
1261        let (status, out, _) = run(&mut shell, "echo one && echo two");
1262        assert!(status.is_success());
1263        assert_eq!(out, "one\ntwo\n");
1264        let (status, out, _) = run(&mut shell, "type nope && echo two || echo fallback");
1265        assert!(status.is_success());
1266        assert!(out.contains("fallback\n"));
1267        assert!(!out.contains("two\n"));
1268    }
1269
1270    #[test]
1271    fn redirection_writes_a_file() {
1272        let (mut shell, _windows) = session();
1273        let (_, _, _) = run(&mut shell, "echo hello > hello.txt");
1274        let (_, out, _) = run(&mut shell, "type hello.txt");
1275        assert_eq!(out, "hello\n");
1276        let (_, _, _) = run(&mut shell, "echo world >> hello.txt");
1277        let (_, out, _) = run(&mut shell, "type hello.txt");
1278        assert_eq!(out, "hello\nworld\n");
1279    }
1280
1281    #[test]
1282    fn cd_and_dir_agree_with_the_filesystem() {
1283        let (mut shell, _windows) = session();
1284        run(&mut shell, "mkdir Work");
1285        let (status, _, _) = run(&mut shell, "cd Work");
1286        assert!(status.is_success());
1287        let (_, out, _) = run(&mut shell, "cd");
1288        assert!(out.contains("Work"), "cd alone prints the cwd: {out}");
1289    }
1290
1291    #[test]
1292    fn pipeline_connects_stdout_to_stdin() {
1293        let (mut shell, _windows) = session();
1294        let (_, out, _) = run(&mut shell, "echo hello | more");
1295        assert_eq!(out, "hello\n");
1296        let (_, out, _) = run(&mut shell, "dir /b | more");
1297        assert!(
1298            out.contains("Desktop"),
1299            "the profile listing flows through the pipeline: {out}"
1300        );
1301    }
1302
1303    #[test]
1304    fn ver_and_exit_work() {
1305        let (mut shell, _windows) = session();
1306        let (_, out, _) = run(&mut shell, "ver");
1307        assert!(out.contains("Microsoft Windows"));
1308        run(&mut shell, "exit 3");
1309        assert_eq!(shell.take_exit_status().map(|s| s.code()), Some(3));
1310    }
1311
1312    #[test]
1313    fn external_commands_resolve() {
1314        let (mut shell, _windows) = session();
1315        let (status, out, _) = run(&mut shell, "hostname");
1316        assert!(status.is_success());
1317        assert!(!out.trim().is_empty());
1318        let (status, out, _) = run(&mut shell, "whoami");
1319        assert!(status.is_success());
1320        assert!(!out.trim().is_empty());
1321        let (status, out, _) = run(&mut shell, "tasklist");
1322        assert!(status.is_success());
1323        assert!(out.contains("hostname") || out.contains("PID"));
1324    }
1325
1326    #[test]
1327    fn unknown_command_reports_cmd_error() {
1328        let (mut shell, _windows) = session();
1329        let (status, _, err) = run(&mut shell, "frobnicate");
1330        assert_eq!(status, ExitStatus::NOT_FOUND);
1331        assert!(err.contains("not recognized as an internal or external command"));
1332    }
1333}