Prepare for OpenPGP cards with extended length support.
[gnupg.git] / scd / scdaemon.c
blob0afb5febca1f9aaffb189a8302d2cda9879fe6c2
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 #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 oDebugLogTid,
73 oNoGreeting,
74 oNoOptions,
75 oHomedir,
76 oNoDetach,
77 oNoGrab,
78 oLogFile,
79 oServer,
80 oMultiServer,
81 oDaemon,
82 oBatch,
83 oReaderPort,
84 oCardTimeout,
85 octapiDriver,
86 opcscDriver,
87 oDisableCCID,
88 oDisableOpenSC,
89 oDisableKeypad,
90 oAllowAdmin,
91 oDenyAdmin,
92 oDisableApplication,
93 oDebugDisableTicker
98 static ARGPARSE_OPTS opts[] = {
99 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
100 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
102 ARGPARSE_group (301, N_("@Options:\n ")),
104 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
105 ARGPARSE_s_n (oMultiServer, "multi-server",
106 N_("run in multi server mode (foreground)")),
107 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
108 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
109 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
110 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
111 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
112 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
113 ARGPARSE_p_u (oDebug, "debug", "@"),
114 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
115 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
116 N_("|LEVEL|set the debugging level to LEVEL")),
117 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
118 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
119 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
120 ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
121 ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
122 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
123 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
124 ARGPARSE_s_s (oReaderPort, "reader-port",
125 N_("|N|connect to reader at port N")),
126 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
127 N_("|NAME|use NAME as ct-API driver")),
128 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
129 N_("|NAME|use NAME as PC/SC driver")),
130 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
131 #ifdef HAVE_LIBUSB
132 N_("do not use the internal CCID driver")
133 #else
135 #endif
136 /* end --disable-ccid */),
137 ARGPARSE_s_u (oCardTimeout, "card-timeout",
138 N_("|N|disconnect the card after N seconds of inactivity")),
139 ARGPARSE_s_n (oDisableKeypad, "disable-keypad",
140 N_("do not use a reader's keypad")),
141 ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
142 ARGPARSE_s_n (oDenyAdmin, "deny-admin",
143 N_("deny the use of admin card commands")),
144 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
146 ARGPARSE_end ()
150 /* The card driver we use by default for PC/SC. */
151 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
152 #define DEFAULT_PCSC_DRIVER "winscard.dll"
153 #elif defined(__APPLE__)
154 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
155 #elif defined(__GLIBC__)
156 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
157 #else
158 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
159 #endif
161 /* The timer tick used for housekeeping stuff. We poll every 500ms to
162 let the user immediately know a status change.
164 This is not too good for power saving but given that there is no
165 easy way to block on card status changes it is the best we can do.
166 For PC/SC we could in theory use an extra thread to wait for status
167 changes but that requires a native thread because there is no way
168 to make the underlying PC/SC card change function block using a Pth
169 mechanism. Given that a native thread could only be used under W32
170 we don't do that at all. */
171 #define TIMERTICK_INTERVAL_SEC (0)
172 #define TIMERTICK_INTERVAL_USEC (500000)
174 /* Flag to indicate that a shutdown was requested. */
175 static int shutdown_pending;
177 /* It is possible that we are currently running under setuid permissions */
178 static int maybe_setuid = 1;
180 /* Flag telling whether we are running as a pipe server. */
181 static int pipe_server;
183 /* Name of the communication socket */
184 static char *socket_name;
186 /* We need to keep track of the server's nonces (these are dummies for
187 POSIX systems). */
188 static assuan_sock_nonce_t socket_nonce;
190 /* Debug flag to disable the ticker. The ticker is in fact not
191 disabled but it won't perform any ticker specific actions. */
192 static int ticker_disabled;
196 static char *create_socket_name (int use_standard_socket,
197 char *standard_name, char *template);
198 static gnupg_fd_t create_server_socket (int is_standard_name, const char *name,
199 assuan_sock_nonce_t *nonce);
201 static void *start_connection_thread (void *arg);
202 static void handle_connections (int listen_fd);
204 /* Pth wrapper function definitions. */
205 GCRY_THREAD_OPTION_PTH_IMPL;
206 static int fixed_gcry_pth_init (void)
208 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
213 static char *
214 make_libversion (const char *libname, const char *(*getfnc)(const char*))
216 const char *s;
217 char *result;
219 if (maybe_setuid)
221 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
222 maybe_setuid = 0;
224 s = getfnc (NULL);
225 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
226 strcpy (stpcpy (stpcpy (result, libname), " "), s);
227 return result;
231 static const char *
232 my_strusage (int level)
234 static char *ver_gcry, *ver_ksba;
235 const char *p;
237 switch (level)
239 case 11: p = "scdaemon (GnuPG)";
240 break;
241 case 13: p = VERSION; break;
242 case 17: p = PRINTABLE_OS_NAME; break;
243 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
244 break;
245 case 20:
246 if (!ver_gcry)
247 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
248 p = ver_gcry;
249 break;
250 case 21:
251 if (!ver_ksba)
252 ver_ksba = make_libversion ("libksba", ksba_check_version);
253 p = ver_ksba;
254 break;
255 case 1:
256 case 40: p = _("Usage: scdaemon [options] (-h for help)");
257 break;
258 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
259 "Smartcard daemon for GnuPG\n");
260 break;
262 default: p = NULL;
264 return p;
268 static unsigned long
269 tid_log_callback (void)
271 #ifdef PTH_HAVE_PTH_THREAD_ID
272 return pth_thread_id ();
273 #else
274 return (unsigned long)pth_self ();
275 #endif
282 /* Setup the debugging. With a LEVEL of NULL only the active debug
283 flags are propagated to the subsystems. With LEVEL set, a specific
284 set of debug flags is set; thus overriding all flags already
285 set. */
286 static void
287 set_debug (const char *level)
289 if (!level)
291 else if (!strcmp (level, "none"))
292 opt.debug = 0;
293 else if (!strcmp (level, "basic"))
294 opt.debug = DBG_ASSUAN_VALUE;
295 else if (!strcmp (level, "advanced"))
296 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
297 else if (!strcmp (level, "expert"))
298 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
299 |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
300 else if (!strcmp (level, "guru"))
301 opt.debug = ~0;
302 else
304 log_error (_("invalid debug-level `%s' given\n"), level);
305 scd_exit(2);
309 if (opt.debug && !opt.verbose)
310 opt.verbose = 1;
311 if (opt.debug && opt.quiet)
312 opt.quiet = 0;
314 if (opt.debug & DBG_MPI_VALUE)
315 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
316 if (opt.debug & DBG_CRYPTO_VALUE )
317 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
318 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
323 static void
324 cleanup (void)
326 if (socket_name && *socket_name)
328 char *p;
330 remove (socket_name);
331 p = strrchr (socket_name, '/');
332 if (p)
334 *p = 0;
335 rmdir (socket_name);
336 *p = '/';
338 *socket_name = 0;
345 main (int argc, char **argv )
347 ARGPARSE_ARGS pargs;
348 int orig_argc;
349 gpg_error_t err;
350 int may_coredump;
351 char **orig_argv;
352 FILE *configfp = NULL;
353 char *configname = NULL;
354 const char *shell;
355 unsigned int configlineno;
356 int parse_debug = 0;
357 const char *debug_level = NULL;
358 int default_config =1;
359 int greeting = 0;
360 int nogreeting = 0;
361 int multi_server = 0;
362 int is_daemon = 0;
363 int nodetach = 0;
364 int csh_style = 0;
365 char *logfile = NULL;
366 int debug_wait = 0;
367 int gpgconf_list = 0;
368 const char *config_filename = NULL;
369 int allow_coredump = 0;
370 int standard_socket = 0;
372 set_strusage (my_strusage);
373 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
374 /* Please note that we may running SUID(ROOT), so be very CAREFUL
375 when adding any stuff between here and the call to INIT_SECMEM()
376 somewhere after the option parsing */
377 log_set_prefix ("scdaemon", 1|4);
379 /* Make sure that our subsystems are ready. */
380 i18n_init ();
381 init_common_subsystems ();
384 /* Libgcrypt requires us to register the threading model first.
385 Note that this will also do the pth_init. */
386 gcry_threads_pth.init = fixed_gcry_pth_init;
387 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
388 if (err)
390 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
391 gpg_strerror (err));
394 /* Check that the libraries are suitable. Do it here because
395 the option parsing may need services of the library */
396 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
398 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
399 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
402 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
404 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
405 assuan_set_assuan_log_stream (log_get_stream ());
406 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
407 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
409 setup_libgcrypt_logging ();
410 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
412 may_coredump = disable_core_dumps ();
414 /* Set default options. */
415 opt.allow_admin = 1;
416 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
418 #ifdef HAVE_W32_SYSTEM
419 standard_socket = 1; /* Under Windows we always use a standard
420 socket. */
421 #endif
424 shell = getenv ("SHELL");
425 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
426 csh_style = 1;
428 opt.homedir = default_homedir ();
430 /* Check whether we have a config file on the commandline */
431 orig_argc = argc;
432 orig_argv = argv;
433 pargs.argc = &argc;
434 pargs.argv = &argv;
435 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
436 while (arg_parse( &pargs, opts))
438 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
439 parse_debug++;
440 else if (pargs.r_opt == oOptions)
441 { /* yes there is one, so we do not try the default one, but
442 read the option file when it is encountered at the
443 commandline */
444 default_config = 0;
446 else if (pargs.r_opt == oNoOptions)
447 default_config = 0; /* --no-options */
448 else if (pargs.r_opt == oHomedir)
449 opt.homedir = pargs.r.ret_str;
452 /* initialize the secure memory. */
453 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
454 maybe_setuid = 0;
457 Now we are working under our real uid
461 if (default_config)
462 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
465 argc = orig_argc;
466 argv = orig_argv;
467 pargs.argc = &argc;
468 pargs.argv = &argv;
469 pargs.flags= 1; /* do not remove the args */
470 next_pass:
471 if (configname)
473 configlineno = 0;
474 configfp = fopen (configname, "r");
475 if (!configfp)
477 if (default_config)
479 if( parse_debug )
480 log_info (_("NOTE: no default option file `%s'\n"),
481 configname );
483 else
485 log_error (_("option file `%s': %s\n"),
486 configname, strerror(errno) );
487 exit(2);
489 xfree (configname);
490 configname = NULL;
492 if (parse_debug && configname )
493 log_info (_("reading options from `%s'\n"), configname );
494 default_config = 0;
497 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
499 switch (pargs.r_opt)
501 case aGPGConfList: gpgconf_list = 1; break;
502 case aGPGConfTest: gpgconf_list = 2; break;
503 case oQuiet: opt.quiet = 1; break;
504 case oVerbose: opt.verbose++; break;
505 case oBatch: opt.batch=1; break;
507 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
508 case oDebugAll: opt.debug = ~0; break;
509 case oDebugLevel: debug_level = pargs.r.ret_str; break;
510 case oDebugWait: debug_wait = pargs.r.ret_int; break;
511 case oDebugAllowCoreDump:
512 enable_core_dumps ();
513 allow_coredump = 1;
514 break;
515 case oDebugCCIDDriver:
516 #ifdef HAVE_LIBUSB
517 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
518 #endif /*HAVE_LIBUSB*/
519 break;
520 case oDebugDisableTicker: ticker_disabled = 1; break;
521 case oDebugLogTid:
522 log_set_get_tid_callback (tid_log_callback);
523 break;
525 case oOptions:
526 /* config files may not be nested (silently ignore them) */
527 if (!configfp)
529 xfree(configname);
530 configname = xstrdup(pargs.r.ret_str);
531 goto next_pass;
533 break;
534 case oNoGreeting: nogreeting = 1; break;
535 case oNoVerbose: opt.verbose = 0; break;
536 case oNoOptions: break; /* no-options */
537 case oHomedir: opt.homedir = pargs.r.ret_str; break;
538 case oNoDetach: nodetach = 1; break;
539 case oLogFile: logfile = pargs.r.ret_str; break;
540 case oCsh: csh_style = 1; break;
541 case oSh: csh_style = 0; break;
542 case oServer: pipe_server = 1; break;
543 case oMultiServer: pipe_server = 1; multi_server = 1; break;
544 case oDaemon: is_daemon = 1; break;
546 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
547 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
548 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
549 case oDisableCCID: opt.disable_ccid = 1; break;
550 case oDisableOpenSC: break;
552 case oDisableKeypad: opt.disable_keypad = 1; break;
554 case oAllowAdmin: /* Dummy because allow is now the default. */
555 break;
556 case oDenyAdmin: opt.allow_admin = 0; break;
558 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
560 case oDisableApplication:
561 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
562 break;
564 default:
565 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
566 break;
569 if (configfp)
571 fclose( configfp );
572 configfp = NULL;
573 /* Keep a copy of the config name for use by --gpgconf-list. */
574 config_filename = configname;
575 configname = NULL;
576 goto next_pass;
578 xfree (configname);
579 configname = NULL;
580 if (log_get_errorcount(0))
581 exit(2);
582 if (nogreeting )
583 greeting = 0;
585 if (greeting)
587 fprintf (stderr, "%s %s; %s\n",
588 strusage(11), strusage(13), strusage(14) );
589 fprintf (stderr, "%s\n", strusage(15) );
591 #ifdef IS_DEVELOPMENT_VERSION
592 log_info ("NOTE: this is a development version!\n");
593 #endif
596 if (atexit (cleanup))
598 log_error ("atexit failed\n");
599 cleanup ();
600 exit (1);
603 set_debug (debug_level);
605 initialize_module_command ();
607 if (gpgconf_list == 2)
608 scd_exit (0);
609 if (gpgconf_list)
611 /* List options and default values in the GPG Conf format. */
612 char *filename = NULL;
613 char *filename_esc;
615 if (config_filename)
616 filename = xstrdup (config_filename);
617 else
618 filename = make_filename (opt.homedir, "scdaemon.conf", NULL);
619 filename_esc = percent_escape (filename, NULL);
621 printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
622 GC_OPT_FLAG_DEFAULT, filename_esc);
623 xfree (filename_esc);
624 xfree (filename);
626 printf ("verbose:%lu:\n"
627 "quiet:%lu:\n"
628 "debug-level:%lu:\"none:\n"
629 "log-file:%lu:\n",
630 GC_OPT_FLAG_NONE,
631 GC_OPT_FLAG_NONE,
632 GC_OPT_FLAG_DEFAULT,
633 GC_OPT_FLAG_NONE );
635 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
636 printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
637 printf ("pcsc-driver:%lu:\"%s:\n",
638 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
639 #ifdef HAVE_LIBUSB
640 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
641 #endif
642 printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
643 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
644 printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
646 scd_exit (0);
649 /* Now start with logging to a file if this is desired. */
650 if (logfile)
652 log_set_file (logfile);
653 log_set_prefix (NULL, 1|2|4);
656 if (debug_wait && pipe_server)
658 log_debug ("waiting for debugger - my pid is %u .....\n",
659 (unsigned int)getpid());
660 gnupg_sleep (debug_wait);
661 log_debug ("... okay\n");
664 if (pipe_server)
666 /* This is the simple pipe based server */
667 ctrl_t ctrl;
668 pth_attr_t tattr;
669 int fd = -1;
671 #ifndef HAVE_W32_SYSTEM
673 struct sigaction sa;
675 sa.sa_handler = SIG_IGN;
676 sigemptyset (&sa.sa_mask);
677 sa.sa_flags = 0;
678 sigaction (SIGPIPE, &sa, NULL);
680 #endif
682 /* If --debug-allow-core-dump has been given we also need to
683 switch the working directory to a place where we can actually
684 write. */
685 if (allow_coredump)
687 if (chdir("/tmp"))
688 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
689 else
690 log_debug ("changed working directory to `/tmp'\n");
693 /* In multi server mode we need to listen on an additional
694 socket. Create that socket now before starting the handler
695 for the pipe connection. This allows that handler to send
696 back the name of that socket. */
697 if (multi_server)
699 socket_name = create_socket_name (standard_socket,
700 "S.scdaemon",
701 "/tmp/gpg-XXXXXX/S.scdaemon");
703 fd = FD2INT(create_server_socket (standard_socket,
704 socket_name, &socket_nonce));
707 tattr = pth_attr_new();
708 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
709 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
710 pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
712 ctrl = xtrycalloc (1, sizeof *ctrl);
713 if ( !ctrl )
715 log_error ("error allocating connection control data: %s\n",
716 strerror (errno) );
717 scd_exit (2);
719 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
720 if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
722 log_error ("error spawning pipe connection handler: %s\n",
723 strerror (errno) );
724 xfree (ctrl);
725 scd_exit (2);
728 /* We run handle_connection to wait for the shutdown signal and
729 to run the ticker stuff. */
730 handle_connections (fd);
731 if (fd != -1)
732 close (fd);
734 else if (!is_daemon)
736 log_info (_("please use the option `--daemon'"
737 " to run the program in the background\n"));
739 else
740 { /* Regular server mode */
741 int fd;
742 #ifndef HAVE_W32_SYSTEM
743 pid_t pid;
744 int i;
745 #endif
747 /* Create the socket. */
748 socket_name = create_socket_name (standard_socket,
749 "S.scdaemon",
750 "/tmp/gpg-XXXXXX/S.scdaemon");
752 fd = FD2INT (create_server_socket (standard_socket,
753 socket_name, &socket_nonce));
756 fflush (NULL);
757 #ifndef HAVE_W32_SYSTEM
758 pid = fork ();
759 if (pid == (pid_t)-1)
761 log_fatal ("fork failed: %s\n", strerror (errno) );
762 exit (1);
764 else if (pid)
765 { /* we are the parent */
766 char *infostr;
768 close (fd);
770 /* create the info string: <name>:<pid>:<protocol_version> */
771 if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
772 socket_name, (ulong) pid) < 0)
774 log_error ("out of core\n");
775 kill (pid, SIGTERM);
776 exit (1);
778 *socket_name = 0; /* don't let cleanup() remove the socket -
779 the child should do this from now on */
780 if (argc)
781 { /* run the program given on the commandline */
782 if (putenv (infostr))
784 log_error ("failed to set environment: %s\n",
785 strerror (errno) );
786 kill (pid, SIGTERM );
787 exit (1);
789 execvp (argv[0], argv);
790 log_error ("failed to run the command: %s\n", strerror (errno));
791 kill (pid, SIGTERM);
792 exit (1);
794 else
796 /* Print the environment string, so that the caller can use
797 shell's eval to set it */
798 if (csh_style)
800 *strchr (infostr, '=') = ' ';
801 printf ( "setenv %s\n", infostr);
803 else
805 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
807 xfree (infostr);
808 exit (0);
810 /* NOTREACHED */
811 } /* end parent */
813 /* This is the child. */
815 /* Detach from tty and put process into a new session. */
816 if (!nodetach )
818 /* Close stdin, stdout and stderr unless it is the log stream. */
819 for (i=0; i <= 2; i++)
821 if ( log_test_fd (i) && i != fd)
822 close (i);
824 if (setsid() == -1)
826 log_error ("setsid() failed: %s\n", strerror(errno) );
827 cleanup ();
828 exit (1);
833 struct sigaction sa;
835 sa.sa_handler = SIG_IGN;
836 sigemptyset (&sa.sa_mask);
837 sa.sa_flags = 0;
838 sigaction (SIGPIPE, &sa, NULL);
841 if (chdir("/"))
843 log_error ("chdir to / failed: %s\n", strerror (errno));
844 exit (1);
847 #endif /*!HAVE_W32_SYSTEM*/
849 handle_connections (fd);
851 close (fd);
854 return 0;
857 void
858 scd_exit (int rc)
860 #if 0
861 #warning no update_random_seed_file
862 update_random_seed_file();
863 #endif
864 #if 0
865 /* at this time a bit annoying */
866 if (opt.debug & DBG_MEMSTAT_VALUE)
868 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
869 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
871 if (opt.debug)
872 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
873 #endif
874 gcry_control (GCRYCTL_TERM_SECMEM );
875 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
876 exit (rc);
880 static void
881 scd_init_default_ctrl (ctrl_t ctrl)
883 ctrl->reader_slot = -1;
886 static void
887 scd_deinit_default_ctrl (ctrl_t ctrl)
889 (void)ctrl;
893 /* Return the name of the socket to be used to connect to this
894 process. If no socket is available, return NULL. */
895 const char *
896 scd_get_socket_name ()
898 if (socket_name && *socket_name)
899 return socket_name;
900 return NULL;
904 static void
905 handle_signal (int signo)
907 switch (signo)
909 #ifndef HAVE_W32_SYSTEM
910 case SIGHUP:
911 log_info ("SIGHUP received - "
912 "re-reading configuration and resetting cards\n");
913 /* reread_configuration (); */
914 break;
916 case SIGUSR1:
917 log_info ("SIGUSR1 received - printing internal information:\n");
918 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
919 app_dump_state ();
920 break;
922 case SIGUSR2:
923 log_info ("SIGUSR2 received - no action defined\n");
924 break;
926 case SIGTERM:
927 if (!shutdown_pending)
928 log_info ("SIGTERM received - shutting down ...\n");
929 else
930 log_info ("SIGTERM received - still %ld running threads\n",
931 pth_ctrl( PTH_CTRL_GETTHREADS ));
932 shutdown_pending++;
933 if (shutdown_pending > 2)
935 log_info ("shutdown forced\n");
936 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
937 cleanup ();
938 scd_exit (0);
940 break;
942 case SIGINT:
943 log_info ("SIGINT received - immediate shutdown\n");
944 log_info( "%s %s stopped\n", strusage(11), strusage(13));
945 cleanup ();
946 scd_exit (0);
947 break;
948 #endif /*!HAVE_W32_SYSTEM*/
950 default:
951 log_info ("signal %d received - no action defined\n", signo);
956 static void
957 handle_tick (void)
959 if (!ticker_disabled)
960 scd_update_reader_status_file ();
964 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
965 true using STANDARD_NAME in the home directory or if given has
966 false from the mkdir type name TEMPLATE. In the latter case a
967 unique name in a unique new directory will be created. In both
968 cases check for valid characters as well as against a maximum
969 allowed length for a unix domain socket is done. The function
970 terminates the process in case of an error. Retunrs: Pointer to an
971 allcoated string with the absolute name of the socket used. */
972 static char *
973 create_socket_name (int use_standard_socket,
974 char *standard_name, char *template)
976 char *name, *p;
978 if (use_standard_socket)
979 name = make_filename (opt.homedir, standard_name, NULL);
980 else
982 name = xstrdup (template);
983 p = strrchr (name, '/');
984 if (!p)
985 BUG ();
986 *p = 0;
987 if (!mkdtemp (name))
989 log_error (_("can't create directory `%s': %s\n"),
990 name, strerror (errno));
991 scd_exit (2);
993 *p = '/';
996 if (strchr (name, PATHSEP_C))
998 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
999 scd_exit (2);
1001 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1003 log_error (_("name of socket too long\n"));
1004 scd_exit (2);
1006 return name;
1011 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1012 whether a non-random socket is used. Returns the file descriptor
1013 or terminates the process in case of an error. */
1014 static gnupg_fd_t
1015 create_server_socket (int is_standard_name, const char *name,
1016 assuan_sock_nonce_t *nonce)
1018 struct sockaddr_un *serv_addr;
1019 socklen_t len;
1020 gnupg_fd_t fd;
1021 int rc;
1023 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1024 if (fd == GNUPG_INVALID_FD)
1026 log_error (_("can't create socket: %s\n"), strerror (errno));
1027 scd_exit (2);
1030 serv_addr = xmalloc (sizeof (*serv_addr));
1031 memset (serv_addr, 0, sizeof *serv_addr);
1032 serv_addr->sun_family = AF_UNIX;
1033 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
1034 strcpy (serv_addr->sun_path, name);
1035 len = (offsetof (struct sockaddr_un, sun_path)
1036 + strlen (serv_addr->sun_path) + 1);
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));