summaryrefslogtreecommitdiffstats
path: root/g13/g13.c
blob: 6b4d05a7fb90fbf1abe2aa2d3952421bd98c3521 (plain)
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
/* g13.c - Disk Key management with GnuPG
 * Copyright (C) 2009 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <pth.h>

#include "g13.h"

#include <gcrypt.h>
#include <assuan.h>

#include "i18n.h"
#include "sysutils.h"
#include "gc-opt-flags.h"
#include "keyblob.h"
#include "./runner.h"
#include "./create.h"
#include "./mount.h"


enum cmd_and_opt_values {
  aNull = 0,
  oQuiet	= 'q',
  oVerbose	= 'v',

  aGPGConfList  = 500,
  aGPGConfTest,
  aCreate,
  aMount,
  aUmount,

  oOptions,
  oDebug,
  oDebugLevel,
  oDebugAll,
  oDebugNone,
  oDebugWait,
  oDebugAllowCoreDump,
  oLogFile,
  oNoLogFile,
  oAuditLog,

  oOutput,

  oAgentProgram,
  oGpgProgram,

  oDisplay,
  oTTYname,
  oTTYtype,
  oLCctype,
  oLCmessages,
  oXauthority,

  oStatusFD,
  oLoggerFD,

  oNoVerbose,
  oNoSecmemWarn,
  oNoGreeting,
  oNoTTY,
  oNoOptions,
  oHomedir,
  oWithColons,
  oDryRun,
  oNoDetach,

  oRecipient,

  oNoRandomSeedFile,
  oFakedSystemTime
 };


static ARGPARSE_OPTS opts[] = {

  ARGPARSE_group (300, N_("@Commands:\n ")),

  ARGPARSE_c (aCreate, "create", N_("Create a new file system container")),
  ARGPARSE_c (aMount,  "mount",  N_("Mount a file system container") ),
  ARGPARSE_c (aUmount, "umount", N_("Unmount a file system container") ),

  ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
  ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),

  ARGPARSE_group (301, N_("@\nOptions:\n ")),

  ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),

  ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
  ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
  ARGPARSE_s_n (oQuiet,	"quiet",  N_("be somewhat more quiet")),
  ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
  ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
  ARGPARSE_s_s (oLogFile, "log-file",  N_("|FILE|write log output to FILE")),
  ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
  ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),

  ARGPARSE_s_s (oAuditLog, "audit-log",
                N_("|FILE|write an audit log to FILE")),
  ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),

  ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),

  ARGPARSE_p_u (oDebug, "debug", "@"),
  ARGPARSE_s_s (oDebugLevel, "debug-level",
                N_("|LEVEL|set the debugging level to LEVEL")),
  ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
  ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
  ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
  ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),

  ARGPARSE_s_i (oStatusFD, "status-fd",
                N_("|FD|write status info to this FD")),

  ARGPARSE_group (302, N_(
  "@\n(See the man page for a complete listing of all commands and options)\n"
  )),

  ARGPARSE_group (303, N_("@\nExamples:\n\n"
    " blurb\n"
                          " blurb\n")),

  /* Hidden options. */
  ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
  ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"), 
  ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
  ARGPARSE_s_n (oNoOptions, "no-options", "@"),
  ARGPARSE_s_s (oHomedir, "homedir", "@"),   
  ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
  ARGPARSE_s_s (oGpgProgram, "gpg-program", "@"),
  ARGPARSE_s_s (oDisplay,    "display", "@"),
  ARGPARSE_s_s (oTTYname,    "ttyname", "@"),
  ARGPARSE_s_s (oTTYtype,    "ttytype", "@"),
  ARGPARSE_s_s (oLCctype,    "lc-ctype", "@"),
  ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
  ARGPARSE_s_s (oXauthority, "xauthority", "@"),
  ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
  ARGPARSE_s_n (oWithColons, "with-colons", "@"),
  ARGPARSE_s_n (oNoRandomSeedFile,  "no-random-seed-file", "@"),

  /* Command aliases.  */

  ARGPARSE_end ()
};


/* Global variable to keep an error count. */
int g13_errors_seen = 0;

/* It is possible that we are currently running under setuid permissions.  */
static int maybe_setuid = 1;

/* Helper to implement --debug-level and --debug.  */
static const char *debug_level;
static unsigned int debug_value;

static void set_cmd (enum cmd_and_opt_values *ret_cmd,
                     enum cmd_and_opt_values new_cmd );

static void emergency_cleanup (void);

