File: ch-run.c

package info (click to toggle)
charliecloud 0.43-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,116 kB
  • sloc: python: 6,021; sh: 4,284; ansic: 3,863; makefile: 598
file content (873 lines) | stat: -rw-r--r-- 27,429 bytes parent folder | download
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
/* Copyright © Triad National Security, LLC, and others. */

#define _GNU_SOURCE
#include "config.h"

#include <argp.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

#include "all.h"


/** Types **/

enum env_option_type {
   ENV_END = 0,  // list terminator sentinel
   ENV_SET,      // --set-env
   ENV_SET0,     // --set-env0
   ENV_UNSET,    // --unset-env
#ifdef HAVE_JSON
   ENV_CDI_DEV,  // --device (specific device)
   ENV_CDI_ALL,  // --devices (all known devices)
#endif
};

struct env_option {
   enum env_option_type opt;
   char *arg;
};

struct args {
   struct container c;
#ifdef HAVE_JSON
   struct cdi_config cdi;
#endif
   struct env_option *env_options;
   enum log_color_when log_color;
   enum log_test log_test;
   char *initial_dir;
#ifdef HAVE_SECCOMP
   bool seccomp_p;
#endif
   char *storage_dir;
   bool unsafe;
};

struct log_color_synonym {
   char *name;
   enum log_color_when color;
};


/** Function prototypes **/

bool getenv_first(char **array, char **name, char **value);
char **combine_cmd_args(const char *entrypoint_path, const char *cmd_path,
                        char **c_argv, int argv_len);
void hooks_env_install(struct args *args);
int join_ct(int cli_ct);
char *join_tag(char *cli_tag);
char **entrypoint_cmd_args_parse(const char *path);
void parse_env(struct env_option **opts, enum env_option_type opt, char *arg);
int parse_int(char *s, bool extra_ok, char *error_tag);
static error_t parse_opt(int key, char *arg, struct argp_state *state);
void privs_verify_invoking();
char *storage_default(void);
void write_fake_enable(struct args *args, char *overlay_size);


/** Constants and macros **/

/* Environment variables used by --join parameters. */
char *JOIN_CT_ENV[] =  { "OMPI_COMM_WORLD_LOCAL_SIZE",
                         "SLURM_STEP_TASKS_PER_NODE",
                         "SLURM_CPUS_ON_NODE",
                         NULL };
char *JOIN_TAG_ENV[] = { "SLURM_STEP_ID",
                         NULL };

/* Default overlaid tmpfs size. */
char *WRITE_FAKE_DEFAULT = "12%";

/* Log color WHEN synonyms. Note that no argument (i.e., bare --color) is
   handled separately. */
struct log_color_synonym log_color_synonyms[] = {
   { "auto",    LL_COLOR_AUTO },
   { "tty",     LL_COLOR_AUTO },
   { "if-tty",  LL_COLOR_AUTO },
   { "yes",     LL_COLOR_YES },
   { "always",  LL_COLOR_YES },
   { "force",   LL_COLOR_YES },
   { "no",      LL_COLOR_NO },
   { "never",   LL_COLOR_NO },
   { "none",    LL_COLOR_NO },
   { NULL,      LL_COLOR_NULL } };


/** Command line options **/

const char usage[] = "\
\n\
Run a command in a Charliecloud container.\n\
\v\
Example:\n\
\n\
  $ ch-run /data/foo -- echo hello\n\
  hello\n\
\n\
You cannot use this program to actually change your UID.\n";

const char args_doc[] = "IMAGE -- COMMAND [ARG...]";

/* Note: Long option numbers, once issued, are permanent; i.e., if you remove
   one, don’t re-number the others. */
