app-openpgp changes
[gnupg.git] / scd / scdaemon.c
blob49f09cf62da60dcb82c5210cab764a733dd90fdd
1 /* scdaemon.c - The GnuPG Smartcard Daemon
2 * Copyright (C) 2001, 2002, 2004, 2005,
3 * 2007, 2008, 2009 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 #define JNLIB_NEED_AFLOCAL
42 #include "scdaemon.h"
43 #include <ksba.h>
44 #include <gcrypt.h>
46 #include <assuan.h> /* malloc hooks */
48 #include "i18n.h"
49 #include "sysutils.h"
50 #include "app-common.h"
51 #include "ccid-driver.h"
52 #include "mkdtemp.h"
53 #include "gc-opt-flags.h"
56 enum cmd_and_opt_values
57 { aNull = 0,
58 oCsh = 'c',
59 oQuiet = 'q',
60 oSh = 's',
61 oVerbose = 'v',
63 oNoVerbose = 500,
64 aGPGConfList,
65 aGPGConfTest,
66 oOptions,
67 oDebug,
68 oDebugAll,
69 oDebugLevel,
70 oDebugWait,
71 oDebugAllowCoreDump,
72 oDebugCCIDDriver,
73 oDebugLogTid,
74 oNoGreeting,
75 oNoOptions,
76 oHomedir,
77 oNoDetach,
78 oNoGrab,
79 oLogFile,
80 oServer,
81 oMultiServer,
82 oDaemon,
83 oBatch,
84 oReaderPort,
85 oCardTimeout,
86 octapiDriver,
87 opcscDriver,
88 oDisableCCID,
89 oDisableOpenSC,
90 oDisableKeypad,
91 oAllowAdmin,
92 oDenyAdmin,
93 oDisableApplication,
94 oDebugDisableTicker
99 static ARGPARSE_OPTS opts[] = {
100 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
101 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
103 ARGPARSE_group (301, N_("@Options:\n ")),
105 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
106 ARGPARSE_s_n (oMultiServer, "multi-server",
107 N_("run in multi server mode (foreground)")),
108 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
109 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
110 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
111 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
112 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
113 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
114 ARGPARSE_p_u (oDebug, "debug", "@"),
115 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
116 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
117 N_("|LEVEL|set the debugging level to LEVEL")),
118 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
119 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
120 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
121 ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
122 ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
123 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
124 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
125 ARGPARSE_s_s (oReaderPort, "reader-port",
126 N_("|N|connect to reader at port N")),
127 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
128 N_("|NAME|use NAME as ct-API driver")),
129 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
130 N_("|NAME|use NAME as PC/SC driver")),
131 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
132 #ifdef HAVE_LIBUSB
133 N_("do not use the internal CCID driver")
134 #else
136 #endif
137 /* end --disable-ccid */),
138 ARGPARSE_s_u (oCardTimeout, "card-timeout",
139 N_("|N|disconnect the card after N seconds of inactivity")),
140 ARGPARSE_s_n (oDisableKeypad, "disable-keypad",
141 N_("do not use a reader's keypad")),
142 ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
143 ARGPARSE_s_n (oDenyAdmin, "deny-admin",
144 N_("deny the use of admin card commands")),
145 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
147 ARGPARSE_end ()
151 /* The card driver we use by default for PC/SC. */
152 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
153 #define DEFAULT_PCSC_DRIVER "winscard.dll"
154 #elif defined(__APPLE__)
155 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
156 #elif defined(__GLIBC__)
157 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
158 #else
159 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
160 #endif
162 /* The timer tick used for housekeeping stuff. We poll every 500ms to
163 let the user immediately know a status change.
165 This is not too good for power saving but given that there is no
166 easy way to block on card status changes it is the best we can do.
167 For PC/SC we could in theory use an extra thread to wait for status
168 changes but that requires a native thread because there is no way
169 to make the underlying PC/SC card change function block using a Pth
170 mechanism. Given that a native thread could only be used under W32
171 we don't do that at all. */
172 #define TIMERTICK_INTERVAL_SEC (0)
173 #define TIMERTICK_INTERVAL_USEC (500000)
175 /* Flag to indicate that a shutdown was requested. */
176 static int shutdown_pending;
178 /* It is possible that we are currently running under setuid permissions */
179 static int maybe_setuid = 1;
181 /* Flag telling whether we are running as a pipe server. */
182 static int pipe_server;
184 /* Name of the communication socket */
185 static char *socket_name;
187 /* We need to keep track of the server's nonces (these are dummies for
188 POSIX systems). */
189 static assuan_sock_nonce_t socket_nonce;
191 /* Debug flag to disable the ticker. The ticker is in fact not
192 disabled but it won't perform any ticker specific actions. */
193 static int ticker_disabled;
197 static char *create_socket_name (int use_standard_socket,
198 char *standard_name, char *template);
199 static gnupg_fd_t create_server_socket (int is_standard_name, const char *name,
200 assuan_sock_nonce_t *nonce);
202 static void *start_connection_thread (void *arg);
203 static void handle_connections (int listen_fd);
205 /* Pth wrapper function definitions. */
206 GCRY_THREAD_OPTION_PTH_IMPL;
207 static int fixed_gcry_pth_init (void)
209 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
214 static char *
215 make_libversion (const char *libname, const char *(*getfnc)(const char*))
217 const char *s;
218 char *result;
220 if (maybe_setuid)
222 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
223 maybe_setuid = 0;
225 s = getfnc (NULL);
226 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
227 strcpy (stpcpy (stpcpy (result, libname), " "), s);
228 return result;
232 static const char *
233 my_strusage (int level)
235 static char *ver_gcry, *ver_ksba;
236 const char *p;
238 switch (level)
240 case 11: p = "scdaemon (GnuPG)";
241 break;
242 case 13: p = VERSION; break;
243 case 17: p = PRINTABLE_OS_NAME; break;
244 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
245 break;
246 case 20:
247 if (!ver_gcry)
248 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
249 p = ver_gcry;
250 break;
251 case 21:
252 if (!ver_ksba)
253 ver_ksba = make_libversion ("libksba", ksba_check_version);
254 p = ver_ksba;
255 break;
256 case 1:
257 case 40: p = _("Usage: scdaemon [options] (-h for help)");
258 break;
259 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
260 "Smartcard daemon for GnuPG\n");
261 break;
263 default: p = NULL;
265 return p;
269 static unsigned long
270 tid_log_callback (void)
272 #ifdef PTH_HAVE_PTH_THREAD_ID
273 return pth_thread_id ();
274 #else
275 return (unsigned long)pth_self ();
276 #endif
283 /* Setup the debugging. With a LEVEL of NULL only the active debug
284 flags are propagated to the subsystems. With LEVEL set, a specific
285 set of debug flags is set; thus overriding all flags already
286 set. */
287 static void
288 set_debug (const char *level)
290 if (!level)
292 else if (!strcmp (level, "none"))
293 opt.debug = 0;
294 else if (!strcmp (level, "basic"))
295 opt.debug = DBG_ASSUAN_VALUE;
296 else if (!strcmp (level, "advanced"))
297 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
298 else if (!strcmp (level, "expert"))
299 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
300 |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
301 else if (!strcmp (level, "guru"))
302 opt.debug = ~0;
303 else
305 log_error (_("invalid debug-level `%s' given\n"), level);
306 scd_exit(2);
310 if (opt.debug && !opt.verbose)
311 opt.verbose = 1;
312 if (opt.debug && opt.quiet)
313 opt.quiet = 0;
315 if (opt.debug & DBG_MPI_VALUE)
316 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
317 if (opt.debug & DBG_CRYPTO_VALUE )
318 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
319 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
324 static void
325 cleanup (void)
327 if (socket_name && *socket_name)
329 char *p;
331 remove (socket_name);
332 p = strrchr (socket_name, '/');
333 if (p)
335 *p = 0;
336 rmdir (socket_name);
337 *p = '/';
339 *socket_name = 0;
346 main (int argc, char **argv )
348 ARGPARSE_ARGS pargs;
349 int orig_argc;
350 gpg_error_t err;
351 int may_coredump;
352 char **orig_argv;
353 FILE *configfp = NULL;
354 char *configname = NULL;
355 const char *shell;
356 unsigned int configlineno;
357 int parse_debug = 0;
358 const char *debug_level = NULL;
359 int default_config =1;
360 int greeting = 0;
361 int nogreeting = 0;
362 int multi_server = 0;
363 int is_daemon = 0;
364 int nodetach = 0;
365 int csh_style = 0;
366 char *logfile = NULL;
367 int debug_wait = 0;
368 int gpgconf_list = 0;
369 const char *config_filename = NULL;
370 int allow_coredump = 0;
371 int standard_socket = 0;
373 set_strusage (my_strusage);
374 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
375 /* Please note that we may running SUID(ROOT), so be very CAREFUL
376 when adding any stuff between here and the call to INIT_SECMEM()
377 somewhere after the option parsing */
378 log_set_prefix ("scdaemon", 1|4);
380 /* Make sure that our subsystems are ready. */
381 i18n_init ();
382 init_common_subsystems ();
385 /* Libgcrypt requires us to register the threading model first.
386 Note that this will also do the pth_init. */
387 gcry_threads_pth.init = fixed_gcry_pth_init;
388 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
389 if (err)
391 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
392 gpg_strerror (err));
395 /* Check that the libraries are suitable. Do it here because
396 the option parsing may need services of the library */
397 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
399 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
400 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
403 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
405 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
406 assuan_set_assuan_log_stream (log_get_stream ());
407 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
408 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
410 setup_libgcrypt_logging ();
411 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
413 may_coredump = disable_core_dumps ();
415 /* Set default options. */
416 opt.allow_admin = 1;
417 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
419 #ifdef HAVE_W32_SYSTEM
420 standard_socket = 1; /* Under Windows we always use a standard
421 socket. */
422 #endif
425 shell = getenv ("SHELL");
426 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
427 csh_style = 1;
429 opt.homedir = default_homedir ();
431 /* Check whether we have a config file on the commandline */
432 orig_argc = argc;
433 orig_argv = argv;
434 pargs.argc = &argc;
435 pargs.argv = &argv;
436 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
437 while (arg_parse( &pargs, opts))
439 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
440 parse_debug++;
441 else if (pargs.r_opt == oOptions)
442 { /* yes there is one, so we do not try the default one, but
443 read the option file when it is encountered at the
444 commandline */
445 default_config = 0;
447 else if (pargs.r_opt == oNoOptions)
448 default_config = 0; /* --no-options */
449 else if (pargs.r_opt == oHomedir)
450 opt.homedir = pargs.r.ret_str;
453 /* initialize the secure memory. */
454 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
455 maybe_setuid = 0;
458 Now we are working under our real uid
462 if (default_config)
463 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
466 argc = orig_argc;
467 argv = orig_argv;
468 pargs.argc = &argc;
469 pargs.argv = &argv;
470 pargs.flags= 1; /* do not remove the args */
471 next_pass:
472 if (configname)
474 configlineno = 0;
475 configfp = fopen (configname, "r");
476 if (!configfp)
478 if (default_config)
480 if( parse_debug )
481 log_info (_("NOTE: no default option file `%s'\n"),
482 configname );
484 else
486 log_error (_("option file `%s': %s\n"),
487 configname, strerror(errno) );
488 exit(2);
490 xfree (configname);
491 configname = NULL;
493 if (parse_debug && configname )
494 log_info (_("reading options from `%s'\n"), configname );
495 default_config = 0;
498 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
500 switch (pargs.r_opt)
502 case aGPGConfList: gpgconf_list = 1; break;
503 case aGPGConfTest: gpgconf_list = 2; break;
504 case oQuiet: opt.quiet = 1; break;
505 case oVerbose: opt.verbose++; break;
506 case oBatch: opt.batch=1; break;
508 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
509 case oDebugAll: opt.debug = ~0; break;
510 case oDebugLevel: debug_level = pargs.r.ret_str; break;
511 case oDebugWait: debug_wait = pargs.r.ret_int; break;
512 case oDebugAllowCoreDump:
513 enable_core_dumps ();
514 allow_coredump = 1;
515 break;
516 case oDebugCCIDDriver:
517 #ifdef HAVE_LIBUSB
518 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
519 #endif /*HAVE_LIBUSB*/
520 break;
521 case oDebugDisableTicker: ticker_disabled = 1; break;
522 case oDebugLogTid:
523 log_set_get_tid_callback (tid_log_callback);
524 break;
526 case oOptions:
527 /* config files may not be nested (silently ignore them) */
528 if (!configfp)
530 xfree(configname);
531 configname = xstrdup(pargs.r.ret_str);
532 goto next_pass;
534 break;
535 case oNoGreeting: nogreeting = 1; break;
536 case oNoVerbose: opt.verbose = 0; break;
537 case oNoOptions: break; /* no-options */
538 case oHomedir: opt.homedir = pargs.r.ret_str; break;
539 case oNoDetach: nodetach = 1; break;
540 case oLogFile: logfile = pargs.r.ret_str; break;
541 case oCsh: csh_style = 1; break;
542 case oSh: csh_style = 0; break;
543 case oServer: pipe_server = 1; break;
544 case oMultiServer: pipe_server = 1; multi_server = 1; break;
545 case oDaemon: is_daemon = 1; break;
547 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
548 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
549 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
550 case oDisableCCID: opt.disable_ccid = 1; break;
551 case oDisableOpenSC: break;
553 case oDisableKeypad: opt.disable_keypad = 1; break;
555 case oAllowAdmin: /* Dummy because allow is now the default. */
556 break;
557 case oDenyAdmin: opt.allow_admin = 0; break;
559 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
561 case oDisableApplication:
562 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
563 break;
565 default:
566 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
567 break;
570 if (configfp)
572 fclose( configfp );
573 configfp = NULL;
574 /* Keep a copy of the config name for use by --gpgconf-list. */
575 config_filename = configname;
576 configname = NULL;
577 goto next_pass;
579 xfree (configname);
580 configname = NULL;
581 if (log_get_errorcount(0))
582 exit(2);
583 if (nogreeting )
584 greeting = 0;
586 if (greeting)
588 fprintf (stderr, "%s %s; %s\n",
589 strusage(11), strusage(13), strusage(14) );
590 fprintf (stderr, "%s\n", strusage(15) );
592 #ifdef IS_DEVELOPMENT_VERSION
593 log_info ("NOTE: this is a development version!\n");
594 #endif
597 if (atexit (cleanup))
599 log_error ("atexit failed\n");
600 cleanup ();
601 exit (1);
604 set_debug (debug_level);
606 initialize_module_command ();
608 if (gpgconf_list == 2)
609 scd_exit (0);
610 if (gpgconf_list)
612 /* List options and default values in the GPG Conf format. */
613 char *filename = NULL;
614 char *filename_esc;
616 if (config_filename)
617 filename = xstrdup (config_filename);
618 else
619 filename = make_filename (opt.homedir, "scdaemon.conf", NULL);
620 filename_esc = percent_escape (filename, NULL);
622 printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
623 GC_OPT_FLAG_DEFAULT, filename_esc);
624 xfree (filename_esc);
625 xfree (filename);
627 printf ("verbose:%lu:\n"
628 "quiet:%lu:\n"
629 "debug-level:%lu:\"none:\n"
630 "log-file:%lu:\n",
631 GC_OPT_FLAG_NONE,
632 GC_OPT_FLAG_NONE,
633 GC_OPT_FLAG_DEFAULT,
634 GC_OPT_FLAG_NONE );
636 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
637 printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
638 printf ("pcsc-driver:%lu:\"%s:\n",
639 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
640 #ifdef HAVE_LIBUSB
641 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
642 #endif
643 printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
644 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
645 printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
647 scd_exit (0);
650 /* Now start with logging to a file if this is desired. */
651 if (logfile)
653 log_set_file (logfile);
654 log_set_prefix (NULL, 1|2|4);
657 if (debug_wait && pipe_server)
659 log_debug ("waiting for debugger - my pid is %u .....\n",
660 (unsigned int)getpid());
661 gnupg_sleep (debug_wait);
662 log_debug ("... okay\n");
665 if (pipe_server)
667 /* This is the simple pipe based server */
668 ctrl_t ctrl;
669 pth_attr_t tattr;
670 int fd = -1;
672 #ifndef HAVE_W32_SYSTEM
674 struct sigaction sa;
676 sa.sa_handler = SIG_IGN;
677 sigemptyset (&sa.sa_mask);
678 sa.sa_flags = 0;
679 sigaction (SIGPIPE, &sa, NULL);
681 #endif
683 /* If --debug-allow-core-dump has been given we also need to
684 switch the working directory to a place where we can actually
685 write. */
686 if (allow_coredump)
688 if (chdir("/tmp"))
689 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
690 else
691 log_debug ("changed working directory to `/tmp'\n");
694 /* In multi server mode we need to listen on an additional
695 socket. Create that socket now before starting the handler
696 for the pipe connection. This allows that handler to send
697 back the name of that socket. */
698 if (multi_server)
700 socket_name = create_socket_name (standard_socket,
701 "S.scdaemon",
702 "/tmp/gpg-XXXXXX/S.scdaemon");
704 fd = FD2INT(create_server_socket (standard_socket,
705 socket_name, &socket_nonce));
708 tattr = pth_attr_new();
709 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
710 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
711 pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
713 ctrl = xtrycalloc (1, sizeof *ctrl);
714 if ( !ctrl )
716 log_error ("error allocating connection control data: %s\n",
717 strerror (errno) );
718 scd_exit (2);
720 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
721 if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
723 log_error ("error spawning pipe connection handler: %s\n",
724 strerror (errno) );
725 xfree (ctrl);
726 scd_exit (2);
729 /* We run handle_connection to wait for the shutdown signal and
730 to run the ticker stuff. */
731 handle_connections (fd);
732 if (fd != -1)
733 close (fd);
735 else if (!is_daemon)
737 log_info (_("please use the option `--daemon'"
738 " to run the program in the background\n"));
740 else
741 { /* Regular server mode */
742 int fd;
743 #ifndef HAVE_W32_SYSTEM
744 pid_t pid;
745 int i;
746 #endif
748 /* Create the socket. */
749 socket_name = create_socket_name (standard_socket,
750 "S.scdaemon",
751 "/tmp/gpg-XXXXXX/S.scdaemon");
753 fd = FD2INT (create_server_socket (standard_socket,
754 socket_name, &socket_nonce));
757 fflush (NULL);
758 #ifndef HAVE_W32_SYSTEM
759 pid = fork ();
760 if (pid == (pid_t)-1)
762 log_fatal ("fork failed: %s\n", strerror (errno) );
763 exit (1);
765 else if (pid)
766 { /* we are the parent */
767 char *infostr;
769 close (fd);
771 /* create the info string: <name>:<pid>:<protocol_version> */
772 if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
773 socket_name, (ulong) pid) < 0)
775 log_error ("out of core\n");
776 kill (pid, SIGTERM);
777 exit (1);
779 *socket_name = 0; /* don't let cleanup() remove the socket -
780 the child should do this from now on */
781 if (argc)
782 { /* run the program given on the commandline */
783 if (putenv (infostr))
785 log_error ("failed to set environment: %s\n",
786 strerror (errno) );
787 kill (pid, SIGTERM );
788 exit (1);
790 execvp (argv[0], argv);
791 log_error ("failed to run the command: %s\n", strerror (errno));
792 kill (pid, SIGTERM);
793 exit (1);
795 else
797 /* Print the environment string, so that the caller can use
798 shell's eval to set it */
799 if (csh_style)
801 *strchr (infostr, '=') = ' ';
802 printf ( "setenv %s\n", infostr);
804 else
806 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
808 xfree (infostr);
809 exit (0);
811 /* NOTREACHED */
812 } /* end parent */
814 /* This is the child. */
816 /* Detach from tty and put process into a new session. */
817 if (!nodetach )
819 /* Close stdin, stdout and stderr unless it is the log stream. */
820 for (i=0; i <= 2; i++)
822 if ( log_test_fd (i) && i != fd)
823 close (i);
825 if (setsid() == -1)
827 log_error ("setsid() failed: %s\n", strerror(errno) );
828 cleanup ();
829 exit (1);
834 struct sigaction sa;
836 sa.sa_handler = SIG_IGN;
837 sigemptyset (&sa.sa_mask);
838 sa.sa_flags = 0;
839 sigaction (SIGPIPE, &sa, NULL);
842 if (chdir("/"))
844 log_error ("chdir to / failed: %s\n", strerror (errno));
845 exit (1);
848 #endif /*!HAVE_W32_SYSTEM*/
850 handle_connections (fd);
852 close (fd);
855 return 0;
858 void
859 scd_exit (int rc)
861 #if 0
862 #warning no update_random_seed_file
863 update_random_seed_file();
864 #endif
865 #if 0
866 /* at this time a bit annoying */
867 if (opt.debug & DBG_MEMSTAT_VALUE)
869 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
870 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
872 if (opt.debug)
873 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
874 #endif
875 gcry_control (GCRYCTL_TERM_SECMEM );
876 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
877 exit (rc);
881 static void
882 scd_init_default_ctrl (ctrl_t ctrl)
884 ctrl->reader_slot = -1;
887 static void
888 scd_deinit_default_ctrl (ctrl_t ctrl)
890 (void)ctrl;
894 /* Return the name of the socket to be used to connect to this
895 process. If no socket is available, return NULL. */
896 const char *
897 scd_get_socket_name ()
899 if (socket_name && *socket_name)
900 return socket_name;
901 return NULL;
905 static void
906 handle_signal (int signo)
908 switch (signo)
910 #ifndef HAVE_W32_SYSTEM
911 case SIGHUP:
912 log_info ("SIGHUP received - "
913 "re-reading configuration and resetting cards\n");
914 /* reread_configuration (); */
915 break;
917 case SIGUSR1:
918 log_info ("SIGUSR1 received - printing internal information:\n");
919 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
920 app_dump_state ();
921 break;
923 case SIGUSR2:
924 log_info ("SIGUSR2 received - no action defined\n");
925 break;
927 case SIGTERM:
928 if (!shutdown_pending)
929 log_info ("SIGTERM received - shutting down ...\n");
930 else
931 log_info ("SIGTERM received - still %ld running threads\n",
932 pth_ctrl( PTH_CTRL_GETTHREADS ));
933 shutdown_pending++;
934 if (shutdown_pending > 2)
936 log_info ("shutdown forced\n");
937 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
938 cleanup ();
939 scd_exit (0);
941 break;
943 case SIGINT:
944 log_info ("SIGINT received - immediate shutdown\n");
945 log_info( "%s %s stopped\n", strusage(11), strusage(13));
946 cleanup ();
947 scd_exit (0);
948 break;
949 #endif /*!HAVE_W32_SYSTEM*/
951 default:
952 log_info ("signal %d received - no action defined\n", signo);
957 static void
958 handle_tick (void)
960 if (!ticker_disabled)
961 scd_update_reader_status_file ();
965 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
966 true using STANDARD_NAME in the home directory or if given has
967 false from the mkdir type name TEMPLATE. In the latter case a
968 unique name in a unique new directory will be created. In both
969 cases check for valid characters as well as against a maximum
970 allowed length for a unix domain socket is done. The function
971 terminates the process in case of an error. Retunrs: Pointer to an
972 allcoated string with the absolute name of the socket used. */
973 static char *
974 create_socket_name (int use_standard_socket,
975 char *standard_name, char *template)
977 char *name, *p;
979 if (use_standard_socket)
980 name = make_filename (opt.homedir, standard_name, NULL);
981 else
983 name = xstrdup (template);
984 p = strrchr (name, '/');
985 if (!p)
986 BUG ();
987 *p = 0;
988 if (!mkdtemp (name))
990 log_error (_("can't create directory `%s': %s\n"),
991 name, strerror (errno));
992 scd_exit (2);
994 *p = '/';
997 if (strchr (name, PATHSEP_C))
999 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1000 scd_exit (2);
1002 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1004 log_error (_("name of socket too long\n"));
1005 scd_exit (2);
1007 return name;
1012 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1013 whether a non-random socket is used. Returns the file descriptor
1014 or terminates the process in case of an error. */
1015 static gnupg_fd_t
1016 create_server_socket (int is_standard_name, const char *name,
1017 assuan_sock_nonce_t *nonce)
1019 struct sockaddr_un *serv_addr;
1020 socklen_t len;
1021 gnupg_fd_t fd;
1022 int rc;
1024 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1025 if (fd == GNUPG_INVALID_FD)
1027 log_error (_("can't create socket: %s\n"), strerror (errno));
1028 scd_exit (2);
1031 serv_addr = xmalloc (sizeof (*serv_addr));
1032 memset (serv_addr, 0, sizeof *serv_addr);
1033 serv_addr->sun_family = AF_UNIX;
1034 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
1035 strcpy (serv_addr->sun_path, name);
1036 len = SUN_LEN (serv_addr);
1038 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1039 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
1041 remove (name);
1042 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1044 if (rc != -1
1045 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1046 log_error (_("error getting nonce for the socket\n"));
1047 if (rc == -1)
1049 log_error (_("error binding socket to `%s': %s\n"),
1050 serv_addr->sun_path,
1051 gpg_strerror (gpg_error_from_syserror ()));
1052 assuan_sock_close (fd);
1053 scd_exit (2);
1056 if (listen (FD2INT(fd), 5 ) == -1)
1058 log_error (_("listen() failed: %s\n"),
1059 gpg_strerror (gpg_error_from_syserror ()));
1060 assuan_sock_close (fd);
1061 scd_exit (2);
1064 if (opt.verbose)
1065 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1067 return fd;
1072 /* This is the standard connection thread's main function. */
1073 static void *
1074 start_connection_thread (void *arg)
1076 ctrl_t ctrl = arg;
1078 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1079 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1081 log_info (_("error reading nonce on fd %d: %s\n"),
1082 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1083 assuan_sock_close (ctrl->thread_startup.fd);
1084 xfree (ctrl);
1085 return NULL;
1088 scd_init_default_ctrl (ctrl);
1089 if (opt.verbose)
1090 log_info (_("handler for fd %d started\n"),
1091 FD2INT(ctrl->thread_startup.fd));
1093 /* If this is a pipe server, we request a shutdown if the command
1094 handler asked for it. With the next ticker event and given that
1095 no other connections are running the shutdown will then
1096 happen. */
1097 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1098 && pipe_server)
1099 shutdown_pending = 1;
1101 if (opt.verbose)
1102 log_info (_("handler for fd %d terminated\n"),
1103 FD2INT (ctrl->thread_startup.fd));
1105 scd_deinit_default_ctrl (ctrl);
1106 xfree (ctrl);
1107 return NULL;
1111 /* Connection handler loop. Wait for connection requests and spawn a
1112 thread after accepting a connection. LISTEN_FD is allowed to be -1
1113 in which case this code will only do regular timeouts and handle
1114 signals. */
1115 static void
1116 handle_connections (int listen_fd)
1118 pth_attr_t tattr;
1119 pth_event_t ev, time_ev;
1120 sigset_t sigs;
1121 int signo;
1122 struct sockaddr_un paddr;
1123 socklen_t plen;
1124 fd_set fdset, read_fdset;
1125 int ret;
1126 int fd;
1127 int nfd;
1129 tattr = pth_attr_new();
1130 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1131 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
1133 #ifndef HAVE_W32_SYSTEM /* fixme */
1134 sigemptyset (&sigs );
1135 sigaddset (&sigs, SIGHUP);
1136 sigaddset (&sigs, SIGUSR1);
1137 sigaddset (&sigs, SIGUSR2);
1138 sigaddset (&sigs, SIGINT);
1139 sigaddset (&sigs, SIGTERM);
1140 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1141 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1142 #else
1143 sigs = 0;
1144 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1145 #endif
1146 time_ev = NULL;
1148 FD_ZERO (&fdset);
1149 nfd = 0;
1150 if (listen_fd != -1)
1152 FD_SET (listen_fd, &fdset);
1153 nfd = listen_fd;
1156 for (;;)
1158 sigset_t oldsigs;
1160 if (shutdown_pending)
1162 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1163 break; /* ready */
1165 /* Do not accept anymore connections but wait for existing
1166 connections to terminate. We do this by clearing out all
1167 file descriptors to wait for, so that the select will be
1168 used to just wait on a signal or timeout event. */
1169 FD_ZERO (&fdset);
1170 listen_fd = -1;
1173 /* Create a timeout event if needed. Round it up to the next
1174 microsecond interval to help with power saving. */
1175 if (!time_ev)
1177 pth_time_t nexttick = pth_timeout (TIMERTICK_INTERVAL_SEC,
1178 TIMERTICK_INTERVAL_USEC/2);
1179 if ((nexttick.tv_usec % (TIMERTICK_INTERVAL_USEC/2)) > 10)
1181 nexttick.tv_usec = ((nexttick.tv_usec
1182 /(TIMERTICK_INTERVAL_USEC/2))
1183 + 1) * (TIMERTICK_INTERVAL_USEC/2);
1184 if (nexttick.tv_usec >= 1000000)
1186 nexttick.tv_sec++;
1187 nexttick.tv_usec = 0;
1190 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1193 /* POSIX says that fd_set should be implemented as a structure,
1194 thus a simple assignment is fine to copy the entire set. */
1195 read_fdset = fdset;
1197 if (time_ev)
1198 pth_event_concat (ev, time_ev, NULL);
1199 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1200 if (time_ev)
1201 pth_event_isolate (time_ev);
1203 if (ret == -1)
1205 if (pth_event_occurred (ev)
1206 || (time_ev && pth_event_occurred (time_ev)))
1208 if (pth_event_occurred (ev))
1209 handle_signal (signo);
1210 if (time_ev && pth_event_occurred (time_ev))
1212 pth_event_free (time_ev, PTH_FREE_ALL);
1213 time_ev = NULL;
1214 handle_tick ();
1216 continue;
1218 log_error (_("pth_select failed: %s - waiting 1s\n"),
1219 strerror (errno));
1220 pth_sleep (1);
1221 continue;
1224 if (pth_event_occurred (ev))
1226 handle_signal (signo);
1229 if (time_ev && pth_event_occurred (time_ev))
1231 pth_event_free (time_ev, PTH_FREE_ALL);
1232 time_ev = NULL;
1233 handle_tick ();
1236 /* We now might create new threads and because we don't want any
1237 signals - we are handling here - to be delivered to a new
1238 thread. Thus we need to block those signals. */
1239 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1241 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1243 ctrl_t ctrl;
1245 plen = sizeof paddr;
1246 fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1247 if (fd == -1)
1249 log_error ("accept failed: %s\n", strerror (errno));
1251 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1253 log_error ("error allocating connection control data: %s\n",
1254 strerror (errno) );
1255 close (fd);
1257 else
1259 char threadname[50];
1261 snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd);
1262 threadname[sizeof threadname -1] = 0;
1263 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1264 ctrl->thread_startup.fd = INT2FD (fd);
1265 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1267 log_error ("error spawning connection handler: %s\n",
1268 strerror (errno) );
1269 xfree (ctrl);
1270 close (fd);
1273 fd = -1;
1276 /* Restore the signal mask. */
1277 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1281 pth_event_free (ev, PTH_FREE_ALL);
1282 if (time_ev)
1283 pth_event_free (time_ev, PTH_FREE_ALL);
1284 cleanup ();
1285 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));