/* Begin Pth wrapper functions. */
GCRY_THREAD_OPTION_PTH_IMPL;
static int fixed_gcry_pth_init (void)
{
  return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
}
/* End Pth wrapper functions. */


static const char *
my_strusage( int level )
{
  const char *p;

  switch (level)
    {
    case 11: p = "g13 (GnuPG)";
      break;
    case 13: p = VERSION; break;
    case 17: p = PRINTABLE_OS_NAME; break;
    case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
      break;
    case 1:
    case 40: p = _("Usage: g13 [options] [files] (-h for help)");
      break;
    case 41:
      p = _("Syntax: g13 [options] [files]\n"
            "Create, mount or unmount an encrypted file system container\n");
      break;

    case 31: p = "\nHome: "; break;
    case 32: p = opt.homedir; break;
     
    default: p = NULL; break;
    }
  return p;
}


static void
wrong_args (const char *text)
{
  fputs (_("usage: g13 [options] "), stderr);
  fputs (text, stderr);
  putc ('\n', stderr);
  g13_exit (2);
}


/* Setup the debugging.  With a DEBUG_LEVEL of NULL only the active
   debug flags are propagated to the subsystems.  With DEBUG_LEVEL
   set, a specific set of debug flags is set; and individual debugging
   flags will be added on top.  */
static void
set_debug (void)
{
  if (!debug_level)
    ;
  else if (!strcmp (debug_level, "none"))
    opt.debug = 0;
  else if (!strcmp (debug_level, "basic"))
    opt.debug = DBG_ASSUAN_VALUE|DBG_MOUNT_VALUE;
  else if (!strcmp (debug_level, "advanced"))
    opt.debug = DBG_ASSUAN_VALUE|DBG_MOUNT_VALUE;
  else if (!strcmp (debug_level, "expert"))
    opt.debug = (DBG_ASSUAN_VALUE|DBG_MOUNT_VALUE|DBG_CRYPTO_VALUE);
  else if (!strcmp (debug_level, "guru"))
    opt.debug = ~0;
  else
    {
      log_error (_("invalid debug-level `%s' given\n"), debug_level);
      g13_exit(2);
    }

  opt.debug |= debug_value;

  if (opt.debug && !opt.verbose)
    opt.verbose = 1;
  if (opt.debug)
    opt.quiet = 0;

  if (opt.debug & DBG_CRYPTO_VALUE )
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
  gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
}
 


static void
set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
{
  enum cmd_and_opt_values cmd = *ret_cmd;

  if (!cmd || cmd == new_cmd)
    cmd = new_cmd;
  else 
    {
      log_error (_("conflicting commands\n"));
      g13_exit (2);
    }

  *ret_cmd = cmd;
}


/* Helper to add recipients to a list. */
static int
add_encryption_key (ctrl_t ctrl, const char *name,
                    void /*FIXME*/ *keylist, int is_cms)
{
  /* FIXME: Decide whether to add a CMS or OpenPGP key and then add
     the key to a list.  */
  /* int rc = foo_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to); */
  /* if (rc) */
  /*   { */
  /*     if (recp_required) */
  /*       { */
  /*         log_error ("can't encrypt to `%s': %s\n", name, gpg_strerror (rc)); */
  /*         gpgsm_status2 (ctrl, STATUS_INV_RECP, */
  /*                        get_inv_recpsgnr_code (rc), name, NULL); */
  /*       } */
  /*     else */
  /*       log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"), */
  /*                 name, gpg_strerror (rc)); */
  /*   } */
  return 0; /* Key is good.  */
}