const struct argp_option options[] = {
   { "abort-fatal",   -21, 0,      0,
     "exit abnormally on error, maybe dumping core" },
   { "bind",          'b', "SRC[:DST]", 0,
     "mount SRC at guest DST (default: same as SRC)"},
   { "cd",            'c', "DIR",  0, "initial working directory in container"},
#ifdef HAVE_JSON
   { "cdi",           'd', "[KIND]", OPTION_ARG_OPTIONAL,
                      "inject CDI resource(s) KIND (repeatable)" },
   { "cdi-dirs",      -19, "DIRS", 0, "director(y|ies) containing CDI specs" },
#endif
   { "color",         -20, "WHEN", OPTION_ARG_OPTIONAL,
                           "specify when to use colored logging" },
   { "env-no-expand", -10, 0,      0, "don't expand $ in --set-env input"},
   { "feature",       -11, "FEAT", 0, "exit successfully if FEAT is enabled" },
   { "gid",           'g', "GID",  0, "run as GID within container" },
   { "home",          -12, 0,      0, "mount host $HOME at guest /home/$USER" },
   { "join",          'j', 0,      0, "use same container as peer ch-run" },
   { "join-pid",       -5, "PID",  0, "join a namespace using a PID" },
   { "join-ct",        -3, "N",    0, "number of join peers (implies --join)" },
   { "join-tag",       -4, "TAG",  0, "label for peer group (implies --join)" },
   { "test",          -17, "TEST", 0, "do test TEST" },
   { "mount",         'm', "DIR",  0, "SquashFS mount point"},
   { "no-passwd",      -9, 0,      0, "don't bind-mount /etc/{passwd,group}"},
   { "private-tmp",   't', 0,      0, "use container-private /tmp" },
   { "quiet",         'q', 0,      0, "print less output (can be repeated)"},
#ifdef HAVE_SECCOMP
   { "seccomp",       -14, 0,      0,
                           "fake success for some syscalls with seccomp(2)"},
#endif
   { "set-env",        -6, "ARG",  OPTION_ARG_OPTIONAL,
                           "set env. variables per ARG (newline-delimited)"},
   { "set-env0",      -15, "ARG",  OPTION_ARG_OPTIONAL,
                           "set env. variables per ARG (null-delimited)"},
   { "storage",       's', "DIR",  0, "set DIR as storage directory"},
   { "uid",           'u', "UID",  0, "run as UID within container" },
   { "unsafe",        -13, 0,      0, "do unsafe things (internal use only)" },
   { "unset-env",      -7, "GLOB", 0, "unset environment variable(s)" },
   { "verbose",       'v', 0,      0, "be more verbose (can be repeated)" },
   { "version",       'V', 0,      0, "print version and exit" },
   { "warnings",      -16, "NUM",  0, "log NUM warnings and exit" },
   { "write",         'w', 0,      0, "mount image read-write (avoid)"},
   { "write-fake",    'W', "SIZE", OPTION_ARG_OPTIONAL,
                           "overlay read-write tmpfs on top of image" },
   { 0 }
};

const struct argp argp = { options, parse_opt, args_doc, usage };


/** Global variables **/

extern char *warnings;


/** Main **/

