Repository navigation
Expand file tree
/
Copy pathcli.rs
More file actions
880 lines (827 loc) · 30.3 KB
/
Copy pathcli.rs
File metadata and controls
880 lines (827 loc) · 30.3 KB
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use std::ffi::OsString;
use std::fmt::Write as _;
use std::io;
use std::iter::Peekable;
use std::path::PathBuf;
use browser::{
AgentOptions, InvalidCa, InvalidIdentity, InvalidProxy, InvalidResolveRule, Profile,
ProfileError, Proxy, RendererSandbox, TrustedCa, ValidIdentity,
};
use logging::Level;
pub(crate) struct Cli {
pub(crate) log_level: Option<Level>,
pub(crate) log_file: Option<PathBuf>,
pub(crate) verbose: bool,
pub(crate) sandbox: RendererSandbox,
pub(crate) mode: Mode,
}
pub(crate) struct DaemonConfig {
pub(crate) port: Option<u16>,
pub(crate) profile: Profile,
pub(crate) network: AgentOptions,
}
pub(crate) enum Mode {
Daemon(DaemonMode),
Extension,
Renderer,
}
pub(crate) enum DaemonMode {
Start {
config: Box<DaemonConfig>,
command_index: usize,
},
Serve(Box<DaemonConfig>),
Stop {
profile: Profile,
},
Status {
profile: Profile,
},
}
pub(crate) enum Outcome {
Help(&'static CommandSpec),
Version,
Run(Box<Cli>),
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliError {
#[error("Invalid UTF-8 was detected in one or more arguments")]
NotUtf8,
#[error("missing command; expected daemon or extension")]
MissingCommand,
#[error("missing subcommand for 'daemon'; expected start, status, stop, or serve")]
MissingDaemonCommand,
#[error("a value is required for '--{flag} {placeholder}' but none was supplied")]
MissingValue {
flag: &'static str,
placeholder: &'static str,
},
#[error("the argument '{spelling}' was provided more than once")]
Repeated { spelling: &'static str },
#[error("unexpected value for '--{flag}'")]
UnexpectedValue { flag: &'static str },
#[error("unexpected argument '{0}' found")]
UnexpectedArgument(String),
#[error("invalid value '{0}' for '--port <PORT>'")]
InvalidPort(String),
#[error(transparent)]
InvalidProfile(#[from] ProfileError),
#[error(transparent)]
InvalidLogLevel(#[from] logging::ParseLevelError),
#[error(transparent)]
InvalidResolve(#[from] InvalidResolveRule),
#[error(transparent)]
InvalidProxy(#[from] InvalidProxy),
#[error("--user-agent: {0}")]
InvalidUserAgent(#[from] InvalidIdentity),
#[error("--tls-ca {}: {source}", path.display())]
TlsCa { path: PathBuf, source: TlsCaError },
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum TlsCaError {
#[error(transparent)]
Read(#[from] io::Error),
#[error(transparent)]
Parse(#[from] InvalidCa),
}
pub(crate) struct CommandSpec {
pub(crate) name: &'static str,
pub(crate) summary: &'static str,
pub(crate) about: &'static str,
pub(crate) usage: &'static str,
pub(crate) subcommands: &'static [&'static CommandSpec],
pub(crate) options: &'static [OptionGroup],
pub(crate) sections: &'static [HelpSection],
}
pub(crate) struct OptionGroup {
pub(crate) heading: &'static str,
pub(crate) options: &'static [OptionSpec],
}
pub(crate) struct OptionSpec {
pub(crate) short: Option<&'static str>,
pub(crate) long: &'static str,
pub(crate) description: &'static [&'static str],
}
pub(crate) struct HelpSection {
pub(crate) heading: &'static str,
pub(crate) lines: &'static [&'static str],
}
impl CommandSpec {
pub(crate) fn render_help(&self) -> String {
let mut out = String::new();
let _ = writeln!(out, "{}\n", self.about);
let _ = writeln!(out, "Usage: {}", self.usage);
if !self.subcommands.is_empty() {
out.push_str("\nCommands:\n");
let width = self
.subcommands
.iter()
.map(|cmd| cmd.name.len())
.max()
.unwrap_or(0);
for cmd in self.subcommands {
let _ = writeln!(out, " {:<width$} {}", cmd.name, cmd.summary);
}
}
for group in self.options {
let _ = writeln!(out, "\n{}:", group.heading);
for opt in group.options {
match opt.short {
Some(short) => {
let _ = writeln!(out, " {short}, {}", opt.long);
}
None => {
let _ = writeln!(out, " {}", opt.long);
}
}
for line in opt.description {
let _ = writeln!(out, " {line}");
}
}
}
for section in self.sections {
let _ = writeln!(out, "\n{}:", section.heading);
for line in section.lines {
let _ = writeln!(out, " {line}");
}
}
out
}
}
const HELP_OPTION: OptionSpec = OptionSpec {
short: Some("-h"),
long: "--help",
description: &["Print help to stdout and exit 0"],
};
const ROOT_HELP_OPTION: OptionSpec = OptionSpec {
short: Some("-h"),
long: "--help",
description: &["Print help to stdout and exit 0 (use `<COMMAND> --help` for subcommand help)"],
};
const VERSION_OPTION: OptionSpec = OptionSpec {
short: Some("-v, -V"),
long: "--version",
description: &["Print `tinybrowser <version>` to stdout and exit 0"],
};
const PROFILE_OPTION: OptionSpec = OptionSpec {
short: None,
long: "--profile <NAME>",
description: &["Profile name (`[A-Za-z0-9._-]+`, max 64 bytes) [default: default]"],
};
const RENDERER_OPTION: OptionSpec = OptionSpec {
short: None,
long: "--renderer",
description: &[
"Internal: run a child renderer worker over inherited file descriptor 0.",
"Spawned automatically by the daemon; cannot be combined with commands or daemon options.",
],
};
const ROOT_OPTIONS: &[OptionGroup] = &[OptionGroup {
heading: "Options",
options: &[RENDERER_OPTION, VERSION_OPTION, ROOT_HELP_OPTION],
}];
const STANDARD_OPTIONS: &[OptionGroup] = &[OptionGroup {
heading: "Options",
options: &[VERSION_OPTION, HELP_OPTION],
}];
const DAEMON_CONTROL_OPTIONS: &[OptionGroup] = &[OptionGroup {
heading: "Options",
options: &[PROFILE_OPTION, VERSION_OPTION, HELP_OPTION],
}];
const DAEMON_RUN_OPTIONS: &[OptionGroup] = &[OptionGroup {
heading: "Options",
options: &[
PROFILE_OPTION,
OptionSpec {
short: None,
long: "--port <PORT>",
description: &[
"Bind `127.0.0.1:<PORT>` (`0..=65535`; default `0` selects an ephemeral port)",
],
},
OptionSpec {
short: None,
long: "--proxy <URI>",
description: &[
"Outbound HTTP/HTTPS proxy (`http://<host>[:<port>]` or `https://<host>[:<port>]`)",
],
},
OptionSpec {
short: None,
long: "--user-agent <VALUE>",
description: &[
"Browser identity: `tinybrowser` (default), `chrome`, or a custom User-Agent string",
],
},
OptionSpec {
short: None,
long: "--resolve <PATTERN=ADDR>",
description: &[
"Override DNS resolution (repeatable): `<host|*.domain>=<ip>[:<port>|fail]`",
],
},
OptionSpec {
short: None,
long: "--tls-ca <PATH>",
description: &["Trust an additional PEM CA certificate file (repeatable)"],
},
OptionSpec {
short: None,
long: "--log-level <LEVEL>",
description: &[
"Minimum log level: `error`, `warn`, `info`, `debug`, or `trace` [default: info]",
"Overrides `TINYBROWSER_LOG`.",
],
},
OptionSpec {
short: None,
long: "--log-file <PATH>",
description: &[
"Write logs to `<PATH>` instead of `$XDG_DATA_HOME/tinybrowser/logs/<profile>.log`",
],
},
OptionSpec {
short: None,
long: "--verbose",
description: &["Shorthand for `--log-level=debug`"],
},
OptionSpec {
short: None,
long: "--no-sandbox",
description: &[
"Disable the renderer OS process sandbox (Landlock/seccomp, Seatbelt, Job Object).",
"Dangerous: use only inside an already-isolated container or sandbox where the host",
"kernel does not permit the renderer sandbox.",
],
},
VERSION_OPTION,
HELP_OPTION,
],
}];
const ROOT_SECTIONS: &[HelpSection] = &[
HelpSection {
heading: "Workflow",
lines: &[
"1. Start the browser once per profile (stays open across tabs and commands):",
" tinybrowser daemon start",
" Waits until the server is bound and a renderer is verified ready, then prints:",
r#" {"profile":"default","pid":12345,"host":"127.0.0.1","port":41234,"url":"http://127.0.0.1:41234"}"#,
" Running `tinybrowser daemon start` again for the same profile reuses the running daemon.",
"2. Connect any CDP or W3C WebDriver client to `http://127.0.0.1:<port>`:",
" - Playwright / CDP: `chromium.connectOverCDP(\"http://127.0.0.1:<port>\")`",
" One blank page target is pre-created at startup (`browser.contexts()[0].pages()[0]`).",
r#" - W3C WebDriver: `POST http://127.0.0.1:<port>/session` with body `{"capabilities":{}}`"#,
"3. Inspect or stop explicitly when done:",
" tinybrowser daemon status",
" tinybrowser daemon stop",
],
},
HelpSection {
heading: "Exit codes",
lines: &[
"0 Success (`--help`, `--version`, `daemon start`, `daemon stop`, healthy `daemon status`, or clean `daemon serve` exit)",
"1 Runtime, renderer startup, bind, or I/O failure, or `daemon status` when daemon is stopped/unhealthy",
"2 Command-line usage or flag validation error (details written to stderr)",
],
},
HelpSection {
heading: "Documentation",
lines: &[
"Full documentation, WebAssembly cheatsheet, and source pointers: https://tinybrowser.ericc.ch/#documentation",
],
},
];
const DAEMON_SECTIONS: &[HelpSection] = &[
HelpSection {
heading: "Endpoints (http://127.0.0.1:<port>)",
lines: &[
"GET /json/version CDP browser metadata and `webSocketDebuggerUrl`",
"GET /json/list CDP open page targets (alias: `GET /json`)",
"WS /devtools/browser CDP browser WebSocket (flattened `sessionId` routing)",
"WS /devtools/page/<id> CDP page target WebSocket",
r#"GET /status WebDriver readiness probe (`{"value":{"ready":true,"message":"ready"}}`)"#,
"POST /session WebDriver Classic create session (one active session at a time)",
"* /session/<id>/... WebDriver Classic session commands (`url`, `execute/sync`, `execute/async`,",
" `element`, `elements`, `screenshot`, `window`, `cookie`, `timeouts`,",
" `actions`, `permissions`)",
"WS /session WebDriver BiDi WebSocket (standalone BiDi session)",
"WS /session/<id> WebDriver BiDi WebSocket attached to an existing Classic session",
],
},
HelpSection {
heading: "Request requirements",
lines: &[
"- `Host` header must name a loopback host (`127.0.0.1`, `localhost`, or `[::1]`).",
"- Omit the `Origin` header (requests with `Origin` return `403 Forbidden`).",
"- Browser Fetch Metadata headers indicating a page request (`Sec-Fetch-Site` other than `none`,",
" `Sec-Fetch-Mode` other than `cors`, `Sec-Fetch-Dest` other than `empty`, or `Sec-Fetch-User`)",
" return `403 Forbidden`.",
"- WebDriver `POST` requests with a `Content-Type` header must use `application/json`.",
],
},
HelpSection {
heading: "Paths",
lines: &[
"Runtime endpoint: `$XDG_RUNTIME_DIR/tinybrowser/<profile>/daemon.json`",
"Profile lock: `$XDG_RUNTIME_DIR/tinybrowser/<profile>/lock`",
"Startup lock: `$XDG_RUNTIME_DIR/tinybrowser/<profile>/start.lock`",
"Profile storage: `$XDG_DATA_HOME/tinybrowser/profiles/<profile>/`",
"Default log file: `$XDG_DATA_HOME/tinybrowser/logs/<profile>.log`",
],
},
];
static ROOT_SPEC: CommandSpec = CommandSpec {
name: "tinybrowser",
summary: "Tiny headless web browser",
about: "Tiny headless web browser (CDP + W3C WebDriver on one loopback port).",
usage: "tinybrowser <COMMAND> [OPTIONS]",
subcommands: &[&DAEMON_SPEC, &EXTENSION_SPEC],
options: ROOT_OPTIONS,
sections: ROOT_SECTIONS,
};
static DAEMON_SPEC: CommandSpec = CommandSpec {
name: "daemon",
summary: "Manage the profile-locked browser daemon",
about: "Manage the profile-locked browser daemon (CDP + W3C WebDriver on one loopback port).",
usage: "tinybrowser daemon <COMMAND> [OPTIONS]",
subcommands: &[
&DAEMON_START_SPEC,
&DAEMON_STATUS_SPEC,
&DAEMON_STOP_SPEC,
&DAEMON_SERVE_SPEC,
],
options: STANDARD_OPTIONS,
sections: DAEMON_SECTIONS,
};
static DAEMON_START_SPEC: CommandSpec = CommandSpec {
name: "start",
summary: "Start the browser daemon in the background and wait until ready",
about: "Start the browser daemon in the background and wait until ready.",
usage: "tinybrowser daemon start [OPTIONS]",
subcommands: &[],
options: DAEMON_RUN_OPTIONS,
sections: &[],
};
static DAEMON_STATUS_SPEC: CommandSpec = CommandSpec {
name: "status",
summary: "Report daemon status and endpoint as JSON (exits 1 when stopped or crashed)",
about: "Report daemon status and endpoint as JSON (exits 1 when stopped or crashed).",
usage: "tinybrowser daemon status [OPTIONS]",
subcommands: &[],
options: DAEMON_CONTROL_OPTIONS,
sections: &[],
};
static DAEMON_STOP_SPEC: CommandSpec = CommandSpec {
name: "stop",
summary: "Gracefully stop the running daemon for a profile",
about: "Gracefully stop the running daemon for a profile.",
usage: "tinybrowser daemon stop [OPTIONS]",
subcommands: &[],
options: DAEMON_CONTROL_OPTIONS,
sections: &[],
};
static DAEMON_SERVE_SPEC: CommandSpec = CommandSpec {
name: "serve",
summary: "Run the browser daemon in the foreground (for supervisors / containers)",
about: "Run the browser daemon in the foreground (for supervisors / containers).",
usage: "tinybrowser daemon serve [OPTIONS]",
subcommands: &[],
options: DAEMON_RUN_OPTIONS,
sections: &[],
};
static EXTENSION_SPEC: CommandSpec = CommandSpec {
name: "extension",
summary: "Manage web extensions from the Chrome Web Store (reserved; not yet implemented)",
about: "Manage web extensions from the Chrome Web Store (reserved; not yet implemented).",
usage: "tinybrowser extension [OPTIONS]",
subcommands: &[],
options: STANDARD_OPTIONS,
sections: &[],
};
pub(crate) fn parse(args: impl Iterator<Item = OsString>) -> Result<Outcome, CliError> {
Scanner::new(args).scan()
}
struct Scanner<I: Iterator<Item = OsString>> {
args: Peekable<I>,
index: usize,
saw_any: bool,
end_of_flags: bool,
path: CommandPath,
action_index: Option<usize>,
log_level: Option<Level>,
log_file: Option<PathBuf>,
verbose: bool,
sandbox: Option<RendererSandbox>,
profile: Option<Profile>,
port: Option<u16>,
user_agent: Option<ValidIdentity>,
network: AgentOptions,
tls_ca: Vec<PathBuf>,
first_flag: Option<&'static str>,
first_daemon_run_flag: Option<&'static str>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CommandPath {
Root,
Daemon(Option<DaemonAction>),
Extension,
Renderer,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum DaemonAction {
Start,
Serve,
Stop,
Status,
}
impl CommandPath {
fn spec(self) -> &'static CommandSpec {
match self {
Self::Root | Self::Renderer => &ROOT_SPEC,
Self::Daemon(None) => &DAEMON_SPEC,
Self::Daemon(Some(DaemonAction::Start)) => &DAEMON_START_SPEC,
Self::Daemon(Some(DaemonAction::Serve)) => &DAEMON_SERVE_SPEC,
Self::Daemon(Some(DaemonAction::Stop)) => &DAEMON_STOP_SPEC,
Self::Daemon(Some(DaemonAction::Status)) => &DAEMON_STATUS_SPEC,
Self::Extension => &EXTENSION_SPEC,
}
}
}
impl<I: Iterator<Item = OsString>> Scanner<I> {
fn new(args: I) -> Self {
Self {
args: args.peekable(),
index: 0,
saw_any: false,
end_of_flags: false,
path: CommandPath::Root,
action_index: None,
log_level: None,
log_file: None,
verbose: false,
sandbox: None,
profile: None,
port: None,
user_agent: None,
network: AgentOptions::default(),
tls_ca: Vec::new(),
first_flag: None,
first_daemon_run_flag: None,
}
}
fn scan(mut self) -> Result<Outcome, CliError> {
while let Some(arg) = self.next_arg() {
let token_index = self.index - 1;
self.saw_any = true;
let text = arg.to_str().ok_or(CliError::NotUtf8)?;
if let Some(outcome) = self.token(text, token_index)? {
return Ok(outcome);
}
}
self.finish()
}
fn next_arg(&mut self) -> Option<OsString> {
let arg = self.args.next()?;
self.index += 1;
Some(arg)
}
fn record_flag(&mut self, name: &'static str) {
if self.first_flag.is_none() {
self.first_flag = Some(name);
}
}
fn token(&mut self, text: &str, token_index: usize) -> Result<Option<Outcome>, CliError> {
if self.end_of_flags {
return Err(CliError::UnexpectedArgument(text.to_owned()));
}
if text == "--" {
self.end_of_flags = true;
return Ok(None);
}
if let Some(long) = text.strip_prefix("--") {
return self.long(long);
}
if let Some(short) = text.strip_prefix('-')
&& !short.is_empty()
{
return self.short(short);
}
self.subcommand(text, token_index)
}
fn subcommand(&mut self, text: &str, token_index: usize) -> Result<Option<Outcome>, CliError> {
match self.path {
CommandPath::Root => match text {
"daemon" => {
self.path = CommandPath::Daemon(None);
Ok(None)
}
"extension" => {
self.path = CommandPath::Extension;
Ok(None)
}
_ => Err(CliError::UnexpectedArgument(text.to_owned())),
},
CommandPath::Daemon(None) => {
let action = match text {
"start" => DaemonAction::Start,
"serve" => DaemonAction::Serve,
"stop" => DaemonAction::Stop,
"status" => DaemonAction::Status,
_ => return Err(CliError::UnexpectedArgument(text.to_owned())),
};
self.path = CommandPath::Daemon(Some(action));
self.action_index = Some(token_index);
Ok(None)
}
CommandPath::Daemon(Some(_)) | CommandPath::Extension | CommandPath::Renderer => {
Err(CliError::UnexpectedArgument(text.to_owned()))
}
}
}
fn long(&mut self, long: &str) -> Result<Option<Outcome>, CliError> {
let (name, inline) = match long.split_once('=') {
Some((name, value)) => (name, Some(value)),
None => (long, None),
};
match name {
"version" => {
if inline.is_some() {
return Err(CliError::UnexpectedValue { flag: "version" });
}
Ok(Some(Outcome::Version))
}
"help" => {
if inline.is_some() {
return Err(CliError::UnexpectedValue { flag: "help" });
}
Ok(Some(Outcome::Help(self.path.spec())))
}
"renderer" => {
if inline.is_some() {
return Err(CliError::UnexpectedValue { flag: "renderer" });
}
match self.path {
CommandPath::Root => {
self.path = CommandPath::Renderer;
Ok(None)
}
CommandPath::Renderer => Err(CliError::Repeated {
spelling: "--renderer",
}),
CommandPath::Daemon(_) | CommandPath::Extension => Err(unexpected("renderer")),
}
}
"log-level" => {
let raw = self.value("log-level", "<LEVEL>", inline)?;
if self.log_level.is_some() {
return Err(CliError::Repeated {
spelling: "--log-level <LEVEL>",
});
}
self.log_level = Some(raw.parse()?);
self.record_flag("log-level");
Ok(None)
}
"log-file" => {
let raw = self.value("log-file", "<PATH>", inline)?;
if self.log_file.is_some() {
return Err(CliError::Repeated {
spelling: "--log-file <PATH>",
});
}
self.log_file = Some(PathBuf::from(&raw));
self.record_flag("log-file");
Ok(None)
}
"verbose" => {
if inline.is_some() {
return Err(CliError::UnexpectedValue { flag: "verbose" });
}
if self.verbose {
return Err(CliError::Repeated {
spelling: "--verbose",
});
}
self.verbose = true;
self.record_flag("verbose");
Ok(None)
}
"no-sandbox" => {
if inline.is_some() {
return Err(CliError::UnexpectedValue { flag: "no-sandbox" });
}
if self.sandbox.is_some() {
return Err(CliError::Repeated {
spelling: "--no-sandbox",
});
}
self.sandbox = Some(RendererSandbox::Disabled);
self.record_flag("no-sandbox");
Ok(None)
}
"profile" => {
let raw = self.value("profile", "<NAME>", inline)?;
let profile = Profile::parse(&raw)?;
if self.profile.is_some() {
return Err(CliError::Repeated {
spelling: "--profile <NAME>",
});
}
self.profile = Some(profile);
self.record_flag("profile");
Ok(None)
}
_ => self.daemon_run_flag(name, inline),
}
}
fn daemon_run_flag(
&mut self,
name: &str,
inline: Option<&str>,
) -> Result<Option<Outcome>, CliError> {
let flag_name = match name {
"port" => {
let raw = self.value("port", "<PORT>", inline)?;
let port: u16 = raw
.parse()
.map_err(|_| CliError::InvalidPort(raw.clone()))?;
if self.port.is_some() {
return Err(CliError::Repeated {
spelling: "--port <PORT>",
});
}
self.port = Some(port);
"port"
}
"resolve" => {
let raw = self.value("resolve", "<PATTERN=ADDR>", inline)?;
let rule = raw.parse()?;
self.network.resolve.push(rule);
"resolve"
}
"tls-ca" => {
let raw = self.value("tls-ca", "<PATH>", inline)?;
self.tls_ca.push(PathBuf::from(&raw));
"tls-ca"
}
"proxy" => {
let raw = self.value("proxy", "<URI>", inline)?;
let proxy = raw.parse::<Proxy>()?;
if self.network.proxy.is_some() {
return Err(CliError::Repeated {
spelling: "--proxy <URI>",
});
}
self.network.proxy = Some(proxy);
"proxy"
}
"user-agent" => {
let raw = self.value("user-agent", "<VALUE>", inline)?;
let identity = ValidIdentity::parse_spec(&raw)?;
if self.user_agent.is_some() {
return Err(CliError::Repeated {
spelling: "--user-agent <VALUE>",
});
}
self.user_agent = Some(identity);
"user-agent"
}
_ => return Err(unexpected(name)),
};
self.record_flag(flag_name);
if self.first_daemon_run_flag.is_none() {
self.first_daemon_run_flag = Some(flag_name);
}
Ok(None)
}
fn short(&self, short: &str) -> Result<Option<Outcome>, CliError> {
match short {
"v" | "V" => Ok(Some(Outcome::Version)),
"h" => Ok(Some(Outcome::Help(self.path.spec()))),
_ => Err(CliError::UnexpectedArgument(format!("-{short}"))),
}
}
fn value(
&mut self,
flag: &'static str,
placeholder: &'static str,
inline: Option<&str>,
) -> Result<String, CliError> {
let missing = || CliError::MissingValue { flag, placeholder };
if let Some(raw) = inline {
if raw.is_empty() {
return Err(missing());
}
return Ok(raw.to_owned());
}
let Some(next) = self.args.peek() else {
return Err(missing());
};
let Some(text) = next.to_str() else {
return Err(CliError::NotUtf8);
};
if text.starts_with('-') {
return Err(missing());
}
match self.next_arg() {
Some(arg) => arg.into_string().map_err(|_| CliError::NotUtf8),
None => Err(missing()),
}
}
fn finish(mut self) -> Result<Outcome, CliError> {
if !self.saw_any {
return Ok(Outcome::Help(&ROOT_SPEC));
}
let mode = match self.path {
CommandPath::Root => return Err(CliError::MissingCommand),
CommandPath::Daemon(None) => {
if self.first_flag.is_some() {
return Err(CliError::MissingDaemonCommand);
}
return Ok(Outcome::Help(&DAEMON_SPEC));
}
CommandPath::Extension => {
if let Some(flag) = self.first_flag {
return Err(unexpected(flag));
}
Mode::Extension
}
CommandPath::Renderer => {
if let Some(flag) = self.first_daemon_run_flag {
return Err(unexpected(flag));
}
if self.profile.is_some() {
return Err(unexpected("profile"));
}
Mode::Renderer
}
CommandPath::Daemon(Some(action)) => match action {
DaemonAction::Stop | DaemonAction::Status => {
if let Some(flag) = self.first_daemon_run_flag {
return Err(unexpected(flag));
}
if self.log_level.is_some() {
return Err(unexpected("log-level"));
}
if self.log_file.is_some() {
return Err(unexpected("log-file"));
}
if self.verbose {
return Err(unexpected("verbose"));
}
if self.sandbox.is_some() {
return Err(unexpected("no-sandbox"));
}
let profile = self.profile.unwrap_or_default();
if action == DaemonAction::Stop {
Mode::Daemon(DaemonMode::Stop { profile })
} else {
Mode::Daemon(DaemonMode::Status { profile })
}
}
DaemonAction::Start | DaemonAction::Serve => {
if let Some(identity) = self.user_agent {
self.network.identity = identity;
}
for path in self.tls_ca {
self.network.tls_cas.push(read_ca(&path)?);
}
let config = Box::new(DaemonConfig {
port: self.port,
profile: self.profile.unwrap_or_default(),
network: self.network,
});
if action == DaemonAction::Start {
Mode::Daemon(DaemonMode::Start {
config,
command_index: self.action_index.unwrap_or(0),
})
} else {
Mode::Daemon(DaemonMode::Serve(config))
}
}
},
};
let sandbox = self.sandbox.unwrap_or(RendererSandbox::Enabled);
Ok(Outcome::Run(Box::new(Cli {
log_level: self.log_level,
log_file: self.log_file,
verbose: self.verbose,
sandbox,
mode,
})))
}
}
fn unexpected(name: &str) -> CliError {
CliError::UnexpectedArgument(format!("--{name}"))
}
fn read_ca(path: &std::path::Path) -> Result<TrustedCa, CliError> {
let pem = std::fs::read(path).map_err(|source| CliError::TlsCa {
path: path.to_owned(),
source: TlsCaError::Read(source),
})?;
TrustedCa::from_pem(&pem).map_err(|source| CliError::TlsCa {
path: path.to_owned(),
source: TlsCaError::Parse(source),
})
}