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