chiark / gitweb /
scd: Fix factory-reset.
[gnupg2.git] / scd / scdaemon.c
1 /* scdaemon.c  -  The GnuPG Smartcard Daemon
2  * Copyright (C) 2001-2002, 2004-2005, 2007-2009 Free Software Foundation, Inc.
3  * Copyright (C) 2001-2002, 2004-2005, 2007-2014 Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <time.h>
31 #include <fcntl.h>
32 #ifndef HAVE_W32_SYSTEM
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 #endif /*HAVE_W32_SYSTEM*/
36 #include <unistd.h>
37 #include <signal.h>
38 #include <npth.h>
39
40 #define GNUPG_COMMON_NEED_AFLOCAL
41 #include "scdaemon.h"
42 #include <ksba.h>
43 #include <gcrypt.h>
44
45 #include <assuan.h> /* malloc hooks */
46
47 #include "i18n.h"
48 #include "sysutils.h"
49 #include "app-common.h"
50 #include "iso7816.h"
51 #include "apdu.h"
52 #include "ccid-driver.h"
53 #include "gc-opt-flags.h"
54 #include "asshelp.h"
55 #include "exechelp.h"
56 #include "../common/init.h"
57
58 #ifndef ENAMETOOLONG
59 # define ENAMETOOLONG EINVAL
60 #endif
61
62 enum cmd_and_opt_values
63 { aNull = 0,
64   oCsh            = 'c',
65   oQuiet          = 'q',
66   oSh             = 's',
67   oVerbose        = 'v',
68
69   oNoVerbose = 500,
70   aGPGConfList,
71   aGPGConfTest,
72   oOptions,
73   oDebug,
74   oDebugAll,
75   oDebugLevel,
76   oDebugWait,
77   oDebugAllowCoreDump,
78   oDebugCCIDDriver,
79   oDebugLogTid,
80   oDebugAssuanLogCats,
81   oNoGreeting,
82   oNoOptions,
83   oHomedir,
84   oNoDetach,
85   oNoGrab,
86   oLogFile,
87   oServer,
88   oMultiServer,
89   oDaemon,
90   oBatch,
91   oReaderPort,
92   oCardTimeout,
93   octapiDriver,
94   opcscDriver,
95   oDisableCCID,
96   oDisableOpenSC,
97   oDisablePinpad,
98   oAllowAdmin,
99   oDenyAdmin,
100   oDisableApplication,
101   oEnablePinpadVarlen,
102   oDebugDisableTicker
103 };
104
105
106
107 static ARGPARSE_OPTS opts[] = {
108   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
109   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
110
111   ARGPARSE_group (301, N_("@Options:\n ")),
112
113   ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
114   ARGPARSE_s_n (oMultiServer, "multi-server",
115                 N_("run in multi server mode (foreground)")),
116   ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
117   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
118   ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
119   ARGPARSE_s_n (oSh,    "sh", N_("sh-style command output")),
120   ARGPARSE_s_n (oCsh,   "csh", N_("csh-style command output")),
121   ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
122   ARGPARSE_s_s (oDebug, "debug", "@"),
123   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
124   ARGPARSE_s_s (oDebugLevel, "debug-level" ,
125                 N_("|LEVEL|set the debugging level to LEVEL")),
126   ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
127   ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
128   ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
129   ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
130   ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
131   ARGPARSE_p_u (oDebugAssuanLogCats, "debug-assuan-log-cats", "@"),
132   ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
133   ARGPARSE_s_s (oLogFile,  "log-file", N_("|FILE|write a log to FILE")),
134   ARGPARSE_s_s (oReaderPort, "reader-port",
135                 N_("|N|connect to reader at port N")),
136   ARGPARSE_s_s (octapiDriver, "ctapi-driver",
137                 N_("|NAME|use NAME as ct-API driver")),
138   ARGPARSE_s_s (opcscDriver, "pcsc-driver",
139                 N_("|NAME|use NAME as PC/SC driver")),
140   ARGPARSE_s_n (oDisableCCID, "disable-ccid",
141 #ifdef HAVE_LIBUSB
142                                     N_("do not use the internal CCID driver")
143 #else
144                                     "@"
145 #endif
146                 /* end --disable-ccid */),
147   ARGPARSE_s_u (oCardTimeout, "card-timeout",
148                 N_("|N|disconnect the card after N seconds of inactivity")),
149
150   ARGPARSE_s_n (oDisablePinpad, "disable-pinpad",
151                 N_("do not use a reader's pinpad")),
152   ARGPARSE_ignore (300, "disable-keypad"),
153
154   ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
155   ARGPARSE_s_n (oDenyAdmin, "deny-admin",
156                 N_("deny the use of admin card commands")),
157   ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
158   ARGPARSE_s_n (oEnablePinpadVarlen, "enable-pinpad-varlen",
159                 N_("use variable length input for pinpad")),
160   ARGPARSE_s_s (oHomedir,    "homedir",      "@"),
161
162   ARGPARSE_end ()
163 };
164
165
166 /* The list of supported debug flags.  */
167 static struct debug_flags_s debug_flags [] =
168   {
169     { DBG_MPI_VALUE    , "mpi"     },
170     { DBG_CRYPTO_VALUE , "crypto"  },
171     { DBG_MEMORY_VALUE , "memory"  },
172     { DBG_CACHE_VALUE  , "cache"   },
173     { DBG_MEMSTAT_VALUE, "memstat" },
174     { DBG_HASHING_VALUE, "hashing" },
175     { DBG_IPC_VALUE    , "ipc"     },
176     { DBG_CARD_IO_VALUE, "cardio"  },
177     { DBG_READER_VALUE , "reader"  },
178     { 0, NULL }
179   };
180
181
182 /* The card driver we use by default for PC/SC.  */
183 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
184 #define DEFAULT_PCSC_DRIVER "winscard.dll"
185 #elif defined(__APPLE__)
186 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
187 #elif defined(__GLIBC__)
188 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
189 #else
190 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
191 #endif
192
193 /* The timer tick used for housekeeping stuff.  We poll every 500ms to
194    let the user immediately know a status change.
195
196    This is not too good for power saving but given that there is no
197    easy way to block on card status changes it is the best we can do.
198    For PC/SC we could in theory use an extra thread to wait for status
199    changes but that requires a native thread because there is no way
200    to make the underlying PC/SC card change function block using a Npth
201    mechanism.  Given that a native thread could only be used under W32
202    we don't do that at all.  */
203 #define TIMERTICK_INTERVAL_SEC     (0)
204 #define TIMERTICK_INTERVAL_USEC    (500000)
205
206 /* Flag to indicate that a shutdown was requested. */
207 static int shutdown_pending;
208
209 /* It is possible that we are currently running under setuid permissions */
210 static int maybe_setuid = 1;
211
212 /* Flag telling whether we are running as a pipe server.  */
213 static int pipe_server;
214
215 /* Name of the communication socket */
216 static char *socket_name;
217 /* Name of the redirected socket or NULL.  */
218 static char *redir_socket_name;
219
220 /* We need to keep track of the server's nonces (these are dummies for
221    POSIX systems). */
222 static assuan_sock_nonce_t socket_nonce;
223
224 /* Debug flag to disable the ticker.  The ticker is in fact not
225    disabled but it won't perform any ticker specific actions. */
226 static int ticker_disabled;
227
228 /* FD to notify update of usb devices.  */
229 static int notify_fd;
230 \f
231 static char *create_socket_name (char *standard_name);
232 static gnupg_fd_t create_server_socket (const char *name,
233                                         char **r_redir_name,
234                                         assuan_sock_nonce_t *nonce);
235
236 static void *start_connection_thread (void *arg);
237 static void handle_connections (int listen_fd);
238
239 /* Pth wrapper function definitions. */
240 ASSUAN_SYSTEM_NPTH_IMPL;
241
242 static int active_connections;
243
244 \f
245 static char *
246 make_libversion (const char *libname, const char *(*getfnc)(const char*))
247 {
248   const char *s;
249   char *result;
250
251   if (maybe_setuid)
252     {
253       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
254       maybe_setuid = 0;
255     }
256   s = getfnc (NULL);
257   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
258   strcpy (stpcpy (stpcpy (result, libname), " "), s);
259   return result;
260 }
261
262
263 static const char *
264 my_strusage (int level)
265 {
266   static char *ver_gcry, *ver_ksba;
267   const char *p;
268
269   switch (level)
270     {
271     case 11: p = "@SCDAEMON@ (@GNUPG@)";
272       break;
273     case 13: p = VERSION; break;
274     case 17: p = PRINTABLE_OS_NAME; break;
275     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
276
277     case 20:
278       if (!ver_gcry)
279         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
280       p = ver_gcry;
281       break;
282     case 21:
283       if (!ver_ksba)
284         ver_ksba = make_libversion ("libksba", ksba_check_version);
285       p = ver_ksba;
286       break;
287     case 1:
288     case 40: p =  _("Usage: @SCDAEMON@ [options] (-h for help)");
289       break;
290     case 41: p =  _("Syntax: scdaemon [options] [command [args]]\n"
291                     "Smartcard daemon for @GNUPG@\n");
292     break;
293
294     default: p = NULL;
295     }
296   return p;
297 }
298
299
300 static int
301 tid_log_callback (unsigned long *rvalue)
302 {
303   int len = sizeof (*rvalue);
304   npth_t thread;
305
306   thread = npth_self ();
307   if (sizeof (thread) < len)
308     len = sizeof (thread);
309   memcpy (rvalue, &thread, len);
310
311   return 2; /* Use use hex representation.  */
312 }
313
314
315 /* Setup the debugging.  With a LEVEL of NULL only the active debug
316    flags are propagated to the subsystems.  With LEVEL set, a specific
317    set of debug flags is set; thus overriding all flags already
318    set. */
319 static void
320 set_debug (const char *level)
321 {
322   int numok = (level && digitp (level));
323   int numlvl = numok? atoi (level) : 0;
324
325   if (!level)
326     ;
327   else if (!strcmp (level, "none") || (numok && numlvl < 1))
328     opt.debug = 0;
329   else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
330     opt.debug = DBG_IPC_VALUE;
331   else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
332     opt.debug = DBG_IPC_VALUE;
333   else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
334     opt.debug = (DBG_IPC_VALUE|DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
335   else if (!strcmp (level, "guru") || numok)
336     {
337       opt.debug = ~0;
338       /* Unless the "guru" string has been used we don't want to allow
339          hashing debugging.  The rationale is that people tend to
340          select the highest debug value and would then clutter their
341          disk with debug files which may reveal confidential data.  */
342       if (numok)
343         opt.debug &= ~(DBG_HASHING_VALUE);
344     }
345   else
346     {
347       log_error (_("invalid debug-level '%s' given\n"), level);
348       scd_exit(2);
349     }
350
351
352   if (opt.debug && !opt.verbose)
353     opt.verbose = 1;
354   if (opt.debug && opt.quiet)
355     opt.quiet = 0;
356
357   if (opt.debug & DBG_MPI_VALUE)
358     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
359   if (opt.debug & DBG_CRYPTO_VALUE )
360     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
361   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
362
363   if (opt.debug)
364     parse_debug_flag (NULL, &opt.debug, debug_flags);
365 }
366
367
368
369 static void
370 cleanup (void)
371 {
372   if (socket_name && *socket_name)
373     {
374       char *name;
375
376       name = redir_socket_name? redir_socket_name : socket_name;
377
378       gnupg_remove (name);
379       *socket_name = 0;
380     }
381 }
382
383
384
385 int
386 main (int argc, char **argv )
387 {
388   ARGPARSE_ARGS pargs;
389   int orig_argc;
390   char **orig_argv;
391   FILE *configfp = NULL;
392   char *configname = NULL;
393   const char *shell;
394   unsigned int configlineno;
395   int parse_debug = 0;
396   const char *debug_level = NULL;
397   int default_config =1;
398   int greeting = 0;
399   int nogreeting = 0;
400   int multi_server = 0;
401   int is_daemon = 0;
402   int nodetach = 0;
403   int csh_style = 0;
404   char *logfile = NULL;
405   int debug_wait = 0;
406   int gpgconf_list = 0;
407   const char *config_filename = NULL;
408   int allow_coredump = 0;
409   struct assuan_malloc_hooks malloc_hooks;
410   int res;
411   npth_t pipecon_handler;
412
413   early_system_init ();
414   set_strusage (my_strusage);
415   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
416   /* Please note that we may running SUID(ROOT), so be very CAREFUL
417      when adding any stuff between here and the call to INIT_SECMEM()
418      somewhere after the option parsing */
419   log_set_prefix ("scdaemon", GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
420
421   /* Make sure that our subsystems are ready.  */
422   i18n_init ();
423   init_common_subsystems (&argc, &argv);
424
425   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
426
427   malloc_hooks.malloc = gcry_malloc;
428   malloc_hooks.realloc = gcry_realloc;
429   malloc_hooks.free = gcry_free;
430   assuan_set_malloc_hooks (&malloc_hooks);
431   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
432   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
433   assuan_sock_init ();
434   setup_libassuan_logging (&opt.debug, NULL);
435
436   setup_libgcrypt_logging ();
437   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
438
439   disable_core_dumps ();
440
441   /* Set default options. */
442   opt.allow_admin = 1;
443   opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
444
445   shell = getenv ("SHELL");
446   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
447     csh_style = 1;
448
449   /* Check whether we have a config file on the commandline */
450   orig_argc = argc;
451   orig_argv = argv;
452   pargs.argc = &argc;
453   pargs.argv = &argv;
454   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
455   while (arg_parse( &pargs, opts))
456     {
457       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
458         parse_debug++;
459       else if (pargs.r_opt == oOptions)
460         { /* yes there is one, so we do not try the default one, but
461              read the option file when it is encountered at the
462              commandline */
463           default_config = 0;
464         }
465         else if (pargs.r_opt == oNoOptions)
466           default_config = 0; /* --no-options */
467         else if (pargs.r_opt == oHomedir)
468           gnupg_set_homedir (pargs.r.ret_str);
469     }
470
471   /* initialize the secure memory. */
472   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
473   maybe_setuid = 0;
474
475   /*
476      Now we are working under our real uid
477   */
478
479
480   if (default_config)
481     configname = make_filename (gnupg_homedir (), SCDAEMON_NAME EXTSEP_S "conf",
482                                 NULL );
483
484
485   argc = orig_argc;
486   argv = orig_argv;
487   pargs.argc = &argc;
488   pargs.argv = &argv;
489   pargs.flags=  1;  /* do not remove the args */
490  next_pass:
491   if (configname)
492     {
493       configlineno = 0;
494       configfp = fopen (configname, "r");
495       if (!configfp)
496         {
497           if (default_config)
498             {
499               if( parse_debug )
500                 log_info (_("Note: no default option file '%s'\n"),
501                           configname );
502             }
503           else
504             {
505               log_error (_("option file '%s': %s\n"),
506                          configname, strerror(errno) );
507               exit(2);
508             }
509           xfree (configname);
510           configname = NULL;
511         }
512       if (parse_debug && configname )
513         log_info (_("reading options from '%s'\n"), configname );
514       default_config = 0;
515     }
516
517   while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
518     {
519       switch (pargs.r_opt)
520         {
521         case aGPGConfList: gpgconf_list = 1; break;
522         case aGPGConfTest: gpgconf_list = 2; break;
523         case oQuiet: opt.quiet = 1; break;
524         case oVerbose: opt.verbose++; break;
525         case oBatch: opt.batch=1; break;
526
527         case oDebug:
528           if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
529             {
530               pargs.r_opt = ARGPARSE_INVALID_ARG;
531               pargs.err = ARGPARSE_PRINT_ERROR;
532             }
533           break;
534         case oDebugAll: opt.debug = ~0; break;
535         case oDebugLevel: debug_level = pargs.r.ret_str; break;
536         case oDebugWait: debug_wait = pargs.r.ret_int; break;
537         case oDebugAllowCoreDump:
538           enable_core_dumps ();
539           allow_coredump = 1;
540           break;
541         case oDebugCCIDDriver:
542 #ifdef HAVE_LIBUSB
543           ccid_set_debug_level (ccid_set_debug_level (-1)+1);
544 #endif /*HAVE_LIBUSB*/
545           break;
546         case oDebugDisableTicker: ticker_disabled = 1; break;
547         case oDebugLogTid:
548           log_set_pid_suffix_cb (tid_log_callback);
549           break;
550         case oDebugAssuanLogCats:
551           set_libassuan_log_cats (pargs.r.ret_ulong);
552           break;
553
554         case oOptions:
555           /* config files may not be nested (silently ignore them) */
556           if (!configfp)
557             {
558                 xfree(configname);
559                 configname = xstrdup(pargs.r.ret_str);
560                 goto next_pass;
561             }
562           break;
563         case oNoGreeting: nogreeting = 1; break;
564         case oNoVerbose: opt.verbose = 0; break;
565         case oNoOptions: break; /* no-options */
566         case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
567         case oNoDetach: nodetach = 1; break;
568         case oLogFile: logfile = pargs.r.ret_str; break;
569         case oCsh: csh_style = 1; break;
570         case oSh: csh_style = 0; break;
571         case oServer: pipe_server = 1; break;
572         case oMultiServer: pipe_server = 1; multi_server = 1; break;
573         case oDaemon: is_daemon = 1; break;
574
575         case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
576         case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
577         case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
578         case oDisableCCID: opt.disable_ccid = 1; break;
579         case oDisableOpenSC: break;
580
581         case oDisablePinpad: opt.disable_pinpad = 1; break;
582
583         case oAllowAdmin: /* Dummy because allow is now the default.  */
584           break;
585         case oDenyAdmin: opt.allow_admin = 0; break;
586
587         case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
588
589         case oDisableApplication:
590           add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
591           break;
592
593         case oEnablePinpadVarlen: opt.enable_pinpad_varlen = 1; break;
594
595         default:
596           pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
597           break;
598         }
599     }
600   if (configfp)
601     {
602       fclose( configfp );
603       configfp = NULL;
604       /* Keep a copy of the config name for use by --gpgconf-list. */
605       config_filename = configname;
606       configname = NULL;
607       goto next_pass;
608     }
609   xfree (configname);
610   configname = NULL;
611   if (log_get_errorcount(0))
612     exit(2);
613   if (nogreeting )
614     greeting = 0;
615
616   if (greeting)
617     {
618       es_fprintf (es_stderr, "%s %s; %s\n",
619                   strusage(11), strusage(13), strusage(14) );
620       es_fprintf (es_stderr, "%s\n", strusage(15) );
621     }
622 #ifdef IS_DEVELOPMENT_VERSION
623   log_info ("NOTE: this is a development version!\n");
624 #endif
625
626   /* Print a warning if an argument looks like an option.  */
627   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
628     {
629       int i;
630
631       for (i=0; i < argc; i++)
632         if (argv[i][0] == '-' && argv[i][1] == '-')
633           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
634     }
635
636   if (atexit (cleanup))
637     {
638       log_error ("atexit failed\n");
639       cleanup ();
640       exit (1);
641     }
642
643   set_debug (debug_level);
644
645   if (initialize_module_command ())
646     {
647       log_error ("initialization failed\n");
648       cleanup ();
649       exit (1);
650     }
651
652   if (gpgconf_list == 2)
653     scd_exit (0);
654   if (gpgconf_list)
655     {
656       /* List options and default values in the GPG Conf format.  */
657       char *filename = NULL;
658       char *filename_esc;
659
660       if (config_filename)
661         filename = xstrdup (config_filename);
662       else
663         filename = make_filename (gnupg_homedir (),
664                                   SCDAEMON_NAME EXTSEP_S "conf", NULL);
665       filename_esc = percent_escape (filename, NULL);
666
667       es_printf ("%s-%s.conf:%lu:\"%s\n",
668                  GPGCONF_NAME, SCDAEMON_NAME,
669                  GC_OPT_FLAG_DEFAULT, filename_esc);
670       xfree (filename_esc);
671       xfree (filename);
672
673       es_printf ("verbose:%lu:\n"
674                  "quiet:%lu:\n"
675                  "debug-level:%lu:\"none:\n"
676                  "log-file:%lu:\n",
677                  GC_OPT_FLAG_NONE,
678                  GC_OPT_FLAG_NONE,
679                  GC_OPT_FLAG_DEFAULT,
680                  GC_OPT_FLAG_NONE );
681
682       es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
683       es_printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
684       es_printf ("pcsc-driver:%lu:\"%s:\n",
685               GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
686 #ifdef HAVE_LIBUSB
687       es_printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
688 #endif
689       es_printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
690       es_printf ("disable-pinpad:%lu:\n", GC_OPT_FLAG_NONE );
691       es_printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
692       es_printf ("enable-pinpad-varlen:%lu:\n", GC_OPT_FLAG_NONE );
693
694       scd_exit (0);
695     }
696
697   /* Now start with logging to a file if this is desired.  */
698   if (logfile)
699     {
700       log_set_file (logfile);
701       log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
702     }
703
704   if (debug_wait && pipe_server)
705     {
706       log_debug ("waiting for debugger - my pid is %u .....\n",
707                  (unsigned int)getpid());
708       gnupg_sleep (debug_wait);
709       log_debug ("... okay\n");
710     }
711
712   if (pipe_server)
713     {
714       /* This is the simple pipe based server */
715       ctrl_t ctrl;
716       npth_attr_t tattr;
717       int fd = -1;
718
719 #ifndef HAVE_W32_SYSTEM
720       {
721         struct sigaction sa;
722
723         sa.sa_handler = SIG_IGN;
724         sigemptyset (&sa.sa_mask);
725         sa.sa_flags = 0;
726         sigaction (SIGPIPE, &sa, NULL);
727       }
728 #endif
729
730       npth_init ();
731       gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
732
733       /* If --debug-allow-core-dump has been given we also need to
734          switch the working directory to a place where we can actually
735          write. */
736       if (allow_coredump)
737         {
738           if (chdir("/tmp"))
739             log_debug ("chdir to '/tmp' failed: %s\n", strerror (errno));
740           else
741             log_debug ("changed working directory to '/tmp'\n");
742         }
743
744       /* In multi server mode we need to listen on an additional
745          socket.  Create that socket now before starting the handler
746          for the pipe connection.  This allows that handler to send
747          back the name of that socket. */
748       if (multi_server)
749         {
750           socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
751           fd = FD2INT(create_server_socket (socket_name,
752                                             &redir_socket_name, &socket_nonce));
753         }
754
755       res = npth_attr_init (&tattr);
756       if (res)
757         {
758           log_error ("error allocating thread attributes: %s\n",
759                      strerror (res));
760           scd_exit (2);
761         }
762       npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
763
764       ctrl = xtrycalloc (1, sizeof *ctrl);
765       if ( !ctrl )
766         {
767           log_error ("error allocating connection control data: %s\n",
768                      strerror (errno) );
769           scd_exit (2);
770         }
771       ctrl->thread_startup.fd = GNUPG_INVALID_FD;
772       res = npth_create (&pipecon_handler, &tattr, start_connection_thread, ctrl);
773       if (res)
774         {
775           log_error ("error spawning pipe connection handler: %s\n",
776                      strerror (res) );
777           xfree (ctrl);
778           scd_exit (2);
779         }
780       npth_setname_np (pipecon_handler, "pipe-connection");
781       npth_attr_destroy (&tattr);
782
783       /* We run handle_connection to wait for the shutdown signal and
784          to run the ticker stuff.  */
785       handle_connections (fd);
786       if (fd != -1)
787         close (fd);
788     }
789   else if (!is_daemon)
790     {
791       log_info (_("please use the option '--daemon'"
792                   " to run the program in the background\n"));
793     }
794   else
795     { /* Regular server mode */
796       int fd;
797 #ifndef HAVE_W32_SYSTEM
798       pid_t pid;
799       int i;
800 #endif
801
802       /* Create the socket.  */
803       socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
804       fd = FD2INT (create_server_socket (socket_name,
805                                          &redir_socket_name, &socket_nonce));
806
807
808       fflush (NULL);
809 #ifdef HAVE_W32_SYSTEM
810       (void)csh_style;
811       (void)nodetach;
812 #else
813       pid = fork ();
814       if (pid == (pid_t)-1)
815         {
816           log_fatal ("fork failed: %s\n", strerror (errno) );
817           exit (1);
818         }
819       else if (pid)
820         { /* we are the parent */
821           char *infostr;
822
823           close (fd);
824
825           /* create the info string: <name>:<pid>:<protocol_version> */
826           if (gpgrt_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
827                               socket_name, (ulong) pid) < 0)
828             {
829               log_error ("out of core\n");
830               kill (pid, SIGTERM);
831               exit (1);
832             }
833           *socket_name = 0; /* don't let cleanup() remove the socket -
834                                the child should do this from now on */
835           if (argc)
836             { /* run the program given on the commandline */
837               if (putenv (infostr))
838                 {
839                   log_error ("failed to set environment: %s\n",
840                              strerror (errno) );
841                   kill (pid, SIGTERM );
842                   exit (1);
843                 }
844               execvp (argv[0], argv);
845               log_error ("failed to run the command: %s\n", strerror (errno));
846               kill (pid, SIGTERM);
847               exit (1);
848             }
849           else
850             {
851               /* Print the environment string, so that the caller can use
852                  shell's eval to set it */
853               if (csh_style)
854                 {
855                   *strchr (infostr, '=') = ' ';
856                   es_printf ( "setenv %s;\n", infostr);
857                 }
858               else
859                 {
860                   es_printf ( "%s; export SCDAEMON_INFO;\n", infostr);
861                 }
862               xfree (infostr);
863               exit (0);
864             }
865           /* NOTREACHED */
866         } /* end parent */
867
868       /* This is the child. */
869
870       npth_init ();
871       gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
872
873       /* Detach from tty and put process into a new session. */
874       if (!nodetach )
875         {
876           /* Close stdin, stdout and stderr unless it is the log stream. */
877           for (i=0; i <= 2; i++)
878             {
879               if (!log_test_fd (i) && i != fd )
880                 {
881                   if ( !close (i)
882                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
883                     {
884                       log_error ("failed to open '%s': %s\n",
885                                  "/dev/null", strerror (errno));
886                       cleanup ();
887                       exit (1);
888                     }
889                 }
890             }
891
892           if (setsid() == -1)
893             {
894               log_error ("setsid() failed: %s\n", strerror(errno) );
895               cleanup ();
896               exit (1);
897             }
898         }
899
900       {
901         struct sigaction sa;
902
903         sa.sa_handler = SIG_IGN;
904         sigemptyset (&sa.sa_mask);
905         sa.sa_flags = 0;
906         sigaction (SIGPIPE, &sa, NULL);
907       }
908
909       if (chdir("/"))
910         {
911           log_error ("chdir to / failed: %s\n", strerror (errno));
912           exit (1);
913         }
914
915 #endif /*!HAVE_W32_SYSTEM*/
916
917       handle_connections (fd);
918
919       close (fd);
920     }
921
922   return 0;
923 }
924
925 void
926 scd_exit (int rc)
927 {
928   apdu_prepare_exit ();
929 #if 0
930 #warning no update_random_seed_file
931   update_random_seed_file();
932 #endif
933 #if 0
934   /* at this time a bit annoying */
935   if (opt.debug & DBG_MEMSTAT_VALUE)
936     {
937       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
938       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
939     }
940   if (opt.debug)
941     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
942 #endif
943   gcry_control (GCRYCTL_TERM_SECMEM );
944   rc = rc? rc : log_get_errorcount(0)? 2 : 0;
945   exit (rc);
946 }
947
948
949 static void
950 scd_init_default_ctrl (ctrl_t ctrl)
951 {
952   (void)ctrl;
953 }
954
955 static void
956 scd_deinit_default_ctrl (ctrl_t ctrl)
957 {
958   if (!ctrl)
959     return;
960   xfree (ctrl->in_data.value);
961   ctrl->in_data.value = NULL;
962   ctrl->in_data.valuelen = 0;
963 }
964
965
966 /* Return the name of the socket to be used to connect to this
967    process.  If no socket is available, return NULL. */
968 const char *
969 scd_get_socket_name ()
970 {
971   if (socket_name && *socket_name)
972     return socket_name;
973   return NULL;
974 }
975
976
977 #ifndef HAVE_W32_SYSTEM
978 static void
979 handle_signal (int signo)
980 {
981   switch (signo)
982     {
983     case SIGHUP:
984       log_info ("SIGHUP received - "
985                 "re-reading configuration and resetting cards\n");
986 /*       reread_configuration (); */
987       break;
988
989     case SIGUSR1:
990       log_info ("SIGUSR1 received - printing internal information:\n");
991       /* Fixme: We need to see how to integrate pth dumping into our
992          logging system.  */
993       /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
994       app_dump_state ();
995       break;
996
997     case SIGUSR2:
998       log_info ("SIGUSR2 received - no action defined\n");
999       break;
1000
1001     case SIGTERM:
1002       if (!shutdown_pending)
1003         log_info ("SIGTERM received - shutting down ...\n");
1004       else
1005         log_info ("SIGTERM received - still %i running threads\n",
1006                   active_connections);
1007       shutdown_pending++;
1008       if (shutdown_pending > 2)
1009         {
1010           log_info ("shutdown forced\n");
1011           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1012           cleanup ();
1013           scd_exit (0);
1014         }
1015       break;
1016
1017     case SIGINT:
1018       log_info ("SIGINT received - immediate shutdown\n");
1019       log_info( "%s %s stopped\n", strusage(11), strusage(13));
1020       cleanup ();
1021       scd_exit (0);
1022       break;
1023
1024     default:
1025       log_info ("signal %d received - no action defined\n", signo);
1026     }
1027 }
1028 #endif /*!HAVE_W32_SYSTEM*/
1029
1030
1031 static void
1032 handle_tick (void)
1033 {
1034   if (!ticker_disabled)
1035     scd_update_reader_status_file ();
1036 }
1037
1038
1039 /* Create a name for the socket.  We check for valid characters as
1040    well as against a maximum allowed length for a unix domain socket
1041    is done.  The function terminates the process in case of an error.
1042    Retunrs: Pointer to an allcoated string with the absolute name of
1043    the socket used.  */
1044 static char *
1045 create_socket_name (char *standard_name)
1046 {
1047   char *name;
1048
1049   name = make_filename (gnupg_socketdir (), standard_name, NULL);
1050   if (strchr (name, PATHSEP_C))
1051     {
1052       log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1053       scd_exit (2);
1054     }
1055   return name;
1056 }
1057
1058
1059
1060 /* Create a Unix domain socket with NAME.  Returns the file descriptor
1061    or terminates the process in case of an error.  If the socket has
1062    been redirected the name of the real socket is stored as a malloced
1063    string at R_REDIR_NAME. */
1064 static gnupg_fd_t
1065 create_server_socket (const char *name, char **r_redir_name,
1066                       assuan_sock_nonce_t *nonce)
1067 {
1068   struct sockaddr *addr;
1069   struct sockaddr_un *unaddr;
1070   socklen_t len;
1071   gnupg_fd_t fd;
1072   int rc;
1073
1074   xfree (*r_redir_name);
1075   *r_redir_name = NULL;
1076
1077   fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1078   if (fd == GNUPG_INVALID_FD)
1079     {
1080       log_error (_("can't create socket: %s\n"), strerror (errno));
1081       scd_exit (2);
1082     }
1083
1084   unaddr = xmalloc (sizeof (*unaddr));
1085   addr = (struct sockaddr*)unaddr;
1086
1087   {
1088     int redirected;
1089
1090     if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1091       {
1092         if (errno == ENAMETOOLONG)
1093           log_error (_("socket name '%s' is too long\n"), name);
1094         else
1095           log_error ("error preparing socket '%s': %s\n",
1096                      name, gpg_strerror (gpg_error_from_syserror ()));
1097         scd_exit (2);
1098       }
1099     if (redirected)
1100       {
1101         *r_redir_name = xstrdup (unaddr->sun_path);
1102         if (opt.verbose)
1103           log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1104       }
1105   }
1106
1107   len = SUN_LEN (unaddr);
1108
1109   rc = assuan_sock_bind (fd, addr, len);
1110   if (rc == -1 && errno == EADDRINUSE)
1111     {
1112       gnupg_remove (unaddr->sun_path);
1113       rc = assuan_sock_bind (fd, addr, len);
1114     }
1115   if (rc != -1
1116       && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1117     log_error (_("error getting nonce for the socket\n"));
1118  if (rc == -1)
1119     {
1120       log_error (_("error binding socket to '%s': %s\n"),
1121                  unaddr->sun_path,
1122                  gpg_strerror (gpg_error_from_syserror ()));
1123       assuan_sock_close (fd);
1124       scd_exit (2);
1125     }
1126
1127   if (gnupg_chmod (unaddr->sun_path, "-rwx"))
1128     log_error (_("can't set permissions of '%s': %s\n"),
1129                unaddr->sun_path, strerror (errno));
1130
1131   if (listen (FD2INT(fd), 5 ) == -1)
1132     {
1133       log_error (_("listen() failed: %s\n"),
1134                  gpg_strerror (gpg_error_from_syserror ()));
1135       assuan_sock_close (fd);
1136       scd_exit (2);
1137     }
1138
1139   if (opt.verbose)
1140     log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1141
1142   return fd;
1143 }
1144
1145
1146
1147 /* This is the standard connection thread's main function.  */
1148 static void *
1149 start_connection_thread (void *arg)
1150 {
1151   ctrl_t ctrl = arg;
1152
1153   if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1154       && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1155     {
1156       log_info (_("error reading nonce on fd %d: %s\n"),
1157                 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1158       assuan_sock_close (ctrl->thread_startup.fd);
1159       xfree (ctrl);
1160       return NULL;
1161     }
1162
1163   scd_init_default_ctrl (ctrl);
1164   if (opt.verbose)
1165     log_info (_("handler for fd %d started\n"),
1166               FD2INT(ctrl->thread_startup.fd));
1167
1168   /* If this is a pipe server, we request a shutdown if the command
1169      handler asked for it.  With the next ticker event and given that
1170      no other connections are running the shutdown will then
1171      happen.  */
1172   if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1173       && pipe_server)
1174     shutdown_pending = 1;
1175
1176   if (opt.verbose)
1177     log_info (_("handler for fd %d terminated\n"),
1178               FD2INT (ctrl->thread_startup.fd));
1179
1180   scd_deinit_default_ctrl (ctrl);
1181   xfree (ctrl);
1182   return NULL;
1183 }
1184
1185
1186 void
1187 scd_kick_the_loop (void)
1188 {
1189   int ret;
1190
1191   /* Kick the select loop.  */
1192   ret = write (notify_fd, "", 1);
1193   (void)ret;
1194 }
1195
1196 /* Connection handler loop.  Wait for connection requests and spawn a
1197    thread after accepting a connection.  LISTEN_FD is allowed to be -1
1198    in which case this code will only do regular timeouts and handle
1199    signals. */
1200 static void
1201 handle_connections (int listen_fd)
1202 {
1203   npth_attr_t tattr;
1204   struct sockaddr_un paddr;
1205   socklen_t plen;
1206   fd_set fdset, read_fdset;
1207   int ret;
1208   int fd;
1209   int nfd;
1210   struct timespec abstime;
1211   struct timespec curtime;
1212   struct timespec timeout;
1213   int saved_errno;
1214 #ifndef HAVE_W32_SYSTEM
1215   int signo;
1216 #endif
1217   int pipe_fd[2];
1218
1219   ret = gnupg_create_pipe (pipe_fd);
1220   if (ret)
1221     {
1222       log_error ("pipe creation failed: %s\n", gpg_strerror (ret));
1223       return;
1224     }
1225   notify_fd = pipe_fd[1];
1226
1227   ret = npth_attr_init(&tattr);
1228   if (ret)
1229     {
1230       log_error ("npth_attr_init failed: %s\n", strerror (ret));
1231       return;
1232     }
1233
1234   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1235
1236 #ifndef HAVE_W32_SYSTEM
1237   npth_sigev_init ();
1238   npth_sigev_add (SIGHUP);
1239   npth_sigev_add (SIGUSR1);
1240   npth_sigev_add (SIGUSR2);
1241   npth_sigev_add (SIGINT);
1242   npth_sigev_add (SIGTERM);
1243   npth_sigev_fini ();
1244 #endif
1245
1246   FD_ZERO (&fdset);
1247   nfd = 0;
1248   if (listen_fd != -1)
1249     {
1250       FD_SET (listen_fd, &fdset);
1251       nfd = listen_fd;
1252     }
1253
1254   npth_clock_gettime (&curtime);
1255   timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1256   timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1257   npth_timeradd (&curtime, &timeout, &abstime);
1258   /* We only require abstime here.  The others will be reused.  */
1259
1260   for (;;)
1261     {
1262       int max_fd;
1263
1264       if (shutdown_pending)
1265         {
1266           if (active_connections == 0)
1267             break; /* ready */
1268
1269           /* Do not accept anymore connections but wait for existing
1270              connections to terminate. We do this by clearing out all
1271              file descriptors to wait for, so that the select will be
1272              used to just wait on a signal or timeout event. */
1273           FD_ZERO (&fdset);
1274           listen_fd = -1;
1275         }
1276
1277       npth_clock_gettime (&curtime);
1278       if (!(npth_timercmp (&curtime, &abstime, <)))
1279         {
1280           /* Timeout.  */
1281           handle_tick ();
1282           timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1283           timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1284           npth_timeradd (&curtime, &timeout, &abstime);
1285         }
1286       npth_timersub (&abstime, &curtime, &timeout);
1287
1288       /* POSIX says that fd_set should be implemented as a structure,
1289          thus a simple assignment is fine to copy the entire set.  */
1290       read_fdset = fdset;
1291
1292       FD_SET (pipe_fd[0], &read_fdset);
1293       if (nfd < pipe_fd[0])
1294         max_fd = pipe_fd[0];
1295       else
1296         max_fd = nfd;
1297
1298 #ifndef HAVE_W32_SYSTEM
1299       ret = npth_pselect (max_fd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask());
1300       saved_errno = errno;
1301
1302       while (npth_sigev_get_pending(&signo))
1303         handle_signal (signo);
1304 #else
1305       ret = npth_eselect (max_fd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
1306       saved_errno = errno;
1307 #endif
1308
1309       if (ret == -1 && saved_errno != EINTR)
1310         {
1311           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1312                      strerror (saved_errno));
1313           npth_sleep (1);
1314           continue;
1315         }
1316
1317       if (ret <= 0)
1318         /* Timeout.  Will be handled when calculating the next timeout.  */
1319         continue;
1320
1321       if (FD_ISSET (pipe_fd[0], &read_fdset))
1322         {
1323           char buf[256];
1324
1325           ret = read (pipe_fd[0], buf, sizeof buf);
1326         }
1327
1328       if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1329         {
1330           ctrl_t ctrl;
1331
1332           plen = sizeof paddr;
1333           fd = npth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1334           if (fd == -1)
1335             {
1336               log_error ("accept failed: %s\n", strerror (errno));
1337             }
1338           else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1339             {
1340               log_error ("error allocating connection control data: %s\n",
1341                          strerror (errno) );
1342               close (fd);
1343             }
1344           else
1345             {
1346               char threadname[50];
1347               npth_t thread;
1348
1349               snprintf (threadname, sizeof threadname, "conn fd=%d", fd);
1350               ctrl->thread_startup.fd = INT2FD (fd);
1351               ret = npth_create (&thread, &tattr, start_connection_thread, ctrl);
1352               if (ret)
1353                 {
1354                   log_error ("error spawning connection handler: %s\n",
1355                              strerror (ret));
1356                   xfree (ctrl);
1357                   close (fd);
1358                 }
1359               else
1360                 npth_setname_np (thread, threadname);
1361             }
1362           fd = -1;
1363         }
1364     }
1365
1366   close (pipe_fd[0]);
1367   close (pipe_fd[1]);
1368   cleanup ();
1369   log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1370   npth_attr_destroy (&tattr);
1371 }