int main(int argc, char *argv[])
{
   bool argp_help_fmt_set;
   struct args args;
   int arg_len;
   int arg_next;
   char ** c_argv;
   char ** c_argv_cmd;
   char *cmd_path = NULL;
   char *entrypoint_path = NULL;

   // early init
   privs_verify_invoking();
   mem_init();
   username_set();
   warnings = mmap(NULL, WARNINGS_SIZE, PROT_READ | PROT_WRITE,
                   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
   T__ (warnings != MAP_FAILED);

   // note: exit functions not called on fatal error if --abort-on-fatal
   Z_e (atexit(mem_exit));
   Z_e (atexit(warnings_reprint));

#ifdef ENABLE_SYSLOG
   syslog(SYSLOG_PRI, "uid=%u args=%d: %s",
          getuid(), argc, argv_to_string(argv));
#endif

   verbose = LL_INFO;  // in ch_misc.c
   args = (struct args){
      .c = (struct container){
         .binds = list_new(0, sizeof(struct bind)),
         .container_gid = getegid(),
         .container_uid = geteuid(),
         .env_expand = true,
         .environ = list_copy(environ, sizeof(environ[0])),
         .hooks_all = list_new(0, sizeof(struct hook)),
         .hooks_guest = list_new(0, sizeof(struct hook)),
         .hooks_host = list_new(0, sizeof(struct hook)),
         .host_home = NULL,
         .img_ref = NULL,
         .initial_dir = NULL,
         .newroot = NULL,
         .join = false,
         .join_ct = 0,
         .join_pid = 0,
         .join_tag = NULL,
         .overlay_size = NULL,
         .private_passwd = false,
         .private_tmp = false,
         .type = IMG_NONE,
         .writable = false
      },
#ifdef HAVE_JSON
      .cdi = (struct cdi_config){
         .spec_dirs = cdi_spec_dirs_default(),
         .res_all_p = false,
         .ids = list_new(0, sizeof(char *)),
      },
#endif
      .env_options = list_new(0, sizeof(struct env_option)),
      .log_color = LL_COLOR_AUTO,
      .log_test = LL_TEST_NONE,
      .storage_dir = storage_default(),
      .unsafe = false
   };

   /* I couldn’t find a way to set argp help defaults other than this
      environment variable. Kludge sets/unsets only if not already set. */
   if (getenv("ARGP_HELP_FMT"))
      argp_help_fmt_set = true;
   else {
      argp_help_fmt_set = false;
      setenv("ARGP_HELP_FMT", "opt-doc-col=27,no-dup-args-note", false);
   }
   Z__ (argp_parse(&argp, argc, argv, 0, &arg_next, &args));
   if (!argp_help_fmt_set)
      unsetenv("ARGP_HELP_FMT");

   logging_init(args.log_color, args.log_test);
   mem_log("init");
#ifdef HAVE_JSON
   json_init();
#endif

   if (arg_next >= argc - 1) {
      fprintf(stderr, "usage: ch-run [OPTION...] IMAGE -- COMMAND [ARG...]\n");
      FATAL(-1, "IMAGE and/or COMMAND not specified");
   }
   args.c.img_ref = argv[arg_next++];
   T__ (args.c.img_ref != NULL);
   args.c.newroot = realpath_ch(args.c.newroot);
   args.storage_dir = realpath_ch(args.storage_dir);
   args.c.type = image_type(args.c.img_ref, args.storage_dir);

   switch (args.c.type) {
   case IMG_DIRECTORY:
      if (args.c.newroot != NULL)  // --mount was set
         WARNING("--mount invalid with directory image, ignoring");
      args.c.newroot = realpath_ch(args.c.img_ref);
      Tfe (path_exists(args.c.newroot, NULL, true),
           "image not found: %s", args.c.newroot);
      Tfe (args.unsafe || !path_subdir_p(args.storage_dir, args.c.newroot),
           "can't run directory images from storage (hint: run by name)");
      break;
   case IMG_NAME:
      args.c.newroot = img_name2path(args.c.img_ref, args.storage_dir);
      Tfe (args.unsafe || !args.c.writable,
           "--write invalid when running by name");
      break;
   case IMG_SQUASH:
#ifndef HAVE_SQUASHFUSE
      FATAL(-1, "this ch-run was not built with SquashFUSE support");
#endif
      break;
   case IMG_NONE:
      FATAL(-1, "unknown image type: %s", args.c.img_ref);
      break;
   }

   if (args.c.join) {
      args.c.join_ct = join_ct(args.c.join_ct);
      args.c.join_tag = join_tag(args.c.join_tag);
   }

   c_argv = list_new(argc - arg_next, sizeof(char *));
   for (int i = 0; i < argc - arg_next; i++)
      c_argv[i] = argv[i + arg_next];

   // Substitute args `ch-run img -- - [args, ...]`
   arg_len = argc - arg_next;
   c_argv_cmd = c_argv;
   if (arg_len >= 1 && streq(c_argv[0], "-")){
      arg_len --;
      c_argv_cmd ++;
   }

   if (args.c.newroot != NULL) {
      entrypoint_path = path_join(args.c.newroot, "ch/entrypoint");
      cmd_path = path_join(args.c.newroot, "ch/cmd");
      c_argv = combine_cmd_args(
         entrypoint_path,
         cmd_path,
         c_argv_cmd,
         arg_len);
   }

   host_tmp = getenv_df("TMPDIR", "/tmp");  // global in misc.c

   VERBOSE("verbosity: %d", verbose);
   VERBOSE("image: %s", args.c.img_ref);
   VERBOSE("storage: %s", args.storage_dir);
   VERBOSE("newroot: %s", args.c.newroot);
   VERBOSE("container uid: %u", args.c.container_uid);
   VERBOSE("container gid: %u", args.c.container_gid);
   VERBOSE("join: %d %d %s %d", args.c.join, args.c.join_ct, args.c.join_tag,
           args.c.join_pid);
   VERBOSE("host $TMPDIR: %s", host_tmp);
   VERBOSE("private /tmp: %d", args.c.private_tmp);
#ifdef HAVE_SECCOMP
   VERBOSE("seccomp: %s", bool_to_string(args.seccomp_p));
#endif
   VERBOSE("unsafe: %s", bool_to_string(args.unsafe));

#ifdef HAVE_JSON
   cdi_init(&args.cdi);
   cdi_hooks_install(&args.c);
#endif

   hooks_env_install(&args);
   containerize(&args.c);
   run_user_command(&args.c, c_argv);  // doesn’t return, even on error
}

/** Supporting functions **/

/* Read and combine ENTRYPOINT, CMD, and user arguments into a single command.
   At least one ENTRYPOINT, CMD, or user argument must be provided.
   ENTRYPOINT is always used if specified, CMD provides default arguments which
   can be overridden if user arguments are provided.
*/
char **combine_cmd_args(const char *entrypoint_path, const char *cmd_path,
                        char **c_argv, int argv_len)
{
   char **entrypoint = NULL;
   char **cmd = NULL;
   int entrypoint_len = 0;
   int cmd_len = 0;
   char **combined_argv = NULL;
   int total_args_len = 0;

   entrypoint = entrypoint_cmd_args_parse(entrypoint_path);
   cmd = entrypoint_cmd_args_parse(cmd_path);

   entrypoint_len = list_count(entrypoint, sizeof(char*));
   cmd_len = list_count(cmd, sizeof(char*));

   // combine entrypoint and cmd
   if (argv_len > 0){
      cmd_len = 0;
   }

   total_args_len = entrypoint_len + cmd_len + argv_len;
   Tfe(total_args_len > 0, "No CMD, ENTRYPOINT, or command specified \
      (total_args_len=%d)", total_args_len);

   // copy entrypoint arguments
   list_cat((void**)&combined_argv, entrypoint, sizeof(char*));
   if (argv_len == 0){
      // copy command arguments if argc args don't exist
      list_cat((void**)&combined_argv, cmd, sizeof(char*));
   }
   else{
      // override cmd with argc arguments
      list_cat((void**)&combined_argv, c_argv, sizeof(char*));
   }

   return combined_argv;
}

/* Set the default environment variables that come before the user-specified
   environment changes. d must be NULL. */
void hook_envs_def_first(struct container *c, void *d)
{
   char *vold;
   T__ (d == NULL);

   // $HOME: If --home, set to “/home/$USER”.
   if (c->host_home)
      cenv_set(c, "HOME", path_join("/home", username));
   else if (path_exists("/root", NULL, true))
      cenv_set(c, "HOME", "/root");
   else
      cenv_set(c, "HOME", "/");

   // $PATH: Append /bin if not already present.
   vold = cenv_get(c, "PATH");
   if (vold == NULL)
      WARNING("$PATH not set");
   else if (strstr(vold, "/bin") != vold && !strstr(vold, ":/bin"))
      cenv_set(c, "PATH", cat(vold, ":/bin"));

   // Unset.
   cenv_unset(c, "TMPDIR");
   cenv_unset(c, "GC_MARKERS");
}

/* Set the default environment variables that come after the user-specified
   changes. d must be NULL. */
void hook_envs_def_last(struct container *c, void *d)
{
   T__ (d == NULL);
   cenv_set(c, "CH_RUNNING", "Weird Al Yankovic");
}

/* Install hooks for environment variable changes. */
void hooks_env_install(struct args *args)
{
   hook_add(&args->c.hooks_all, HOOK_DUP_FAIL,
            "env-def-first", hook_envs_def_first, NULL);

   for (int i = 0; args->env_options[i].opt != ENV_END; i++) {
      char *name = NULL;
      hookf_t *f = NULL;
      void *d = NULL;
      enum env_option_type opt = args->env_options[i].opt;
      char *arg = args->env_options[i].arg;

      switch (opt) {
      case ENV_SET:
      case ENV_SET0: {
           int delim = (opt == ENV_SET) ? '\n' : '\0';
            if (arg == NULL) {                 // guest path; defer file read
               struct env_file *ef;
               name = "env-set-gfile";
               f = envs_hook_set_file;
               ef = malloc_ch(sizeof(struct env_file), true);
               ef->path = "/ch/environment";
               ef->delim = delim;
               ef->expand = args->c.env_expand;
               d = ef;
            } else {
               f = envs_hook_set;
               if (strchr(arg, '=') == NULL) {  // host path; read file now
                  name = "env-set-hfile";
                  d = env_file_read(arg, delim);
               } else {                         // direct set
                  name = "env-set-direct";
                  d = list_new(1, sizeof(struct env_var));
                  ((struct env_var *)d)[0] = env_parse(arg, NULL, 0);
               }
            }
            break;
         }
      case ENV_UNSET:
         name = "env-unset";
         f = envs_hook_unset;
         d = arg;
         break;
#ifdef HAVE_JSON
      case ENV_CDI_DEV:
         name = "env-set-cdi";
         f = envs_hook_set;
         d = cdi_envs_get(arg);
         break;
      case ENV_CDI_ALL:
         name = "env-set-cdi-all";
         f = envs_hook_set;
         d = cdi_envs_get(NULL);
         break;
#endif
      case ENV_END:
         T__ (false);  // unreachable
         break;
      }
      hook_add(&args->c.hooks_all, HOOK_DUP_OK, name, f, d);
   }

   hook_add(&args->c.hooks_all, HOOK_DUP_FAIL,
            "env-def-last", hook_envs_def_last, NULL);
}

/* Find an appropriate join count; assumes --join was specified or implied.
   Exit with error if no valid value is available. */
int join_ct(int cli_ct)
{
   int j = 0;
   char *ev_name, *ev_value;

   if (cli_ct != 0) {
      VERBOSE("join: peer group size from command line");
      j = cli_ct;
      goto end;
   }

   if (getenv_first(JOIN_CT_ENV, &ev_name, &ev_value)) {
      VERBOSE("join: peer group size from %s", ev_name);
      j = parse_int(ev_value, true, ev_name);
      goto end;
   }

end:
   Tfe (j > 0, "join: no valid peer group size found");
   return j;
}

/* Find an appropriate join tag; assumes --join was specified or implied. Exit
   with error if no valid value is found. */
char *join_tag(char *cli_tag)
{
   char *tag;
   char *ev_name, *ev_value;

   if (cli_tag != NULL) {
      VERBOSE("join: peer group tag from command line");
      tag = cli_tag;
      goto end;
   }

   if (getenv_first(JOIN_TAG_ENV, &ev_name, &ev_value)) {
      VERBOSE("join: peer group tag from %s", ev_name);
      tag = ev_value;
      goto end;
   }

   VERBOSE("join: peer group tag from getppid(2)");
   tag = asprintf_ch("%d", getppid());

end:
   Tfe (tag[0] != '\0', "join: peer group tag cannot be empty string");
   return tag;
}

// Parse entrypoint/cmd arguments
char **entrypoint_cmd_args_parse(const char* path) {
   FILE *fp;

   if (path == NULL)
      return NULL;

   fp = fopen(path, "rb");
   if (fp == NULL) {
      return NULL;
   }

   char **args = NULL;
   char *token = NULL;

   while ((token = getdelim_ch(fp, '\0'))) {
      list_append((void**)&args, &token, sizeof(char*));
   }
   fclose(fp);
   return args;
}

/* Parse an integer string arg and return the result. If an error occurs,
   print a message prefixed by error_tag and exit. If not extra_ok, additional
   characters remaining after the integer are an error. */
int parse_int(char *s, bool extra_ok, char *error_tag)
{
   char *end;
   long l;

   errno = 0;
   l = strtol(s, &end, 10);
   Tfe (end != s, "%s: no digits found", error_tag);
   Tfe (errno != ERANGE && l >= INT_MIN && l <= INT_MAX,
        "%s: out of range", error_tag);
   Tfe (errno == 0, "%s", error_tag);
   Tfe (extra_ok || *end == 0, "%s: extra characters after digits", error_tag);
   return (int)l;
}

/* Parse one command line option. Called by argp_parse(). */
static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
   struct args *args = state->input;
   int i;

   switch (key) {
   case -3: // --join-ct
      args->c.join = true;
      args->c.join_ct = parse_int(arg, false, "--join-ct");
      break;
   case -4: // --join-tag
      args->c.join = true;
      args->c.join_tag = arg;
      break;
   case -5: // --join-pid
      args->c.join_pid = parse_int(arg, false, "--join-pid");
      break;
   case -6: // --set-env
      parse_env(&args->env_options, ENV_SET, arg);
      break;
   case -7: // --unset-env
      parse_env(&args->env_options, ENV_UNSET, arg);
      break;
   case -9: // --no-passwd
      args->c.private_passwd = true;
      break;
   case -10: // --env-no-expand
      args->c.env_expand = false;
      break;
   case -11: // --feature
      // FIXME: This conditional tree is getting really ugly but the
      // interaction between preprocessor symbols that we don’t really control
      // (they’re from config.h) and C code is beyond my skills today.
      if (streq(arg, "extglob")) {
#ifdef HAVE_FNM_EXTMATCH
         exit(0);
#else
         exit(EXIT_ERR_MISC);
#endif
      } else if (streq(arg, "json")) {
#ifdef HAVE_JSON
         exit(0);
#else
         exit(EXIT_ERR_MISC);
#endif
      } else if (streq(arg, "overlayfs")) {
#ifdef HAVE_OVERLAYFS
         exit(0);
#else
         exit(EXIT_ERR_MISC);
#endif
      } else if (streq(arg, "seccomp")) {
#ifdef HAVE_SECCOMP
         exit(0);
#else
         exit(EXIT_ERR_MISC);
#endif
      } else if (streq(arg, "squash")) {
#ifdef HAVE_SQUASHFUSE
         exit(0);
#else
         exit(EXIT_ERR_MISC);
#endif
      } else if (streq(arg, "tmpfs-xattrs")) {
#ifdef HAVE_TMPFS_XATTRS
         exit(0);
#else
         exit(EXIT_ERR_MISC);
#endif
      }
      else
         FATAL(-1, "unknown feature: %s", arg);
      break;
   case -12: // --home
      Tf_ (args->c.host_home = getenv("HOME"), "--home: $HOME not set");
      if (args->c.overlay_size == NULL) {
         VERBOSE("--home specified; also setting --write-fake");
         args->c.overlay_size = WRITE_FAKE_DEFAULT;
      }
      break;
   case -13: // --unsafe
      args->unsafe = true;
      break;
#ifdef HAVE_SECCOMP
   case -14: // --seccomp
      hook_add(&args->c.hooks_guest, HOOK_DUP_SKIP,
               "seccomp", hook_seccomp, NULL);
      break;
#endif
   case -15: // --set-env0
      parse_env(&args->env_options, ENV_SET0, arg);
      break;
   case -16: // --warnings
      for (int i = 1; i <= parse_int(arg, false, "--warnings"); i++)
         WARNING("this is warning %d!", i);
      exit(0);
      break;
   case -17: // --test
      if (streq(arg, "log"))
         args->log_test = LL_TEST_YES;
      else if (streq(arg, "log-fail"))
         args->log_test = LL_TEST_FATAL;
      else
         FATAL(-1, "invalid --test argument: %s; see source code", arg);
      break;
#ifdef HAVE_JSON
   case -19: // --cdi-dirs
      Tf_ (strlen(arg) > 0, "--cdi-dirs: PATHS must be non-empty");
      args->cdi.spec_dirs = list_new_strings(':', arg);
      break;
#endif
   case -20: // --color
      if (arg == NULL)
         args->log_color = LL_COLOR_AUTO;
      args->log_color = LL_COLOR_NULL;
      for (int i = 0; true; i++) {
         if (log_color_synonyms[i].name == NULL)
            break;
         if (streq(arg, log_color_synonyms[i].name)) {
            args->log_color = log_color_synonyms[i].color;
            break;
         }
      }
      Tf_ (args->log_color != LL_COLOR_NULL, "--color: invalid arg: %s", arg);
      break;
   case -21: // --abort-fatal
      abort_fatal = true;  // in misc.c
      break;
   case 'b': {  // --bind
        char *src, *dst;
        i = list_count(args->c.binds, sizeof(args->c.binds[0]));
        args->c.binds = realloc_ch(args->c.binds, (i+2) * sizeof(struct bind),
                                   true);
        memset(&args->c.binds[i+1], 0, sizeof(args->c.binds[0]));  // terminate
        args->c.binds[i].flags = BD_DST_CREATE;
        // source
        src = strsep(&arg, ":");
        T__ (src != NULL);
        Tf_ (src[0] != 0, "--bind: no source provided");
        args->c.binds[i].src = src;
        // destination
        dst = arg ? arg : src;
        Tf_ (dst[0] != 0, "--bind: no destination provided");
        Tf_ (!streq(dst, "/"), "--bind: destination can't be /");
        Tf_ (dst[0] == '/', "--bind: destination must be absolute");
        args->c.binds[i].dst = dst;
      }
      break;
   case 'c':  // --cd
      args->c.initial_dir = arg;
      break;
#ifdef HAVE_JSON
   case 'd': {  // --cdi
         // We do not yet know the spec directories yet and therefore may not
         // have all the spec files yet.
         struct env_option ope;
         write_fake_enable(args, NULL);
         if (arg) {  // specified resource(s)
            arg = cdi_resid_canonicalize(arg);
            list_append((void **)&args->cdi.ids, &arg, sizeof(arg));
            ope.opt = ENV_CDI_DEV;
            ope.arg = arg;
         } else {    // all resources
            args->cdi.res_all_p = true;
            ope.opt = ENV_CDI_ALL;
            ope.arg = NULL;
         }
         list_append((void **)&args->env_options, &ope, sizeof(ope));
      }
      break;
#endif
   case 'g':  // --gid
      i = parse_int(arg, false, "--gid");
      Tf_ (i >= 0, "--gid: must be non-negative");
      args->c.container_gid = (gid_t) i;
      break;
   case 'j':  // --join
      args->c.join = true;
      break;
   case 'm':  // --mount
      Tf_ (arg[0] != '\0', "mount point can't be empty string");
      args->c.newroot = arg;
      break;
   case 's':  // --storage
      args->storage_dir = arg;
      if (!path_exists(arg, NULL, false))
         WARNING("storage directory not found: %s", arg);
      break;
   case 'q':  // --quiet
      Tf_ (verbose <= 0, "--quiet incompatible with --verbose");
      verbose--;
      Tf_ (verbose >= -3, "--quiet can be specified at most thrice");
      break;
   case 't':  // --private-tmp
      args->c.private_tmp = true;
      break;
   case 'u':  // --uid
      i = parse_int(arg, false, "--uid");
      Tf_ (i >= 0, "--uid: must be non-negative");
      args->c.container_uid = (uid_t) i;
      break;
   case 'V':  // --version
      version();
      exit(EXIT_SUCCESS);
      break;
   case 'v':  // --verbose
      Tf_ (verbose >= 0, "--verbose incompatible with --quiet");
      verbose++;
      Tf_ (verbose <= 3, "--verbose can be specified at most thrice");
      break;
   case 'w':  // --write
      args->c.writable = true;
      break;
   case 'W':  // --write-fake
      write_fake_enable(args, arg);
      break;
   case ARGP_KEY_NO_ARGS:
      argp_state_help(state, stderr, (  ARGP_HELP_SHORT_USAGE
                                      | ARGP_HELP_PRE_DOC
                                      | ARGP_HELP_LONG
                                      | ARGP_HELP_POST_DOC));
      exit(EXIT_FAILURE);
   default:
      return ARGP_ERR_UNKNOWN;
   }

   return 0;
}

