Fix signal handling race condition.
[gnupg.git] / scd / scdaemon.c
bloba094ae36b2a380200b33242e56c2e6460b2bf2fc
1 /* scdaemon.c - The GnuPG Smartcard Daemon
2 * Copyright (C) 2001, 2002, 2004, 2005,
3 * 2007, 2008 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
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 <pth.h>
40 #define JNLIB_NEED_LOG_LOGV
41 #include "scdaemon.h"
42 #include <ksba.h>
43 #include <gcrypt.h>
45 #include <assuan.h> /* malloc hooks */
47 #include "i18n.h"
48 #include "sysutils.h"
49 #include "app-common.h"
50 #include "ccid-driver.h"
51 #include "mkdtemp.h"
52 #include "gc-opt-flags.h"
55 enum cmd_and_opt_values
56 { aNull = 0,
57 oCsh = 'c',
58 oQuiet = 'q',
59 oSh = 's',
60 oVerbose = 'v',
62 oNoVerbose = 500,
63 aGPGConfList,
64 aGPGConfTest,
65 oOptions,
66 oDebug,
67 oDebugAll,
68 oDebugLevel,
69 oDebugWait,
70 oDebugAllowCoreDump,
71 oDebugCCIDDriver,
72 oNoGreeting,
73 oNoOptions,
74 oHomedir,
75 oNoDetach,
76 oNoGrab,
77 oLogFile,
78 oServer,
79 oMultiServer,
80 oDaemon,
81 oBatch,
82 oReaderPort,
83 oCardTimeout,
84 octapiDriver,
85 opcscDriver,
86 oDisableCCID,
87 oDisableOpenSC,
88 oDisableKeypad,
89 oAllowAdmin,
90 oDenyAdmin,
91 oDisableApplication,
92 oDebugDisableTicker
97 static ARGPARSE_OPTS opts[] = {
98 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
99 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
101 ARGPARSE_group (301, N_("@Options:\n ")),
103 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
104 ARGPARSE_s_n (oMultiServer, "multi-server",
105 N_("run in multi server mode (foreground)")),
106 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
107 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
108 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
109 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
110 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
111 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
112 ARGPARSE_p_u (oDebug, "debug", "@"),
113 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
114 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
115 N_("|LEVEL|set the debugging level to LEVEL")),
116 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
117 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
118 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
119 ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
120 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
121 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
122 ARGPARSE_s_s (oReaderPort, "reader-port",
123 N_("|N|connect to reader at port N")),
124 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
125 N_("|NAME|use NAME as ct-API driver")),
126 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
127 N_("|NAME|use NAME as PC/SC driver")),
128 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
129 #ifdef HAVE_LIBUSB
130 N_("do not use the internal CCID driver")
131 #else
133 #endif
134 /* end --disable-ccid */),
135 ARGPARSE_s_u (oCardTimeout, "card-timeout",
136 N_("|N|disconnect the card after N seconds of inactivity")),
137 ARGPARSE_s_n (oDisableKeypad, "disable-keypad",
138 N_("do not use a reader's keypad")),
139 ARGPARSE_s_n (oAllowAdmin, "allow-admin",
140 N_("allow the use of admin card commands")),
141 ARGPARSE_s_n (oDenyAdmin, "deny-admin", "@"),
142 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
144 ARGPARSE_end ()
148 /* The card driver we use by default for PC/SC. */
149 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
150 #define DEFAULT_PCSC_DRIVER "winscard.dll"
151 #elif defined(__APPLE__)
152 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
153 #elif defined(__GLIBC__)
154 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
155 #else
156 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
157 #endif
159 /* The timer tick used for housekeeping stuff. We poll every 500ms to
160 let the user immediately know a status change.
162 This is not too good for power saving but given that there is no
163 easy way to block on card status changes it is the best we can do.
164 For PC/SC we could in theory use an extra thread to wait for status
165 changes but that requires a native thread because there is no way
166 to make the underlying PC/SC card change function block using a Pth
167 mechanism. Given that a native thread could only be used under W32
168 we don't do that at all. */
169 #define TIMERTICK_INTERVAL_SEC (0)
170 #define TIMERTICK_INTERVAL_USEC (500000)
172 /* Flag to indicate that a shutdown was requested. */
173 static int shutdown_pending;
175 /* It is possible that we are currently running under setuid permissions */
176 static int maybe_setuid = 1;
178 /* Flag telling whether we are running as a pipe server. */
179 static int pipe_server;
181 /* Name of the communication socket */
182 static char *socket_name;
184 /* We need to keep track of the server's nonces (these are dummies for
185 POSIX systems). */
186 static assuan_sock_nonce_t socket_nonce;
188 /* Debug flag to disable the ticker. The ticker is in fact not
189 disabled but it won't perform any ticker specific actions. */
190 static int ticker_disabled;
194 static char *create_socket_name (int use_standard_socket,
195 char *standard_name, char *template);
196 static gnupg_fd_t create_server_socket (int is_standard_name, const char *name,
197 assuan_sock_nonce_t *nonce);
199 static void *start_connection_thread (void *arg);
200 static void handle_connections (int listen_fd);
202 /* Pth wrapper function definitions. */
203 GCRY_THREAD_OPTION_PTH_IMPL;
204 static int fixed_gcry_pth_init (void)
206 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
211 static char *
212 make_libversion (const char *libname, const char *(*getfnc)(const char*))
214 const char *s;
215 char *result;
217 if (maybe_setuid)
219 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
220 maybe_setuid = 0;
222 s = getfnc (NULL);
223 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
224 strcpy (stpcpy (stpcpy (result, libname), " "), s);
225 return result;
229 static const char *
230 my_strusage (int level)
232 static char *ver_gcry, *ver_ksba;
233 const char *p;
235 switch (level)
237 case 11: p = "scdaemon (GnuPG)";
238 break;
239 case 13: p = VERSION; break;
240 case 17: p = PRINTABLE_OS_NAME; break;
241 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
242 break;
243 case 20:
244 if (!ver_gcry)
245 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
246 p = ver_gcry;
247 break;
248 case 21:
249 if (!ver_ksba)
250 ver_ksba = make_libversion ("libksba", ksba_check_version);
251 p = ver_ksba;
252 break;
253 case 1:
254 case 40: p = _("Usage: scdaemon [options] (-h for help)");
255 break;
256 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
257 "Smartcard daemon for GnuPG\n");
258 break;
260 default: p = NULL;
262 return p;
269 /* Setup the debugging. With a LEVEL of NULL only the active debug
270 flags are propagated to the subsystems. With LEVEL set, a specific
271 set of debug flags is set; thus overriding all flags already
272 set. */
273 static void
274 set_debug (const char *level)
276 if (!level)
278 else if (!strcmp (level, "none"))
279 opt.debug = 0;
280 else if (!strcmp (level, "basic"))
281 opt.debug = DBG_ASSUAN_VALUE;
282 else if (!strcmp (level, "advanced"))
283 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
284 else if (!strcmp (level, "expert"))
285 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
286 |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
287 else if (!strcmp (level, "guru"))
288 opt.debug = ~0;
289 else
291 log_error (_("invalid debug-level `%s' given\n"), level);
292 scd_exit(2);
296 if (opt.debug && !opt.verbose)
297 opt.verbose = 1;
298 if (opt.debug && opt.quiet)
299 opt.quiet = 0;
301 if (opt.debug & DBG_MPI_VALUE)
302 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
303 if (opt.debug & DBG_CRYPTO_VALUE )
304 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
305 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
310 static void
311 cleanup (void)
313 if (socket_name && *socket_name)
315 char *p;
317 remove (socket_name);
318 p = strrchr (socket_name, '/');
319 if (p)
321 *p = 0;
322 rmdir (socket_name);
323 *p = '/';
325 *socket_name = 0;
332 main (int argc, char **argv )
334 ARGPARSE_ARGS pargs;
335 int orig_argc;
336 gpg_error_t err;
337 int may_coredump;
338 char **orig_argv;
339 FILE *configfp = NULL;
340 char *configname = NULL;
341 const char *shell;
342 unsigned int configlineno;
343 int parse_debug = 0;
344 const char *debug_level = NULL;
345 int default_config =1;
346 int greeting = 0;
347 int nogreeting = 0;
348 int multi_server = 0;
349 int is_daemon = 0;
350 int nodetach = 0;
351 int csh_style = 0;
352 char *logfile = NULL;
353 int debug_wait = 0;
354 int gpgconf_list = 0;
355 const char *config_filename = NULL;
356 int allow_coredump = 0;
357 int standard_socket = 0;
359 set_strusage (my_strusage);
360 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
361 /* Please note that we may running SUID(ROOT), so be very CAREFUL
362 when adding any stuff between here and the call to INIT_SECMEM()
363 somewhere after the option parsing */
364 log_set_prefix ("scdaemon", 1|4);
366 /* Make sure that our subsystems are ready. */
367 i18n_init ();
368 init_common_subsystems ();
371 /* Libgcrypt requires us to register the threading model first.
372 Note that this will also do the pth_init. */
373 gcry_threads_pth.init = fixed_gcry_pth_init;
374 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
375 if (err)
377 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
378 gpg_strerror (err));
381 /* Check that the libraries are suitable. Do it here because
382 the option parsing may need services of the library */
383 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
385 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
386 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
389 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
391 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
392 assuan_set_assuan_log_stream (log_get_stream ());
393 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
394 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
396 setup_libgcrypt_logging ();
397 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
399 may_coredump = disable_core_dumps ();
401 /* Set default options. */
402 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
404 #ifdef HAVE_W32_SYSTEM
405 standard_socket = 1; /* Under Windows we always use a standard
406 socket. */
407 #endif
410 shell = getenv ("SHELL");
411 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
412 csh_style = 1;
414 opt.homedir = default_homedir ();
416 /* Check whether we have a config file on the commandline */
417 orig_argc = argc;
418 orig_argv = argv;
419 pargs.argc = &argc;
420 pargs.argv = &argv;
421 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
422 while (arg_parse( &pargs, opts))
424 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
425 parse_debug++;
426 else if (pargs.r_opt == oOptions)
427 { /* yes there is one, so we do not try the default one, but
428 read the option file when it is encountered at the
429 commandline */
430 default_config = 0;
432 else if (pargs.r_opt == oNoOptions)
433 default_config = 0; /* --no-options */
434 else if (pargs.r_opt == oHomedir)
435 opt.homedir = pargs.r.ret_str;
438 /* initialize the secure memory. */
439 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
440 maybe_setuid = 0;
443 Now we are working under our real uid
447 if (default_config)
448 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
451 argc = orig_argc;
452 argv = orig_argv;
453 pargs.argc = &argc;
454 pargs.argv = &argv;
455 pargs.flags= 1; /* do not remove the args */
456 next_pass:
457 if (configname)
459 configlineno = 0;
460 configfp = fopen (configname, "r");
461 if (!configfp)
463 if (default_config)
465 if( parse_debug )
466 log_info (_("NOTE: no default option file `%s'\n"),
467 configname );
469 else
471 log_error (_("option file `%s': %s\n"),
472 configname, strerror(errno) );
473 exit(2);
475 xfree (configname);
476 configname = NULL;
478 if (parse_debug && configname )
479 log_info (_("reading options from `%s'\n"), configname );
480 default_config = 0;
483 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
485 switch (pargs.r_opt)
487 case aGPGConfList: gpgconf_list = 1; break;
488 case aGPGConfTest: gpgconf_list = 2; break;
489 case oQuiet: opt.quiet = 1; break;
490 case oVerbose: opt.verbose++; break;
491 case oBatch: opt.batch=1; break;
493 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
494 case oDebugAll: opt.debug = ~0; break;
495 case oDebugLevel: debug_level = pargs.r.ret_str; break;
496 case oDebugWait: debug_wait = pargs.r.ret_int; break;
497 case oDebugAllowCoreDump:
498 enable_core_dumps ();
499 allow_coredump = 1;
500 break;
501 case oDebugCCIDDriver:
502 #ifdef HAVE_LIBUSB
503 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
504 #endif /*HAVE_LIBUSB*/
505 break;
506 case oDebugDisableTicker: ticker_disabled = 1; break;
508 case oOptions:
509 /* config files may not be nested (silently ignore them) */
510 if (!configfp)
512 xfree(configname);
513 configname = xstrdup(pargs.r.ret_str);
514 goto next_pass;
516 break;
517 case oNoGreeting: nogreeting = 1; break;
518 case oNoVerbose: opt.verbose = 0; break;
519 case oNoOptions: break; /* no-options */
520 case oHomedir: opt.homedir = pargs.r.ret_str; break;
521 case oNoDetach: nodetach = 1; break;
522 case oLogFile: logfile = pargs.r.ret_str; break;
523 case oCsh: csh_style = 1; break;
524 case oSh: csh_style = 0; break;
525 case oServer: pipe_server = 1; break;
526 case oMultiServer: pipe_server = 1; multi_server = 1; break;
527 case oDaemon: is_daemon = 1; break;
529 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
530 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
531 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
532 case oDisableCCID: opt.disable_ccid = 1; break;
533 case oDisableOpenSC: break;
535 case oDisableKeypad: opt.disable_keypad = 1; break;
537 case oAllowAdmin: opt.allow_admin = 1; break;
538 case oDenyAdmin: opt.allow_admin = 0; break;
540 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
542 case oDisableApplication:
543 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
544 break;
546 default:
547 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
548 break;
551 if (configfp)
553 fclose( configfp );
554 configfp = NULL;
555 /* Keep a copy of the config name for use by --gpgconf-list. */
556 config_filename = configname;
557 configname = NULL;
558 goto next_pass;
560 xfree (configname);
561 configname = NULL;
562 if (log_get_errorcount(0))
563 exit(2);
564 if (nogreeting )
565 greeting = 0;
567 if (greeting)
569 fprintf (stderr, "%s %s; %s\n",
570 strusage(11), strusage(13), strusage(14) );
571 fprintf (stderr, "%s\n", strusage(15) );
573 #ifdef IS_DEVELOPMENT_VERSION
574 log_info ("NOTE: this is a development version!\n");
575 #endif
578 if (atexit (cleanup))
580 log_error ("atexit failed\n");
581 cleanup ();
582 exit (1);
585 set_debug (debug_level);
587 if (debug_wait && pipe_server)
589 log_debug ("waiting for debugger - my pid is %u .....\n",
590 (unsigned int)getpid());
591 gnupg_sleep (debug_wait);
592 log_debug ("... okay\n");
595 initialize_module_command ();
597 if (gpgconf_list == 2)
598 scd_exit (0);
599 if (gpgconf_list)
601 /* List options and default values in the GPG Conf format. */
602 char *filename = NULL;
603 char *filename_esc;
605 if (config_filename)
606 filename = xstrdup (config_filename);
607 else
608 filename = make_filename (opt.homedir, "scdaemon.conf", NULL);
609 filename_esc = percent_escape (filename, NULL);
611 printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
612 GC_OPT_FLAG_DEFAULT, filename_esc);
613 xfree (filename_esc);
614 xfree (filename);
616 printf ("verbose:%lu:\n"
617 "quiet:%lu:\n"
618 "debug-level:%lu:\"none:\n"
619 "log-file:%lu:\n",
620 GC_OPT_FLAG_NONE,
621 GC_OPT_FLAG_NONE,
622 GC_OPT_FLAG_DEFAULT,
623 GC_OPT_FLAG_NONE );
625 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
626 printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
627 printf ("pcsc-driver:%lu:\"%s:\n",
628 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
629 #ifdef HAVE_LIBUSB
630 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
631 #endif
632 printf ("allow-admin:%lu:\n", GC_OPT_FLAG_NONE );
633 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
634 printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
636 scd_exit (0);
639 /* now start with logging to a file if this is desired */
640 if (logfile)
642 log_set_file (logfile);
643 log_set_prefix (NULL, 1|2|4);
646 if (pipe_server)
648 /* This is the simple pipe based server */
649 ctrl_t ctrl;
650 pth_attr_t tattr;
651 int fd = -1;
653 #ifndef HAVE_W32_SYSTEM
655 struct sigaction sa;
657 sa.sa_handler = SIG_IGN;
658 sigemptyset (&sa.sa_mask);
659 sa.sa_flags = 0;
660 sigaction (SIGPIPE, &sa, NULL);
662 #endif
664 /* If --debug-allow-core-dump has been given we also need to
665 switch the working directory to a place where we can actually
666 write. */
667 if (allow_coredump)
669 if (chdir("/tmp"))
670 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
671 else
672 log_debug ("changed working directory to `/tmp'\n");
675 /* In multi server mode we need to listen on an additional
676 socket. Create that socket now before starting the handler
677 for the pipe connection. This allows that handler to send
678 back the name of that socket. */
679 if (multi_server)
681 socket_name = create_socket_name (standard_socket,
682 "S.scdaemon",
683 "/tmp/gpg-XXXXXX/S.scdaemon");
685 fd = FD2INT(create_server_socket (standard_socket,
686 socket_name, &socket_nonce));
689 tattr = pth_attr_new();
690 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
691 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
692 pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
694 ctrl = xtrycalloc (1, sizeof *ctrl);
695 if ( !ctrl )
697 log_error ("error allocating connection control data: %s\n",
698 strerror (errno) );
699 scd_exit (2);
701 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
702 if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
704 log_error ("error spawning pipe connection handler: %s\n",
705 strerror (errno) );
706 xfree (ctrl);
707 scd_exit (2);
710 /* We run handle_connection to wait for the shutdown signal and
711 to run the ticker stuff. */
712 handle_connections (fd);
713 if (fd != -1)
714 close (fd);
716 else if (!is_daemon)
718 log_info (_("please use the option `--daemon'"
719 " to run the program in the background\n"));
721 else
722 { /* Regular server mode */
723 int fd;
724 #ifndef HAVE_W32_SYSTEM
725 pid_t pid;
726 int i;
727 #endif
729 /* Create the socket. */
730 socket_name = create_socket_name (standard_socket,
731 "S.scdaemon",
732 "/tmp/gpg-XXXXXX/S.scdaemon");
734 fd = FD2INT (create_server_socket (standard_socket,
735 socket_name, &socket_nonce));
738 fflush (NULL);
739 #ifndef HAVE_W32_SYSTEM
740 pid = fork ();
741 if (pid == (pid_t)-1)
743 log_fatal ("fork failed: %s\n", strerror (errno) );
744 exit (1);
746 else if (pid)
747 { /* we are the parent */
748 char *infostr;
750 close (fd);
752 /* create the info string: <name>:<pid>:<protocol_version> */
753 if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
754 socket_name, (ulong) pid) < 0)
756 log_error ("out of core\n");
757 kill (pid, SIGTERM);
758 exit (1);
760 *socket_name = 0; /* don't let cleanup() remove the socket -
761 the child should do this from now on */
762 if (argc)
763 { /* run the program given on the commandline */
764 if (putenv (infostr))
766 log_error ("failed to set environment: %s\n",
767 strerror (errno) );
768 kill (pid, SIGTERM );
769 exit (1);
771 execvp (argv[0], argv);
772 log_error ("failed to run the command: %s\n", strerror (errno));
773 kill (pid, SIGTERM);
774 exit (1);
776 else
778 /* Print the environment string, so that the caller can use
779 shell's eval to set it */
780 if (csh_style)
782 *strchr (infostr, '=') = ' ';
783 printf ( "setenv %s\n", infostr);
785 else
787 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
789 xfree (infostr);
790 exit (0);
792 /* NOTREACHED */
793 } /* end parent */
795 /* This is the child. */
797 /* Detach from tty and put process into a new session. */
798 if (!nodetach )
800 /* Close stdin, stdout and stderr unless it is the log stream. */
801 for (i=0; i <= 2; i++)
803 if ( log_test_fd (i) && i != fd)
804 close (i);
806 if (setsid() == -1)
808 log_error ("setsid() failed: %s\n", strerror(errno) );
809 cleanup ();
810 exit (1);
815 struct sigaction sa;
817 sa.sa_handler = SIG_IGN;
818 sigemptyset (&sa.sa_mask);
819 sa.sa_flags = 0;
820 sigaction (SIGPIPE, &sa, NULL);
823 if (chdir("/"))
825 log_error ("chdir to / failed: %s\n", strerror (errno));
826 exit (1);
829 #endif /*!HAVE_W32_SYSTEM*/
831 handle_connections (fd);
833 close (fd);
836 return 0;
839 void
840 scd_exit (int rc)
842 #if 0
843 #warning no update_random_seed_file
844 update_random_seed_file();
845 #endif
846 #if 0
847 /* at this time a bit annoying */
848 if (opt.debug & DBG_MEMSTAT_VALUE)
850 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
851 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
853 if (opt.debug)
854 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
855 #endif
856 gcry_control (GCRYCTL_TERM_SECMEM );
857 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
858 exit (rc);
862 static void
863 scd_init_default_ctrl (ctrl_t ctrl)
865 ctrl->reader_slot = -1;
868 static void
869 scd_deinit_default_ctrl (ctrl_t ctrl)
871 (void)ctrl;
875 /* Return the name of the socket to be used to connect to this
876 process. If no socket is available, return NULL. */
877 const char *
878 scd_get_socket_name ()
880 if (socket_name && *socket_name)
881 return socket_name;
882 return NULL;
886 static void
887 handle_signal (int signo)
889 switch (signo)
891 #ifndef HAVE_W32_SYSTEM
892 case SIGHUP:
893 log_info ("SIGHUP received - "
894 "re-reading configuration and resetting cards\n");
895 /* reread_configuration (); */
896 break;
898 case SIGUSR1:
899 log_info ("SIGUSR1 received - printing internal information:\n");
900 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
901 app_dump_state ();
902 break;
904 case SIGUSR2:
905 log_info ("SIGUSR2 received - no action defined\n");
906 break;
908 case SIGTERM:
909 if (!shutdown_pending)
910 log_info ("SIGTERM received - shutting down ...\n");
911 else
912 log_info ("SIGTERM received - still %ld running threads\n",
913 pth_ctrl( PTH_CTRL_GETTHREADS ));
914 shutdown_pending++;
915 if (shutdown_pending > 2)
917 log_info ("shutdown forced\n");
918 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
919 cleanup ();
920 scd_exit (0);
922 break;
924 case SIGINT:
925 log_info ("SIGINT received - immediate shutdown\n");
926 log_info( "%s %s stopped\n", strusage(11), strusage(13));
927 cleanup ();
928 scd_exit (0);
929 break;
930 #endif /*!HAVE_W32_SYSTEM*/
932 default:
933 log_info ("signal %d received - no action defined\n", signo);
938 static void
939 handle_tick (void)
941 if (!ticker_disabled)
942 scd_update_reader_status_file ();
946 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
947 true using STANDARD_NAME in the home directory or if given has
948 false from the mkdir type name TEMPLATE. In the latter case a
949 unique name in a unique new directory will be created. In both
950 cases check for valid characters as well as against a maximum
951 allowed length for a unix domain socket is done. The function
952 terminates the process in case of an error. Retunrs: Pointer to an
953 allcoated string with the absolute name of the socket used. */
954 static char *
955 create_socket_name (int use_standard_socket,
956 char *standard_name, char *template)
958 char *name, *p;
960 if (use_standard_socket)
961 name = make_filename (opt.homedir, standard_name, NULL);
962 else
964 name = xstrdup (template);
965 p = strrchr (name, '/');
966 if (!p)
967 BUG ();
968 *p = 0;
969 if (!mkdtemp (name))
971 log_error (_("can't create directory `%s': %s\n"),
972 name, strerror (errno));
973 scd_exit (2);
975 *p = '/';
978 if (strchr (name, PATHSEP_C))
980 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
981 scd_exit (2);
983 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
985 log_error (_("name of socket too long\n"));
986 scd_exit (2);
988 return name;
993 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
994 whether a non-random socket is used. Returns the file descriptor
995 or terminates the process in case of an error. */
996 static gnupg_fd_t
997 create_server_socket (int is_standard_name, const char *name,
998 assuan_sock_nonce_t *nonce)
1000 struct sockaddr_un *serv_addr;
1001 socklen_t len;
1002 gnupg_fd_t fd;
1003 int rc;
1005 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1006 if (fd == GNUPG_INVALID_FD)
1008 log_error (_("can't create socket: %s\n"), strerror (errno));
1009 scd_exit (2);
1012 serv_addr = xmalloc (sizeof (*serv_addr));
1013 memset (serv_addr, 0, sizeof *serv_addr);
1014 serv_addr->sun_family = AF_UNIX;
1015 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
1016 strcpy (serv_addr->sun_path, name);
1017 len = (offsetof (struct sockaddr_un, sun_path)
1018 + strlen (serv_addr->sun_path) + 1);
1020 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1021 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
1023 remove (name);
1024 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1026 if (rc != -1
1027 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1028 log_error (_("error getting nonce for the socket\n"));
1029 if (rc == -1)
1031 log_error (_("error binding socket to `%s': %s\n"),
1032 serv_addr->sun_path,
1033 gpg_strerror (gpg_error_from_syserror ()));
1034 assuan_sock_close (fd);
1035 scd_exit (2);
1038 if (listen (FD2INT(fd), 5 ) == -1)
1040 log_error (_("listen() failed: %s\n"),
1041 gpg_strerror (gpg_error_from_syserror ()));
1042 assuan_sock_close (fd);
1043 scd_exit (2);
1046 if (opt.verbose)
1047 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1049 return fd;
1054 /* This is the standard connection thread's main function. */
1055 static void *
1056 start_connection_thread (void *arg)
1058 ctrl_t ctrl = arg;
1060 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1061 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1063 log_info (_("error reading nonce on fd %d: %s\n"),
1064 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1065 assuan_sock_close (ctrl->thread_startup.fd);
1066 xfree (ctrl);
1067 return NULL;
1070 scd_init_default_ctrl (ctrl);
1071 if (opt.verbose)
1072 log_info (_("handler for fd %d started\n"),
1073 FD2INT(ctrl->thread_startup.fd));
1075 /* If this is a pipe server, we request a shutdown if the command
1076 hanlder asked for it. With the next ticker event and given that
1077 no other connections are running the shutdown will then
1078 happen. */
1079 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1080 && pipe_server)
1081 shutdown_pending = 1;
1083 if (opt.verbose)
1084 log_info (_("handler for fd %d terminated\n"),
1085 FD2INT (ctrl->thread_startup.fd));
1087 scd_deinit_default_ctrl (ctrl);
1088 xfree (ctrl);
1089 return NULL;
1093 /* Connection handler loop. Wait for connection requests and spawn a
1094 thread after accepting a connection. LISTEN_FD is allowed to be -1
1095 in which case this code will only do regular timeouts and handle
1096 signals. */
1097 static void
1098 handle_connections (int listen_fd)
1100 pth_attr_t tattr;
1101 pth_event_t ev, time_ev;
1102 sigset_t sigs;
1103 int signo;
1104 struct sockaddr_un paddr;
1105 socklen_t plen;
1106 fd_set fdset, read_fdset;
1107 int ret;
1108 int fd;
1109 int nfd;
1111 tattr = pth_attr_new();
1112 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1113 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
1115 #ifndef HAVE_W32_SYSTEM /* fixme */
1116 sigemptyset (&sigs );
1117 sigaddset (&sigs, SIGHUP);
1118 sigaddset (&sigs, SIGUSR1);
1119 sigaddset (&sigs, SIGUSR2);
1120 sigaddset (&sigs, SIGINT);
1121 sigaddset (&sigs, SIGTERM);
1122 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1123 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1124 #else
1125 sigs = 0;
1126 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1127 #endif
1128 time_ev = NULL;
1130 FD_ZERO (&fdset);
1131 nfd = 0;
1132 if (listen_fd != -1)
1134 FD_SET (listen_fd, &fdset);
1135 nfd = listen_fd;
1138 for (;;)
1140 sigset_t oldsigs;
1142 if (shutdown_pending)
1144 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1145 break; /* ready */
1147 /* Do not accept anymore connections but wait for existing
1148 connections to terminate. We do this by clearing out all
1149 file descriptors to wait for, so that the select will be
1150 used to just wait on a signal or timeout event. */
1151 FD_ZERO (&fdset);
1152 listen_fd = -1;
1155 /* Create a timeout event if needed. Round it up to the next
1156 microsecond interval to help with power saving. */
1157 if (!time_ev)
1159 pth_time_t nexttick = pth_timeout (TIMERTICK_INTERVAL_SEC,
1160 TIMERTICK_INTERVAL_USEC/2);
1161 if ((nexttick.tv_usec % (TIMERTICK_INTERVAL_USEC/2)) > 10)
1163 nexttick.tv_usec = ((nexttick.tv_usec
1164 /(TIMERTICK_INTERVAL_USEC/2))
1165 + 1) * (TIMERTICK_INTERVAL_USEC/2);
1166 if (nexttick.tv_usec >= 1000000)
1168 nexttick.tv_sec++;
1169 nexttick.tv_usec = 0;
1172 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1175 /* POSIX says that fd_set should be implemented as a structure,
1176 thus a simple assignment is fine to copy the entire set. */
1177 read_fdset = fdset;
1179 if (time_ev)
1180 pth_event_concat (ev, time_ev, NULL);
1181 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1182 if (time_ev)
1183 pth_event_isolate (time_ev);
1185 if (ret == -1)
1187 if (pth_event_occurred (ev)
1188 || (time_ev && pth_event_occurred (time_ev)))
1190 if (pth_event_occurred (ev))
1191 handle_signal (signo);
1192 if (time_ev && pth_event_occurred (time_ev))
1194 pth_event_free (time_ev, PTH_FREE_ALL);
1195 time_ev = NULL;
1196 handle_tick ();
1198 continue;
1200 log_error (_("pth_select failed: %s - waiting 1s\n"),
1201 strerror (errno));
1202 pth_sleep (1);
1203 continue;
1206 if (pth_event_occurred (ev))
1208 handle_signal (signo);
1211 if (time_ev && pth_event_occurred (time_ev))
1213 pth_event_free (time_ev, PTH_FREE_ALL);
1214 time_ev = NULL;
1215 handle_tick ();
1218 /* We now might create new threads and because we don't want any
1219 signals - we are handling here - to be delivered to a new
1220 thread. Thus we need to block those signals. */
1221 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1223 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1225 ctrl_t ctrl;
1227 plen = sizeof paddr;
1228 fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1229 if (fd == -1)
1231 log_error ("accept failed: %s\n", strerror (errno));
1233 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1235 log_error ("error allocating connection control data: %s\n",
1236 strerror (errno) );
1237 close (fd);
1239 else
1241 char threadname[50];
1243 snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd);
1244 threadname[sizeof threadname -1] = 0;
1245 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1246 ctrl->thread_startup.fd = INT2FD (fd);
1247 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1249 log_error ("error spawning connection handler: %s\n",
1250 strerror (errno) );
1251 xfree (ctrl);
1252 close (fd);
1255 fd = -1;
1258 /* Restore the signal mask. */
1259 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1263 pth_event_free (ev, PTH_FREE_ALL);
1264 if (time_ev)
1265 pth_event_free (time_ev, PTH_FREE_ALL);
1266 cleanup ();
1267 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));