int
main ( int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  int orig_argc;
  char **orig_argv;
  gpg_error_t err;
  const char *fname;
  int may_coredump;
  FILE *configfp = NULL;
  char *configname = NULL;
  unsigned configlineno;
  int parse_debug = 0;
  int no_more_options = 0;
  int default_config =1;
  char *logfile = NULL;
  char *auditlog = NULL;
  int greeting = 0;
  int nogreeting = 0;
  int debug_wait = 0;
  int use_random_seed = 1;
  int nodetach = 0;
  int nokeysetup = 0;
  enum cmd_and_opt_values cmd = 0;
  struct server_control_s ctrl;
  estream_t auditfp = NULL;
  strlist_t recipients = NULL;

  /*mtrace();*/

  gnupg_reopen_std ("g13");
  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);

  log_set_prefix ("g13", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems ();

  /* Libgcrypt requires us to register the threading model first.
     Note that this will also do the pth_init. */
  gcry_threads_pth.init = fixed_gcry_pth_init;
  err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
  if (err)
    {
      log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
                 gpg_strerror (err));
    }

  /* Check that the Libgcrypt is suitable.  */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt", 
               NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );

  /* Take extra care of the random pool.  */
  gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);

  may_coredump = disable_core_dumps ();
  
  gnupg_init_signals (0, emergency_cleanup);
  
  create_dotlock (NULL); /* Register locking cleanup.  */

  opt.homedir = default_homedir ();

  /* First check whether we have a config file on the commandline.  */
  orig_argc = argc;
  orig_argv = argv;
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags= 1|(1<<6);  /* Do not remove the args, ignore version.  */
  while (arg_parse( &pargs, opts))
    {
      if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
        parse_debug++;
      else if (pargs.r_opt == oOptions)
        { /* Yes, there is one, so we do not try the default one but
             read the config file when it is encountered at the
             commandline.  */
          default_config = 0;
	}
      else if (pargs.r_opt == oNoOptions)
        default_config = 0; /* --no-options */
      else if (pargs.r_opt == oHomedir)
        opt.homedir = pargs.r.ret_str;
    }

  /* Initialize the secure memory. */
  gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
  maybe_setuid = 0;

  /* 
     Now we are now working under our real uid 
  */

  /* Setup malloc hooks. */
  {
    struct assuan_malloc_hooks malloc_hooks;

    malloc_hooks.malloc = gcry_malloc;
    malloc_hooks.realloc = gcry_realloc;
    malloc_hooks.free = gcry_free;
    assuan_set_malloc_hooks (&malloc_hooks);
  }
  
  /* Prepare libassuan.  */
  assuan_set_assuan_log_prefix (log_get_prefix (NULL));
  assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);


  /* Setup a default control structure for command line mode.  */
  memset (&ctrl, 0, sizeof ctrl);
  g13_init_default_ctrl (&ctrl);

  /* Set the default option file */
  if (default_config )
    configname = make_filename (opt.homedir, "g13.conf", NULL);
  
  argc        = orig_argc;
  argv        = orig_argv;
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags =  1;  /* Do not remove the args.  */

 next_pass:
  if (configname)
    {
      configlineno = 0;
      configfp = fopen (configname, "r");
      if (!configfp)
        {
          if (default_config)
            {
              if (parse_debug)
                log_info (_("NOTE: no default option file `%s'\n"), configname);
            }
          else 
            {
              log_error (_("option file `%s': %s\n"), 
                         configname, strerror(errno));
              g13_exit(2);
            }
          xfree (configname);
          configname = NULL;
        }
      if (parse_debug && configname)
        log_info (_("reading options from `%s'\n"), configname);
      default_config = 0;
    }
  
  while (!no_more_options 
         && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
	case aGPGConfList: 
	case aGPGConfTest: 
          set_cmd (&cmd, pargs.r_opt);
          nogreeting = 1;
          nokeysetup = 1;
          break;

        case aMount:
        case aUmount:
          nokeysetup = 1;
        case aCreate:
          set_cmd (&cmd, pargs.r_opt);
          break;

        case oOutput: opt.outfile = pargs.r.ret_str; break;

        case oQuiet: opt.quiet = 1; break;
        case oNoGreeting: nogreeting = 1; break;
        case oNoTTY:  break;

        case oDryRun: opt.dry_run = 1; break;

        case oVerbose:
          opt.verbose++;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;
        case oNoVerbose:
          opt.verbose = 0;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;

        case oLogFile: logfile = pargs.r.ret_str; break;
        case oNoLogFile: logfile = NULL; break;          

        case oAuditLog: auditlog = pargs.r.ret_str; break;

        case oNoDetach: nodetach = 1; break;

        case oDebug: debug_value |= pargs.r.ret_ulong; break;
        case oDebugAll: debug_value = ~0; break;
        case oDebugNone: debug_value = 0; break;
        case oDebugLevel: debug_level = pargs.r.ret_str; break;
        case oDebugWait: debug_wait = pargs.r.ret_int; break;
        case oDebugAllowCoreDump:
          may_coredump = enable_core_dumps ();
          break;

        case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
        case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;

        case oNoOptions: break; /* no-options */
        case oOptions:
          /* Config files may not be nested (silently ignore them).  */
          if (!configfp)
            {
              xfree(configname);
              configname = xstrdup (pargs.r.ret_str);
              goto next_pass;
	    }
          break;

        case oHomedir: opt.homedir = pargs.r.ret_str; break;

        case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
        case oGpgProgram: opt.gpg_program = pargs.r.ret_str;  break;
        case oDisplay: opt.display = xstrdup (pargs.r.ret_str); break;
        case oTTYname: opt.ttyname = xstrdup (pargs.r.ret_str); break;
        case oTTYtype: opt.ttytype = xstrdup (pargs.r.ret_str); break;
        case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
        case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
        case oXauthority: opt.xauthority = xstrdup (pargs.r.ret_str); break;
          
        case oFakedSystemTime:
          {
            time_t faked_time = isotime2epoch (pargs.r.ret_str); 
            if (faked_time == (time_t)(-1))
              faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
            gnupg_set_time (faked_time, 0);
          }
          break;

        case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break;

        case oNoRandomSeedFile: use_random_seed = 0; break;

        case oRecipient: /* Store the encryption key.  */
          add_to_strlist (&recipients, pargs.r.ret_str);
          break;


        default: 
          pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR; 
          break;
	}
    }

  if (configfp)
    {
      fclose (configfp);
      configfp = NULL;
      /* Keep a copy of the config filename. */
      opt.config_filename = configname;
      configname = NULL;
      goto next_pass;
    }
  xfree (configname);
  configname = NULL;

  if (!opt.config_filename)
    opt.config_filename = make_filename (opt.homedir, "g13.conf", NULL);

  if (log_get_errorcount(0))
    g13_exit(2);

  /* Now that we have the options parsed we need to update the default
     control structure.  */
  g13_init_default_ctrl (&ctrl);

  if (nogreeting)
    greeting = 0;
  
  if (greeting)
    {
      fprintf(stderr, "%s %s; %s\n",
              strusage(11), strusage(13), strusage(14) );
      fprintf(stderr, "%s\n", strusage(15) );
    }

  if (may_coredump && !opt.quiet)
    log_info (_("WARNING: program may create a core file!\n"));

  if (logfile)
    {
      log_set_file (logfile);
      log_set_prefix (NULL, 1|2|4);
    }

  if (gnupg_faked_time_p ())
    {
      gnupg_isotime_t tbuf;

      log_info (_("WARNING: running with faked system time: "));
      gnupg_get_isotime (tbuf);
      dump_isotime (tbuf);
      log_printf ("\n");
    }

  /* Print any pending secure memory warnings.  */
  gcry_control (GCRYCTL_RESUME_SECMEM_WARN);

  /* Setup the debug flags for all subsystems.  */
  set_debug ();

  /* Install a regular exit handler to make real sure that the secure
     memory gets wiped out.  */
  if (atexit (emergency_cleanup))
    {
      log_error ("atexit failed\n");
      g13_exit (2);
    }

  /* Terminate if we found any error until now.  */
  if (log_get_errorcount(0))
    g13_exit (2);
  
  /* Set the standard GnuPG random seed file.  */
  if (use_random_seed) 
    {
      char *p = make_filename (opt.homedir, "random_seed", NULL);
      gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
      xfree(p);
    }
  
  /* Store given filename into FNAME. */
  fname = argc? *argv : NULL;

  /* Parse all given encryption keys.  This does a lookup of the keys
     and stops if any of the given keys was not found. */
  if (!nokeysetup)
    {
      strlist_t sl;
      int failed = 0;
      
      for (sl = recipients; sl; sl = sl->next)
        if (add_encryption_key (&ctrl, sl->d, NULL /* FIXME*/, 0))
          failed = 1;
      if (failed)
        g13_exit (1);
    }
  
  /* Dispatch command.  */
  switch (cmd)
    {
    case aGPGConfList: 
      { /* List options and default values in the GPG Conf format.  */
	char *config_filename_esc = percent_escape (opt.config_filename, NULL);

        printf ("gpgconf-g13.conf:%lu:\"%s\n",
                GC_OPT_FLAG_DEFAULT, config_filename_esc);
        xfree (config_filename_esc);

        printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
	printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
	printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
	printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
      }
      break;
    case aGPGConfTest:
      /* This is merely a dummy command to test whether the
         configuration file is valid.  */
      break;

    case aCreate: /* Create a new container. */
      {
        if (argc != 1) 
          wrong_args ("--create filename");
        err = g13_create_container (&ctrl, argv[0]);
        if (err)
          log_error ("error creating a new container: %s <%s>\n",
                     gpg_strerror (err), gpg_strsource (err));
        else
          {
            unsigned int n;

            while ((n = runner_get_threads ()))
              {
                log_info ("number of running threads: %u\n", n);
                pth_sleep (5);
              }
          }
      }
      break;

    case aMount: /* Mount a container. */
      {
        if (argc != 1 && argc != 2 ) 
          wrong_args ("--mount filename [mountpoint]");
        err = g13_mount_container (&ctrl, argv[0], argc == 2?argv[1]:NULL);
        if (err)
          log_error ("error mounting container `%s': %s <%s>\n",
                     *argv, gpg_strerror (err), gpg_strsource (err));
        else
          {
            unsigned int n;

            while ((n = runner_get_threads ()))
              {
                log_info ("number of running threads: %u\n", n);
                pth_sleep (5);
              }
          }
      }
      break;

    default:
      log_error (_("invalid command (there is no implicit command)\n"));
      break;
    }

  /* Print the audit result if needed.  */
  if (auditlog && auditfp)
    {
      /* audit_print_result (ctrl.audit, auditfp, 0); */
      /* audit_release (ctrl.audit); */
      ctrl.audit = NULL;
      es_fclose (auditfp);
    }
  
  /* Cleanup.  */
  g13_exit (0);
  return 8; /*NOTREACHED*/
}