void parse_env(struct env_option **opts, enum env_option_type opt, char *arg)
{
   struct env_option eo = (struct env_option){ .opt = opt,
                                               .arg = arg };
   Tf_ (arg == NULL || strlen(arg) > 0,
        "environment options: argument must have non-zero length");
   list_append((void **)opts, &eo, sizeof(eo));
}

/* Validate that the UIDs and GIDs are appropriate for program start, and
   abort if not.

   Note: If the binary is setuid, then the real UID will be the invoking user
   and the effective and saved UIDs will be the owner of the binary.
   Otherwise, all three IDs are that of the invoking user. */
void privs_verify_invoking()
{
   uid_t ruid, euid, suid;
   gid_t rgid, egid, sgid;

   Z_e (getresuid(&ruid, &euid, &suid));
   Z_e (getresgid(&rgid, &egid, &sgid));

   // Calling the program if user is really root is OK.
   if (   ruid == 0 && euid == 0 && suid == 0
       && rgid == 0 && egid == 0 && sgid == 0)
      return;

   // Now that we know user isn't root, no GID privilege is allowed.
   T__ (egid != 0);                           // no privilege
   T__ (egid == rgid && egid == sgid);        // no setuid or funny business

   // No UID privilege allowed either.
   T__ (euid != 0);                           // no privilege
   T__ (euid == ruid && euid == suid);        // no setuid or funny business
}

/* Return default path to the storage directory. */
char *storage_default(void)
{
   return getenv_df("CH_IMAGE_STORAGE",
                    asprintf_ch("/var/tmp/%s.ch", username));
}

/* Enable the overlay if not already enabled. */
void write_fake_enable(struct args *args, char *overlay_size)
{
   if (overlay_size != NULL) {
      // new overlay size specified: use it regardless of previous enablement
      args->c.overlay_size = overlay_size;
   } else if (args->c.overlay_size == NULL) {
      // no new size, not yet enabled: enable with default size
      args->c.overlay_size = WRITE_FAKE_DEFAULT;
   } else {
      // no new size, already enabled: keep existing size, nothing to do
      T__ (args->c.overlay_size != NULL);
   }
}