po/
[gnupg.git] / scd / scdaemon.c
blob8e353189f404c6823d640349ed636c91617ff989
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 "apdu.h"
52 #include "ccid-driver.h"
53 #include "mkdtemp.h"
54 #include "gc-opt-flags.h"
57 enum cmd_and_opt_values
58 { aNull = 0,
59 oCsh = 'c',
60 oQuiet = 'q',
61 oSh = 's',
62 oVerbose = 'v',
64 oNoVerbose = 500,
65 aGPGConfList,
66 aGPGConfTest,
67 oOptions,
68 oDebug,
69 oDebugAll,
70 oDebugLevel,
71 oDebugWait,
72 oDebugAllowCoreDump,
73 oDebugCCIDDriver,
74 oDebugLogTid,
75 oNoGreeting,
76 oNoOptions,
77 oHomedir,
78 oNoDetach,
79 oNoGrab,
80 oLogFile,
81 oServer,
82 oMultiServer,
83 oDaemon,
84 oBatch,
85 oReaderPort,
86 oCardTimeout,
87 octapiDriver,
88 opcscDriver,
89 oDisableCCID,
90 oDisableOpenSC,
91 oDisableKeypad,
92 oAllowAdmin,
93 oDenyAdmin,
94 oDisableApplication,
95 oDebugDisableTicker
100 static ARGPARSE_OPTS opts[] = {
101 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
102 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
104 ARGPARSE_group (301, N_("@Options:\n ")),
106 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
107 ARGPARSE_s_n (oMultiServer, "multi-server",
108 N_("run in multi server mode (foreground)")),
109 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
110 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
111 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
112 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
113 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
114 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
115 ARGPARSE_p_u (oDebug, "debug", "@"),
116 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
117 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
118 N_("|LEVEL|set the debugging level to LEVEL")),
119 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
120 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
121 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
122 ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
123 ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
124 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
125 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
126 ARGPARSE_s_s (oReaderPort, "reader-port",
127 N_("|N|connect to reader at port N")),
128 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
129 N_("|NAME|use NAME as ct-API driver")),
130 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
131 N_("|NAME|use NAME as PC/SC driver")),
132 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
133 #ifdef HAVE_LIBUSB
134 N_("do not use the internal CCID driver")
135 #else
137 #endif
138 /* end --disable-ccid */),
139 ARGPARSE_s_u (oCardTimeout, "card-timeout",
140 N_("|N|disconnect the card after N seconds of inactivity")),
141 ARGPARSE_s_n (oDisableKeypad, "disable-keypad",
142 N_("do not use a reader's keypad")),
143 ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
144 ARGPARSE_s_n (oDenyAdmin, "deny-admin",
145 N_("deny the use of admin card commands")),
146 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
148 ARGPARSE_end ()
152 /* The card driver we use by default for PC/SC. */
153 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
154 #define DEFAULT_PCSC_DRIVER "winscard.dll"
155 #elif defined(__APPLE__)
156 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
157 #elif defined(__GLIBC__)
158 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
159 #else
160 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
161 #endif
163 /* The timer tick used for housekeeping stuff. We poll every 500ms to
164 let the user immediately know a status change.
166 This is not too good for power saving but given that there is no
167 easy way to block on card status changes it is the best we can do.
168 For PC/SC we could in theory use an extra thread to wait for status
169 changes but that requires a native thread because there is no way
170 to make the underlying PC/SC card change function block using a Pth
171 mechanism. Given that a native thread could only be used under W32
172 we don't do that at all. */
173 #define TIMERTICK_INTERVAL_SEC (0)
174 #define TIMERTICK_INTERVAL_USEC (500000)
176 /* Flag to indicate that a shutdown was requested. */
177 static int shutdown_pending;
179 /* It is possible that we are currently running under setuid permissions */
180 static int maybe_setuid = 1;
182 /* Flag telling whether we are running as a pipe server. */
183 static int pipe_server;
185 /* Name of the communication socket */
186 static char *socket_name;
188 /* We need to keep track of the server's nonces (these are dummies for
189 POSIX systems). */
190 static assuan_sock_nonce_t socket_nonce;
192 /* Debug flag to disable the ticker. The ticker is in fact not
193 disabled but it won't perform any ticker specific actions. */
194 static int ticker_disabled;
198 static char *create_socket_name (int use_standard_socket,
199 char *standard_name, char *template);
200 static gnupg_fd_t create_server_socket (int is_standard_name, const char *name,
201 assuan_sock_nonce_t *nonce);
203 static void *start_connection_thread (void *arg);
204 static void handle_connections (int listen_fd);
206 /* Pth wrapper function definitions. */
207 GCRY_THREAD_OPTION_PTH_IMPL;
208 static int fixed_gcry_pth_init (void)
210 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
215 static char *
216 make_libversion (const char *libname, const char *(*getfnc)(const char*))
218 const char *s;
219 char *result;
221 if (maybe_setuid)
223 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
224 maybe_setuid = 0;
226 s = getfnc (NULL);
227 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
228 strcpy (stpcpy (stpcpy (result, libname), " "), s);
229 return result;
233 static const char *
234 my_strusage (int level)
236 static char *ver_gcry, *ver_ksba;
237 const char *p;
239 switch (level)
241 case 11: p = "scdaemon (GnuPG)";
242 break;
243 case 13: p = VERSION; break;
244 case 17: p = PRINTABLE_OS_NAME; break;
245 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
247 case 20:
248 if (!ver_gcry)
249 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
250 p = ver_gcry;
251 break;
252 case 21:
253 if (!ver_ksba)
254 ver_ksba = make_libversion ("libksba", ksba_check_version);
255 p = ver_ksba;
256 break;
257 case 1:
258 case 40: p = _("Usage: scdaemon [options] (-h for help)");
259 break;
260 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
261 "Smartcard daemon for GnuPG\n");
262 break;
264 default: p = NULL;
266 return p;
270 static unsigned long
271 tid_log_callback (void)
273 #ifdef PTH_HAVE_PTH_THREAD_ID
274 return pth_thread_id ();
275 #else
276 return (unsigned long)pth_self ();
277 #endif
284 /* Setup the debugging. With a LEVEL of NULL only the active debug
285 flags are propagated to the subsystems. With LEVEL set, a specific
286 set of debug flags is set; thus overriding all flags already
287 set. */
288 static void
289 set_debug (const char *level)
291 if (!level)
293 else if (!strcmp (level, "none"))
294 opt.debug = 0;
295 else if (!strcmp (level, "basic"))
296 opt.debug = DBG_ASSUAN_VALUE;
297 else if (!strcmp (level, "advanced"))
298 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
299 else if (!strcmp (level, "expert"))
300 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
301 |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
302 else if (!strcmp (level, "guru"))
303 opt.debug = ~0;
304 else
306 log_error (_("invalid debug-level `%s' given\n"), level);
307 scd_exit(2);
311 if (opt.debug && !opt.verbose)
312 opt.verbose = 1;
313 if (opt.debug && opt.quiet)
314 opt.quiet = 0;
316 if (opt.debug & DBG_MPI_VALUE)
317 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
318 if (opt.debug & DBG_CRYPTO_VALUE )
319 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
320 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
325 static void
326 cleanup (void)
328 if (socket_name && *socket_name)
330 char *p;
332 remove (socket_name);
333 p = strrchr (socket_name, '/');
334 if (p)
336 *p = 0;
337 rmdir (socket_name);
338 *p = '/';
340 *socket_name = 0;
347 main (int argc, char **argv )
349 ARGPARSE_ARGS pargs;
350 int orig_argc;
351 gpg_error_t err;
352 int may_coredump;
353 char **orig_argv;
354 FILE *configfp = NULL;
355 char *configname = NULL;
356 const char *shell;
357 unsigned int configlineno;
358 int parse_debug = 0;
359 const char *debug_level = NULL;
360 int default_config =1;
361 int greeting = 0;
362 int nogreeting = 0;
363 int multi_server = 0;
364 int is_daemon = 0;
365 int nodetach = 0;
366 int csh_style = 0;
367 char *logfile = NULL;
368 int debug_wait = 0;
369 int gpgconf_list = 0;
370 const char *config_filename = NULL;
371 int allow_coredump = 0;
372 int standard_socket = 0;
373 struct assuan_malloc_hooks malloc_hooks;
375 set_strusage (my_strusage);
376 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
377 /* Please note that we may running SUID(ROOT), so be very CAREFUL
378 when adding any stuff between here and the call to INIT_SECMEM()
379 somewhere after the option parsing */
380 log_set_prefix ("scdaemon", 1|4);
382 /* Make sure that our subsystems are ready. */
383 i18n_init ();
384 init_common_subsystems ();
387 /* Libgcrypt requires us to register the threading model first.
388 Note that this will also do the pth_init. */
389 gcry_threads_pth.init = fixed_gcry_pth_init;
390 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
391 if (err)
393 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
394 gpg_strerror (err));
397 /* Check that the libraries are suitable. Do it here because
398 the option parsing may need services of the library */
399 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
401 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
402 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
405 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
407 malloc_hooks.malloc = gcry_malloc;
408 malloc_hooks.realloc = gcry_realloc;
409 malloc_hooks.free = gcry_free;
410 assuan_set_malloc_hooks (&malloc_hooks);
411 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
412 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
414 setup_libgcrypt_logging ();
415 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
417 may_coredump = disable_core_dumps ();
419 /* Set default options. */
420 opt.allow_admin = 1;
421 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
423 #ifdef HAVE_W32_SYSTEM
424 standard_socket = 1; /* Under Windows we always use a standard
425 socket. */
426 #endif
429 shell = getenv ("SHELL");
430 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
431 csh_style = 1;
433 opt.homedir = default_homedir ();
435 /* Check whether we have a config file on the commandline */
436 orig_argc = argc;
437 orig_argv = argv;
438 pargs.argc = &argc;
439 pargs.argv = &argv;
440 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
441 while (arg_parse( &pargs, opts))
443 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
444 parse_debug++;
445 else if (pargs.r_opt == oOptions)
446 { /* yes there is one, so we do not try the default one, but
447 read the option file when it is encountered at the
448 commandline */
449 default_config = 0;
451 else if (pargs.r_opt == oNoOptions)
452 default_config = 0; /* --no-options */
453 else if (pargs.r_opt == oHomedir)
454 opt.homedir = pargs.r.ret_str;
457 /* initialize the secure memory. */
458 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
459 maybe_setuid = 0;
462 Now we are working under our real uid
466 if (default_config)
467 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
470 argc = orig_argc;
471 argv = orig_argv;
472 pargs.argc = &argc;
473 pargs.argv = &argv;
474 pargs.flags= 1; /* do not remove the args */
475 next_pass:
476 if (configname)
478 configlineno = 0;
479 configfp = fopen (configname, "r");
480 if (!configfp)
482 if (default_config)
484 if( parse_debug )
485 log_info (_("NOTE: no default option file `%s'\n"),
486 configname );
488 else
490 log_error (_("option file `%s': %s\n"),
491 configname, strerror(errno) );
492 exit(2);
494 xfree (configname);
495 configname = NULL;
497 if (parse_debug && configname )
498 log_info (_("reading options from `%s'\n"), configname );
499 default_config = 0;
502 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
504 switch (pargs.r_opt)
506 case aGPGConfList: gpgconf_list = 1; break;
507 case aGPGConfTest: gpgconf_list = 2; break;
508 case oQuiet: opt.quiet = 1; break;
509 case oVerbose: opt.verbose++; break;
510 case oBatch: opt.batch=1; break;
512 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
513 case oDebugAll: opt.debug = ~0; break;
514 case oDebugLevel: debug_level = pargs.r.ret_str; break;
515 case oDebugWait: debug_wait = pargs.r.ret_int; break;
516 case oDebugAllowCoreDump:
517 enable_core_dumps ();
518 allow_coredump = 1;
519 break;
520 case oDebugCCIDDriver:
521 #ifdef HAVE_LIBUSB
522 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
523 #endif /*HAVE_LIBUSB*/
524 break;
525 case oDebugDisableTicker: ticker_disabled = 1; break;
526 case oDebugLogTid:
527 log_set_get_tid_callback (tid_log_callback);
528 break;
530 case oOptions:
531 /* config files may not be nested (silently ignore them) */
532 if (!configfp)
534 xfree(configname);
535 configname = xstrdup(pargs.r.ret_str);
536 goto next_pass;
538 break;
539 case oNoGreeting: nogreeting = 1; break;
540 case oNoVerbose: opt.verbose = 0; break;
541 case oNoOptions: break; /* no-options */
542 case oHomedir: opt.homedir = pargs.r.ret_str; break;
543 case oNoDetach: nodetach = 1; break;
544 case oLogFile: logfile = pargs.r.ret_str; break;
545 case oCsh: csh_style = 1; break;
546 case oSh: csh_style = 0; break;
547 case oServer: pipe_server = 1; break;
548 case oMultiServer: pipe_server = 1; multi_server = 1; break;
549 case oDaemon: is_daemon = 1; break;
551 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
552 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
553 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
554 case oDisableCCID: opt.disable_ccid = 1; break;
555 case oDisableOpenSC: break;
557 case oDisableKeypad: opt.disable_keypad = 1; break;
559 case oAllowAdmin: /* Dummy because allow is now the default. */
560 break;
561 case oDenyAdmin: opt.allow_admin = 0; break;
563 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
565 case oDisableApplication:
566 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
567 break;
569 default:
570 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
571 break;
574 if (configfp)
576 fclose( configfp );
577 configfp = NULL;
578 /* Keep a copy of the config name for use by --gpgconf-list. */
579 config_filename = configname;
580 configname = NULL;
581 goto next_pass;
583 xfree (configname);
584 configname = NULL;
585 if (log_get_errorcount(0))
586 exit(2);
587 if (nogreeting )
588 greeting = 0;
590 if (greeting)
592 fprintf (stderr, "%s %s; %s\n",
593 strusage(11), strusage(13), strusage(14) );
594 fprintf (stderr, "%s\n", strusage(15) );
596 #ifdef IS_DEVELOPMENT_VERSION
597 log_info ("NOTE: this is a development version!\n");
598 #endif
601 if (atexit (cleanup))
603 log_error ("atexit failed\n");
604 cleanup ();
605 exit (1);
608 set_debug (debug_level);
610 initialize_module_command ();
612 if (gpgconf_list == 2)
613 scd_exit (0);
614 if (gpgconf_list)
616 /* List options and default values in the GPG Conf format. */
617 char *filename = NULL;
618 char *filename_esc;
620 if (config_filename)
621 filename = xstrdup (config_filename);
622 else
623 filename = make_filename (opt.homedir, "scdaemon.conf", NULL);
624 filename_esc = percent_escape (filename, NULL);
626 printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
627 GC_OPT_FLAG_DEFAULT, filename_esc);
628 xfree (filename_esc);
629 xfree (filename);
631 printf ("verbose:%lu:\n"
632 "quiet:%lu:\n"
633 "debug-level:%lu:\"none:\n"
634 "log-file:%lu:\n",
635 GC_OPT_FLAG_NONE,
636 GC_OPT_FLAG_NONE,
637 GC_OPT_FLAG_DEFAULT,
638 GC_OPT_FLAG_NONE );
640 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
641 printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
642 printf ("pcsc-driver:%lu:\"%s:\n",
643 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
644 #ifdef HAVE_LIBUSB
645 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
646 #endif
647 printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
648 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
649 printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
651 scd_exit (0);
654 /* Now start with logging to a file if this is desired. */
655 if (logfile)
657 log_set_file (logfile);
658 log_set_prefix (NULL, 1|2|4);
661 if (debug_wait && pipe_server)
663 log_debug ("waiting for debugger - my pid is %u .....\n",
664 (unsigned int)getpid());
665 gnupg_sleep (debug_wait);
666 log_debug ("... okay\n");
669 if (pipe_server)
671 /* This is the simple pipe based server */
672 ctrl_t ctrl;
673 pth_attr_t tattr;
674 int fd = -1;
676 #ifndef HAVE_W32_SYSTEM
678 struct sigaction sa;
680 sa.sa_handler = SIG_IGN;
681 sigemptyset (&sa.sa_mask);
682 sa.sa_flags = 0;
683 sigaction (SIGPIPE, &sa, NULL);
685 #endif
687 /* If --debug-allow-core-dump has been given we also need to
688 switch the working directory to a place where we can actually
689 write. */
690 if (allow_coredump)
692 if (chdir("/tmp"))
693 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
694 else
695 log_debug ("changed working directory to `/tmp'\n");
698 /* In multi server mode we need to listen on an additional
699 socket. Create that socket now before starting the handler
700 for the pipe connection. This allows that handler to send
701 back the name of that socket. */
702 if (multi_server)
704 socket_name = create_socket_name (standard_socket,
705 "S.scdaemon",
706 "/tmp/gpg-XXXXXX/S.scdaemon");
708 fd = FD2INT(create_server_socket (standard_socket,
709 socket_name, &socket_nonce));
712 tattr = pth_attr_new();
713 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
714 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
715 pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
717 ctrl = xtrycalloc (1, sizeof *ctrl);
718 if ( !ctrl )
720 log_error ("error allocating connection control data: %s\n",
721 strerror (errno) );
722 scd_exit (2);
724 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
725 if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
727 log_error ("error spawning pipe connection handler: %s\n",
728 strerror (errno) );
729 xfree (ctrl);
730 scd_exit (2);
733 /* We run handle_connection to wait for the shutdown signal and
734 to run the ticker stuff. */
735 handle_connections (fd);
736 if (fd != -1)
737 close (fd);
739 else if (!is_daemon)
741 log_info (_("please use the option `--daemon'"
742 " to run the program in the background\n"));
744 else
745 { /* Regular server mode */
746 int fd;
747 #ifndef HAVE_W32_SYSTEM
748 pid_t pid;
749 int i;
750 #endif
752 /* Create the socket. */
753 socket_name = create_socket_name (standard_socket,
754 "S.scdaemon",
755 "/tmp/gpg-XXXXXX/S.scdaemon");
757 fd = FD2INT (create_server_socket (standard_socket,
758 socket_name, &socket_nonce));
761 fflush (NULL);
762 #ifndef HAVE_W32_SYSTEM
763 pid = fork ();
764 if (pid == (pid_t)-1)
766 log_fatal ("fork failed: %s\n", strerror (errno) );
767 exit (1);
769 else if (pid)
770 { /* we are the parent */
771 char *infostr;
773 close (fd);
775 /* create the info string: <name>:<pid>:<protocol_version> */
776 if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
777 socket_name, (ulong) pid) < 0)
779 log_error ("out of core\n");
780 kill (pid, SIGTERM);
781 exit (1);
783 *socket_name = 0; /* don't let cleanup() remove the socket -
784 the child should do this from now on */
785 if (argc)
786 { /* run the program given on the commandline */
787 if (putenv (infostr))
789 log_error ("failed to set environment: %s\n",
790 strerror (errno) );
791 kill (pid, SIGTERM );
792 exit (1);
794 execvp (argv[0], argv);
795 log_error ("failed to run the command: %s\n", strerror (errno));
796 kill (pid, SIGTERM);
797 exit (1);
799 else
801 /* Print the environment string, so that the caller can use
802 shell's eval to set it */
803 if (csh_style)
805 *strchr (infostr, '=') = ' ';
806 printf ( "setenv %s\n", infostr);
808 else
810 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
812 xfree (infostr);
813 exit (0);
815 /* NOTREACHED */
816 } /* end parent */
818 /* This is the child. */
820 /* Detach from tty and put process into a new session. */
821 if (!nodetach )
823 /* Close stdin, stdout and stderr unless it is the log stream. */
824 for (i=0; i <= 2; i++)
826 if ( log_test_fd (i) && i != fd)
827 close (i);
829 if (setsid() == -1)
831 log_error ("setsid() failed: %s\n", strerror(errno) );
832 cleanup ();
833 exit (1);
838 struct sigaction sa;
840 sa.sa_handler = SIG_IGN;
841 sigemptyset (&sa.sa_mask);
842 sa.sa_flags = 0;
843 sigaction (SIGPIPE, &sa, NULL);
846 if (chdir("/"))
848 log_error ("chdir to / failed: %s\n", strerror (errno));
849 exit (1);
852 #endif /*!HAVE_W32_SYSTEM*/
854 handle_connections (fd);
856 close (fd);
859 return 0;
862 void
863 scd_exit (int rc)
865 apdu_prepare_exit ();
866 #if 0
867 #warning no update_random_seed_file
868 update_random_seed_file();
869 #endif
870 #if 0
871 /* at this time a bit annoying */
872 if (opt.debug & DBG_MEMSTAT_VALUE)
874 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
875 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
877 if (opt.debug)
878 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
879 #endif
880 gcry_control (GCRYCTL_TERM_SECMEM );
881 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
882 exit (rc);
886 static void
887 scd_init_default_ctrl (ctrl_t ctrl)
889 ctrl->reader_slot = -1;
892 static void
893 scd_deinit_default_ctrl (ctrl_t ctrl)
895 (void)ctrl;
899 /* Return the name of the socket to be used to connect to this
900 process. If no socket is available, return NULL. */
901 const char *
902 scd_get_socket_name ()
904 if (socket_name && *socket_name)
905 return socket_name;
906 return NULL;
910 static void
911 handle_signal (int signo)
913 switch (signo)
915 #ifndef HAVE_W32_SYSTEM
916 case SIGHUP:
917 log_info ("SIGHUP received - "
918 "re-reading configuration and resetting cards\n");
919 /* reread_configuration (); */
920 break;
922 case SIGUSR1:
923 log_info ("SIGUSR1 received - printing internal information:\n");
924 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
925 app_dump_state ();
926 break;
928 case SIGUSR2:
929 log_info ("SIGUSR2 received - no action defined\n");
930 break;
932 case SIGTERM:
933 if (!shutdown_pending)
934 log_info ("SIGTERM received - shutting down ...\n");
935 else
936 log_info ("SIGTERM received - still %ld running threads\n",
937 pth_ctrl( PTH_CTRL_GETTHREADS ));
938 shutdown_pending++;
939 if (shutdown_pending > 2)
941 log_info ("shutdown forced\n");
942 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
943 cleanup ();
944 scd_exit (0);
946 break;
948 case SIGINT:
949 log_info ("SIGINT received - immediate shutdown\n");
950 log_info( "%s %s stopped\n", strusage(11), strusage(13));
951 cleanup ();
952 scd_exit (0);
953 break;
954 #endif /*!HAVE_W32_SYSTEM*/
956 default:
957 log_info ("signal %d received - no action defined\n", signo);
962 static void
963 handle_tick (void)
965 if (!ticker_disabled)
966 scd_update_reader_status_file ();
970 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
971 true using STANDARD_NAME in the home directory or if given has
972 false from the mkdir type name TEMPLATE. In the latter case a
973 unique name in a unique new directory will be created. In both
974 cases check for valid characters as well as against a maximum
975 allowed length for a unix domain socket is done. The function
976 terminates the process in case of an error. Retunrs: Pointer to an
977 allcoated string with the absolute name of the socket used. */
978 static char *
979 create_socket_name (int use_standard_socket,
980 char *standard_name, char *template)
982 char *name, *p;
984 if (use_standard_socket)
985 name = make_filename (opt.homedir, standard_name, NULL);
986 else
988 name = xstrdup (template);
989 p = strrchr (name, '/');
990 if (!p)
991 BUG ();
992 *p = 0;
993 if (!mkdtemp (name))
995 log_error (_("can't create directory `%s': %s\n"),
996 name, strerror (errno));
997 scd_exit (2);
999 *p = '/';
1002 if (strchr (name, PATHSEP_C))
1004 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1005 scd_exit (2);
1007 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1009 log_error (_("name of socket too long\n"));
1010 scd_exit (2);
1012 return name;
1017 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1018 whether a non-random socket is used. Returns the file descriptor
1019 or terminates the process in case of an error. */
1020 static gnupg_fd_t
1021 create_server_socket (int is_standard_name, const char *name,
1022 assuan_sock_nonce_t *nonce)
1024 struct sockaddr_un *serv_addr;
1025 socklen_t len;
1026 gnupg_fd_t fd;
1027 int rc;
1029 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1030 if (fd == GNUPG_INVALID_FD)
1032 log_error (_("can't create socket: %s\n"), strerror (errno));
1033 scd_exit (2);
1036 serv_addr = xmalloc (sizeof (*serv_addr));
1037 memset (serv_addr, 0, sizeof *serv_addr);
1038 serv_addr->sun_family = AF_UNIX;
1039 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
1040 strcpy (serv_addr->sun_path, name);
1041 len = SUN_LEN (serv_addr);
1043 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1044 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
1046 remove (name);
1047 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1049 if (rc != -1
1050 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1051 log_error (_("error getting nonce for the socket\n"));
1052 if (rc == -1)
1054 log_error (_("error binding socket to `%s': %s\n"),
1055 serv_addr->sun_path,
1056 gpg_strerror (gpg_error_from_syserror ()));
1057 assuan_sock_close (fd);
1058 scd_exit (2);
1061 if (listen (FD2INT(fd), 5 ) == -1)
1063 log_error (_("listen() failed: %s\n"),
1064 gpg_strerror (gpg_error_from_syserror ()));
1065 assuan_sock_close (fd);
1066 scd_exit (2);
1069 if (opt.verbose)
1070 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1072 return fd;
1077 /* This is the standard connection thread's main function. */
1078 static void *
1079 start_connection_thread (void *arg)
1081 ctrl_t ctrl = arg;
1083 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1084 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1086 log_info (_("error reading nonce on fd %d: %s\n"),
1087 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1088 assuan_sock_close (ctrl->thread_startup.fd);
1089 xfree (ctrl);
1090 return NULL;
1093 scd_init_default_ctrl (ctrl);
1094 if (opt.verbose)
1095 log_info (_("handler for fd %d started\n"),
1096 FD2INT(ctrl->thread_startup.fd));
1098 /* If this is a pipe server, we request a shutdown if the command
1099 handler asked for it. With the next ticker event and given that
1100 no other connections are running the shutdown will then
1101 happen. */
1102 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1103 && pipe_server)
1104 shutdown_pending = 1;
1106 if (opt.verbose)
1107 log_info (_("handler for fd %d terminated\n"),
1108 FD2INT (ctrl->thread_startup.fd));
1110 scd_deinit_default_ctrl (ctrl);
1111 xfree (ctrl);
1112 return NULL;
1116 /* Connection handler loop. Wait for connection requests and spawn a
1117 thread after accepting a connection. LISTEN_FD is allowed to be -1
1118 in which case this code will only do regular timeouts and handle
1119 signals. */
1120 static void
1121 handle_connections (int listen_fd)
1123 pth_attr_t tattr;
1124 pth_event_t ev, time_ev;
1125 sigset_t sigs;
1126 int signo;
1127 struct sockaddr_un paddr;
1128 socklen_t plen;
1129 fd_set fdset, read_fdset;
1130 int ret;
1131 int fd;
1132 int nfd;
1134 tattr = pth_attr_new();
1135 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1136 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
1138 #ifndef HAVE_W32_SYSTEM /* fixme */
1139 sigemptyset (&sigs );
1140 sigaddset (&sigs, SIGHUP);
1141 sigaddset (&sigs, SIGUSR1);
1142 sigaddset (&sigs, SIGUSR2);
1143 sigaddset (&sigs, SIGINT);
1144 sigaddset (&sigs, SIGTERM);
1145 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1146 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1147 #else
1148 sigs = 0;
1149 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1150 #endif
1151 time_ev = NULL;
1153 FD_ZERO (&fdset);
1154 nfd = 0;
1155 if (listen_fd != -1)
1157 FD_SET (listen_fd, &fdset);
1158 nfd = listen_fd;
1161 for (;;)
1163 sigset_t oldsigs;
1165 if (shutdown_pending)
1167 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1168 break; /* ready */
1170 /* Do not accept anymore connections but wait for existing
1171 connections to terminate. We do this by clearing out all
1172 file descriptors to wait for, so that the select will be
1173 used to just wait on a signal or timeout event. */
1174 FD_ZERO (&fdset);
1175 listen_fd = -1;
1178 /* Create a timeout event if needed. Round it up to the next
1179 microsecond interval to help with power saving. */
1180 if (!time_ev)
1182 pth_time_t nexttick = pth_timeout (TIMERTICK_INTERVAL_SEC,
1183 TIMERTICK_INTERVAL_USEC/2);
1184 if ((nexttick.tv_usec % (TIMERTICK_INTERVAL_USEC/2)) > 10)
1186 nexttick.tv_usec = ((nexttick.tv_usec
1187 /(TIMERTICK_INTERVAL_USEC/2))
1188 + 1) * (TIMERTICK_INTERVAL_USEC/2);
1189 if (nexttick.tv_usec >= 1000000)
1191 nexttick.tv_sec++;
1192 nexttick.tv_usec = 0;
1195 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1198 /* POSIX says that fd_set should be implemented as a structure,
1199 thus a simple assignment is fine to copy the entire set. */
1200 read_fdset = fdset;
1202 if (time_ev)
1203 pth_event_concat (ev, time_ev, NULL);
1204 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1205 if (time_ev)
1206 pth_event_isolate (time_ev);
1208 if (ret == -1)
1210 if (pth_event_occurred (ev)
1211 || (time_ev && pth_event_occurred (time_ev)))
1213 if (pth_event_occurred (ev))
1214 handle_signal (signo);
1215 if (time_ev && pth_event_occurred (time_ev))
1217 pth_event_free (time_ev, PTH_FREE_ALL);
1218 time_ev = NULL;
1219 handle_tick ();
1221 continue;
1223 log_error (_("pth_select failed: %s - waiting 1s\n"),
1224 strerror (errno));
1225 pth_sleep (1);
1226 continue;
1229 if (pth_event_occurred (ev))
1231 handle_signal (signo);
1234 if (time_ev && pth_event_occurred (time_ev))
1236 pth_event_free (time_ev, PTH_FREE_ALL);
1237 time_ev = NULL;
1238 handle_tick ();
1241 /* We now might create new threads and because we don't want any
1242 signals - we are handling here - to be delivered to a new
1243 thread. Thus we need to block those signals. */
1244 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1246 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1248 ctrl_t ctrl;
1250 plen = sizeof paddr;
1251 fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1252 if (fd == -1)
1254 log_error ("accept failed: %s\n", strerror (errno));
1256 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1258 log_error ("error allocating connection control data: %s\n",
1259 strerror (errno) );
1260 close (fd);
1262 else
1264 char threadname[50];
1266 snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd);
1267 threadname[sizeof threadname -1] = 0;
1268 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1269 ctrl->thread_startup.fd = INT2FD (fd);
1270 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1272 log_error ("error spawning connection handler: %s\n",
1273 strerror (errno) );
1274 xfree (ctrl);
1275 close (fd);
1278 fd = -1;
1281 /* Restore the signal mask. */
1282 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1286 pth_event_free (ev, PTH_FREE_ALL);
1287 if (time_ev)
1288 pth_event_free (time_ev, PTH_FREE_ALL);
1289 cleanup ();
1290 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));