/* Note: This function is used by signal handlers!. */
static void
emergency_cleanup (void)
{
  gcry_control (GCRYCTL_TERM_SECMEM );
}


void
g13_exit (int rc)
{
  gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
  if (opt.debug & DBG_MEMSTAT_VALUE)
    {
      gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
      gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
    }
  if (opt.debug)
    gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
  emergency_cleanup ();
  rc = rc? rc : log_get_errorcount(0)? 2 : g13_errors_seen? 1 : 0;
  exit (rc);
}


void
g13_init_default_ctrl (struct server_control_s *ctrl)
{
  ctrl->conttype = CONTTYPE_ENCFS;
}


/* static void */
/* daemonize (int nodetach) */
/* { */
/*   gnupg_fd_t fd; */
/*   gnupg_fd_t fd_ssh; */
/*   pid_t pid; */

/*   fflush (NULL); */
/* #ifdef HAVE_W32_SYSTEM */
/*   pid = getpid (); */
/* #else /\*!HAVE_W32_SYSTEM*\/ */
/*   pid = fork (); */
/*   if (pid == (pid_t)-1)  */
/*     { */
/*       log_fatal ("fork failed: %s\n", strerror (errno) ); */
/*       g13_exit (1); */
/*     } */
/*   else if (pid) /\* We are the parent *\/ */
/*     {  */
/*       /\* We need to clwanup our resources.  An gcry_atfork might be */
/*          needed. *\/ */
/*       exit (0);  */
/*       /\*NOTREACHED*\/ */
/*     } /\* End parent *\/ */

/*   /\*  */
/*      This is the child */
/*   *\/ */

/*   /\* Detach from tty and put process into a new session *\/ */
/*   if (!nodetach ) */
/*     {  */
/*       int i; */
/*       unsigned int oldflags; */
      
/*       /\* Close stdin, stdout and stderr unless it is the log stream *\/ */
/*       for (i=0; i <= 2; i++)  */
/*         { */
/*           if (!log_test_fd (i) && i != fd ) */
/*             { */
/*               if ( ! close (i) */
/*                    && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) */
/*                 { */
/*                   log_error ("failed to open `%s': %s\n", */
/*                              "/dev/null", strerror (errno)); */
/*                   cleanup (); */
/*                   exit (1); */
/*                 } */
/*             } */
/*         } */
/*       if (setsid() == -1) */
/*         { */
/*           log_error ("setsid() failed: %s\n", strerror(errno) ); */
/*           cleanup (); */
/*           exit (1); */
/*         } */

/*       log_get_prefix (&oldflags); */
/*       log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED); */
/*       opt.running_detached = 1; */
/*     } */
  
/*   if (chdir("/")) */
/*     { */
/*       log_error ("chdir to / failed: %s\n", strerror (errno)); */
/*       exit (1); */
/*     } */

/*   { */
/*     struct sigaction sa; */
    
/*     sa.sa_handler = SIG_IGN; */
/*     sigemptyset (&sa.sa_mask); */
/*     sa.sa_flags = 0; */
/*     sigaction (SIGPIPE, &sa, NULL); */
/*   } */
/* #endif /\*!HAVE_W32_SYSTEM*\/ */

/*   log_info ("%s %s started\n", strusage(11), strusage(13) ); */
/*   handle_something (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD); */
/* } */