[scd] Memory leak fix.
[gnupg.git] / scd / scdaemon.c
blob5823c9948c0b6a9d848bc5a03ec3a42887f46d4f
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"
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 ASSUAN_SYSTEM_PTH_IMPL;
208 GCRY_THREAD_OPTION_PTH_IMPL;
209 static int fixed_gcry_pth_init (void)
211 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
216 static char *
217 make_libversion (const char *libname, const char *(*getfnc)(const char*))
219 const char *s;
220 char *result;
222 if (maybe_setuid)
224 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
225 maybe_setuid = 0;
227 s = getfnc (NULL);
228 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
229 strcpy (stpcpy (stpcpy (result, libname), " "), s);
230 return result;
234 static const char *
235 my_strusage (int level)
237 static char *ver_gcry, *ver_ksba;
238 const char *p;
240 switch (level)
242 case 11: p = "scdaemon (GnuPG)";
243 break;
244 case 13: p = VERSION; break;
245 case 17: p = PRINTABLE_OS_NAME; break;
246 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
248 case 20:
249 if (!ver_gcry)
250 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
251 p = ver_gcry;
252 break;
253 case 21:
254 if (!ver_ksba)
255 ver_ksba = make_libversion ("libksba", ksba_check_version);
256 p = ver_ksba;
257 break;
258 case 1:
259 case 40: p = _("Usage: scdaemon [options] (-h for help)");
260 break;
261 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
262 "Smartcard daemon for GnuPG\n");
263 break;
265 default: p = NULL;
267 return p;
271 static unsigned long
272 tid_log_callback (void)
274 #ifdef PTH_HAVE_PTH_THREAD_ID
275 return pth_thread_id ();
276 #else
277 return (unsigned long)pth_self ();
278 #endif
285 /* Setup the debugging. With a LEVEL of NULL only the active debug
286 flags are propagated to the subsystems. With LEVEL set, a specific
287 set of debug flags is set; thus overriding all flags already
288 set. */
289 static void
290 set_debug (const char *level)
292 if (!level)
294 else if (!strcmp (level, "none"))
295 opt.debug = 0;
296 else if (!strcmp (level, "basic"))
297 opt.debug = DBG_ASSUAN_VALUE;
298 else if (!strcmp (level, "advanced"))
299 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
300 else if (!strcmp (level, "expert"))
301 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
302 |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
303 else if (!strcmp (level, "guru"))
304 opt.debug = ~0;
305 else
307 log_error (_("invalid debug-level `%s' given\n"), level);
308 scd_exit(2);
312 if (opt.debug && !opt.verbose)
313 opt.verbose = 1;
314 if (opt.debug && opt.quiet)
315 opt.quiet = 0;
317 if (opt.debug & DBG_MPI_VALUE)
318 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
319 if (opt.debug & DBG_CRYPTO_VALUE )
320 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
321 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
326 static void
327 cleanup (void)
329 if (socket_name && *socket_name)
331 char *p;
333 remove (socket_name);
334 p = strrchr (socket_name, '/');
335 if (p)
337 *p = 0;
338 rmdir (socket_name);
339 *p = '/';
341 *socket_name = 0;
348 main (int argc, char **argv )
350 ARGPARSE_ARGS pargs;
351 int orig_argc;
352 gpg_error_t err;
353 int may_coredump;
354 char **orig_argv;
355 FILE *configfp = NULL;
356 char *configname = NULL;
357 const char *shell;
358 unsigned int configlineno;
359 int parse_debug = 0;
360 const char *debug_level = NULL;
361 int default_config =1;
362 int greeting = 0;
363 int nogreeting = 0;
364 int multi_server = 0;
365 int is_daemon = 0;
366 int nodetach = 0;
367 int csh_style = 0;
368 char *logfile = NULL;
369 int debug_wait = 0;
370 int gpgconf_list = 0;
371 const char *config_filename = NULL;
372 int allow_coredump = 0;
373 int standard_socket = 0;
374 struct assuan_malloc_hooks malloc_hooks;
376 set_strusage (my_strusage);
377 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
378 /* Please note that we may running SUID(ROOT), so be very CAREFUL
379 when adding any stuff between here and the call to INIT_SECMEM()
380 somewhere after the option parsing */
381 log_set_prefix ("scdaemon", 1|4);
383 /* Make sure that our subsystems are ready. */
384 i18n_init ();
385 init_common_subsystems ();
388 /* Libgcrypt requires us to register the threading model first.
389 Note that this will also do the pth_init. */
390 gcry_threads_pth.init = fixed_gcry_pth_init;
391 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
392 if (err)
394 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
395 gpg_strerror (err));
398 /* Check that the libraries are suitable. Do it here because
399 the option parsing may need services of the library */
400 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
402 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
403 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
406 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
408 malloc_hooks.malloc = gcry_malloc;
409 malloc_hooks.realloc = gcry_realloc;
410 malloc_hooks.free = gcry_free;
411 assuan_set_malloc_hooks (&malloc_hooks);
412 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
413 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
414 assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
415 assuan_sock_init ();
417 setup_libgcrypt_logging ();
418 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
420 may_coredump = disable_core_dumps ();
422 /* Set default options. */
423 opt.allow_admin = 1;
424 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
426 #ifdef HAVE_W32_SYSTEM
427 standard_socket = 1; /* Under Windows we always use a standard
428 socket. */
429 #endif
432 shell = getenv ("SHELL");
433 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
434 csh_style = 1;
436 opt.homedir = default_homedir ();
438 /* Check whether we have a config file on the commandline */
439 orig_argc = argc;
440 orig_argv = argv;
441 pargs.argc = &argc;
442 pargs.argv = &argv;
443 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
444 while (arg_parse( &pargs, opts))
446 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
447 parse_debug++;
448 else if (pargs.r_opt == oOptions)
449 { /* yes there is one, so we do not try the default one, but
450 read the option file when it is encountered at the
451 commandline */
452 default_config = 0;
454 else if (pargs.r_opt == oNoOptions)
455 default_config = 0; /* --no-options */
456 else if (pargs.r_opt == oHomedir)
457 opt.homedir = pargs.r.ret_str;
460 /* initialize the secure memory. */
461 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
462 maybe_setuid = 0;
465 Now we are working under our real uid
469 if (default_config)
470 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
473 argc = orig_argc;
474 argv = orig_argv;
475 pargs.argc = &argc;
476 pargs.argv = &argv;
477 pargs.flags= 1; /* do not remove the args */
478 next_pass:
479 if (configname)
481 configlineno = 0;
482 configfp = fopen (configname, "r");
483 if (!configfp)
485 if (default_config)
487 if( parse_debug )
488 log_info (_("NOTE: no default option file `%s'\n"),
489 configname );
491 else
493 log_error (_("option file `%s': %s\n"),
494 configname, strerror(errno) );
495 exit(2);
497 xfree (configname);
498 configname = NULL;
500 if (parse_debug && configname )
501 log_info (_("reading options from `%s'\n"), configname );
502 default_config = 0;
505 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
507 switch (pargs.r_opt)
509 case aGPGConfList: gpgconf_list = 1; break;
510 case aGPGConfTest: gpgconf_list = 2; break;
511 case oQuiet: opt.quiet = 1; break;
512 case oVerbose: opt.verbose++; break;
513 case oBatch: opt.batch=1; break;
515 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
516 case oDebugAll: opt.debug = ~0; break;
517 case oDebugLevel: debug_level = pargs.r.ret_str; break;
518 case oDebugWait: debug_wait = pargs.r.ret_int; break;
519 case oDebugAllowCoreDump:
520 enable_core_dumps ();
521 allow_coredump = 1;
522 break;
523 case oDebugCCIDDriver:
524 #ifdef HAVE_LIBUSB
525 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
526 #endif /*HAVE_LIBUSB*/
527 break;
528 case oDebugDisableTicker: ticker_disabled = 1; break;
529 case oDebugLogTid:
530 log_set_get_tid_callback (tid_log_callback);
531 break;
533 case oOptions:
534 /* config files may not be nested (silently ignore them) */
535 if (!configfp)
537 xfree(configname);
538 configname = xstrdup(pargs.r.ret_str);
539 goto next_pass;
541 break;
542 case oNoGreeting: nogreeting = 1; break;
543 case oNoVerbose: opt.verbose = 0; break;
544 case oNoOptions: break; /* no-options */
545 case oHomedir: opt.homedir = pargs.r.ret_str; break;
546 case oNoDetach: nodetach = 1; break;
547 case oLogFile: logfile = pargs.r.ret_str; break;
548 case oCsh: csh_style = 1; break;
549 case oSh: csh_style = 0; break;
550 case oServer: pipe_server = 1; break;
551 case oMultiServer: pipe_server = 1; multi_server = 1; break;
552 case oDaemon: is_daemon = 1; break;
554 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
555 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
556 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
557 case oDisableCCID: opt.disable_ccid = 1; break;
558 case oDisableOpenSC: break;
560 case oDisableKeypad: opt.disable_keypad = 1; break;
562 case oAllowAdmin: /* Dummy because allow is now the default. */
563 break;
564 case oDenyAdmin: opt.allow_admin = 0; break;
566 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
568 case oDisableApplication:
569 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
570 break;
572 default:
573 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
574 break;
577 if (configfp)
579 fclose( configfp );
580 configfp = NULL;
581 /* Keep a copy of the config name for use by --gpgconf-list. */
582 config_filename = configname;
583 configname = NULL;
584 goto next_pass;
586 xfree (configname);
587 configname = NULL;
588 if (log_get_errorcount(0))
589 exit(2);
590 if (nogreeting )
591 greeting = 0;
593 if (greeting)
595 fprintf (stderr, "%s %s; %s\n",
596 strusage(11), strusage(13), strusage(14) );
597 fprintf (stderr, "%s\n", strusage(15) );
599 #ifdef IS_DEVELOPMENT_VERSION
600 log_info ("NOTE: this is a development version!\n");
601 #endif
604 if (atexit (cleanup))
606 log_error ("atexit failed\n");
607 cleanup ();
608 exit (1);
611 set_debug (debug_level);
613 initialize_module_command ();
615 if (gpgconf_list == 2)
616 scd_exit (0);
617 if (gpgconf_list)
619 /* List options and default values in the GPG Conf format. */
620 char *filename = NULL;
621 char *filename_esc;
623 if (config_filename)
624 filename = xstrdup (config_filename);
625 else
626 filename = make_filename (opt.homedir, "scdaemon.conf", NULL);
627 filename_esc = percent_escape (filename, NULL);
629 printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
630 GC_OPT_FLAG_DEFAULT, filename_esc);
631 xfree (filename_esc);
632 xfree (filename);
634 printf ("verbose:%lu:\n"
635 "quiet:%lu:\n"
636 "debug-level:%lu:\"none:\n"
637 "log-file:%lu:\n",
638 GC_OPT_FLAG_NONE,
639 GC_OPT_FLAG_NONE,
640 GC_OPT_FLAG_DEFAULT,
641 GC_OPT_FLAG_NONE );
643 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
644 printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
645 printf ("pcsc-driver:%lu:\"%s:\n",
646 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
647 #ifdef HAVE_LIBUSB
648 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
649 #endif
650 printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
651 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
652 printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
654 scd_exit (0);
657 /* Now start with logging to a file if this is desired. */
658 if (logfile)
660 log_set_file (logfile);
661 log_set_prefix (NULL, 1|2|4);
664 if (debug_wait && pipe_server)
666 log_debug ("waiting for debugger - my pid is %u .....\n",
667 (unsigned int)getpid());
668 gnupg_sleep (debug_wait);
669 log_debug ("... okay\n");
672 if (pipe_server)
674 /* This is the simple pipe based server */
675 ctrl_t ctrl;
676 pth_attr_t tattr;
677 int fd = -1;
679 #ifndef HAVE_W32_SYSTEM
681 struct sigaction sa;
683 sa.sa_handler = SIG_IGN;
684 sigemptyset (&sa.sa_mask);
685 sa.sa_flags = 0;
686 sigaction (SIGPIPE, &sa, NULL);
688 #endif
690 /* If --debug-allow-core-dump has been given we also need to
691 switch the working directory to a place where we can actually
692 write. */
693 if (allow_coredump)
695 if (chdir("/tmp"))
696 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
697 else
698 log_debug ("changed working directory to `/tmp'\n");
701 /* In multi server mode we need to listen on an additional
702 socket. Create that socket now before starting the handler
703 for the pipe connection. This allows that handler to send
704 back the name of that socket. */
705 if (multi_server)
707 socket_name = create_socket_name (standard_socket,
708 "S.scdaemon",
709 "/tmp/gpg-XXXXXX/S.scdaemon");
711 fd = FD2INT(create_server_socket (standard_socket,
712 socket_name, &socket_nonce));
715 tattr = pth_attr_new();
716 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
717 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
718 pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
720 ctrl = xtrycalloc (1, sizeof *ctrl);
721 if ( !ctrl )
723 log_error ("error allocating connection control data: %s\n",
724 strerror (errno) );
725 scd_exit (2);
727 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
728 if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
730 log_error ("error spawning pipe connection handler: %s\n",
731 strerror (errno) );
732 xfree (ctrl);
733 scd_exit (2);
736 /* We run handle_connection to wait for the shutdown signal and
737 to run the ticker stuff. */
738 handle_connections (fd);
739 if (fd != -1)
740 close (fd);
742 else if (!is_daemon)
744 log_info (_("please use the option `--daemon'"
745 " to run the program in the background\n"));
747 else
748 { /* Regular server mode */
749 int fd;
750 #ifndef HAVE_W32_SYSTEM
751 pid_t pid;
752 int i;
753 #endif
755 /* Create the socket. */
756 socket_name = create_socket_name (standard_socket,
757 "S.scdaemon",
758 "/tmp/gpg-XXXXXX/S.scdaemon");
760 fd = FD2INT (create_server_socket (standard_socket,
761 socket_name, &socket_nonce));
764 fflush (NULL);
765 #ifndef HAVE_W32_SYSTEM
766 pid = fork ();
767 if (pid == (pid_t)-1)
769 log_fatal ("fork failed: %s\n", strerror (errno) );
770 exit (1);
772 else if (pid)
773 { /* we are the parent */
774 char *infostr;
776 close (fd);
778 /* create the info string: <name>:<pid>:<protocol_version> */
779 if (estream_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
780 socket_name, (ulong) pid) < 0)
782 log_error ("out of core\n");
783 kill (pid, SIGTERM);
784 exit (1);
786 *socket_name = 0; /* don't let cleanup() remove the socket -
787 the child should do this from now on */
788 if (argc)
789 { /* run the program given on the commandline */
790 if (putenv (infostr))
792 log_error ("failed to set environment: %s\n",
793 strerror (errno) );
794 kill (pid, SIGTERM );
795 exit (1);
797 execvp (argv[0], argv);
798 log_error ("failed to run the command: %s\n", strerror (errno));
799 kill (pid, SIGTERM);
800 exit (1);
802 else
804 /* Print the environment string, so that the caller can use
805 shell's eval to set it */
806 if (csh_style)
808 *strchr (infostr, '=') = ' ';
809 printf ( "setenv %s\n", infostr);
811 else
813 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
815 xfree (infostr);
816 exit (0);
818 /* NOTREACHED */
819 } /* end parent */
821 /* This is the child. */
823 /* Detach from tty and put process into a new session. */
824 if (!nodetach )
826 /* Close stdin, stdout and stderr unless it is the log stream. */
827 for (i=0; i <= 2; i++)
829 if ( log_test_fd (i) && i != fd)
830 close (i);
832 if (setsid() == -1)
834 log_error ("setsid() failed: %s\n", strerror(errno) );
835 cleanup ();
836 exit (1);
841 struct sigaction sa;
843 sa.sa_handler = SIG_IGN;
844 sigemptyset (&sa.sa_mask);
845 sa.sa_flags = 0;
846 sigaction (SIGPIPE, &sa, NULL);
849 if (chdir("/"))
851 log_error ("chdir to / failed: %s\n", strerror (errno));
852 exit (1);
855 #endif /*!HAVE_W32_SYSTEM*/
857 handle_connections (fd);
859 close (fd);
862 return 0;
865 void
866 scd_exit (int rc)
868 apdu_prepare_exit ();
869 #if 0
870 #warning no update_random_seed_file
871 update_random_seed_file();
872 #endif
873 #if 0
874 /* at this time a bit annoying */
875 if (opt.debug & DBG_MEMSTAT_VALUE)
877 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
878 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
880 if (opt.debug)
881 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
882 #endif
883 gcry_control (GCRYCTL_TERM_SECMEM );
884 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
885 exit (rc);
889 static void
890 scd_init_default_ctrl (ctrl_t ctrl)
892 ctrl->reader_slot = -1;
895 static void
896 scd_deinit_default_ctrl (ctrl_t ctrl)
898 if (!ctrl)
899 return;
900 xfree (ctrl->in_data.value);
901 ctrl->in_data.value = NULL;
902 ctrl->in_data.valuelen = 0;
906 /* Return the name of the socket to be used to connect to this
907 process. If no socket is available, return NULL. */
908 const char *
909 scd_get_socket_name ()
911 if (socket_name && *socket_name)
912 return socket_name;
913 return NULL;
917 static void
918 handle_signal (int signo)
920 switch (signo)
922 #ifndef HAVE_W32_SYSTEM
923 case SIGHUP:
924 log_info ("SIGHUP received - "
925 "re-reading configuration and resetting cards\n");
926 /* reread_configuration (); */
927 break;
929 case SIGUSR1:
930 log_info ("SIGUSR1 received - printing internal information:\n");
931 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
932 app_dump_state ();
933 break;
935 case SIGUSR2:
936 log_info ("SIGUSR2 received - no action defined\n");
937 break;
939 case SIGTERM:
940 if (!shutdown_pending)
941 log_info ("SIGTERM received - shutting down ...\n");
942 else
943 log_info ("SIGTERM received - still %ld running threads\n",
944 pth_ctrl( PTH_CTRL_GETTHREADS ));
945 shutdown_pending++;
946 if (shutdown_pending > 2)
948 log_info ("shutdown forced\n");
949 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
950 cleanup ();
951 scd_exit (0);
953 break;
955 case SIGINT:
956 log_info ("SIGINT received - immediate shutdown\n");
957 log_info( "%s %s stopped\n", strusage(11), strusage(13));
958 cleanup ();
959 scd_exit (0);
960 break;
961 #endif /*!HAVE_W32_SYSTEM*/
963 default:
964 log_info ("signal %d received - no action defined\n", signo);
969 static void
970 handle_tick (void)
972 if (!ticker_disabled)
973 scd_update_reader_status_file ();
977 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
978 true using STANDARD_NAME in the home directory or if given has
979 false from the mkdir type name TEMPLATE. In the latter case a
980 unique name in a unique new directory will be created. In both
981 cases check for valid characters as well as against a maximum
982 allowed length for a unix domain socket is done. The function
983 terminates the process in case of an error. Retunrs: Pointer to an
984 allcoated string with the absolute name of the socket used. */
985 static char *
986 create_socket_name (int use_standard_socket,
987 char *standard_name, char *template)
989 char *name, *p;
991 if (use_standard_socket)
992 name = make_filename (opt.homedir, standard_name, NULL);
993 else
995 name = xstrdup (template);
996 p = strrchr (name, '/');
997 if (!p)
998 BUG ();
999 *p = 0;
1000 if (!mkdtemp (name))
1002 log_error (_("can't create directory `%s': %s\n"),
1003 name, strerror (errno));
1004 scd_exit (2);
1006 *p = '/';
1009 if (strchr (name, PATHSEP_C))
1011 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1012 scd_exit (2);
1014 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1016 log_error (_("name of socket too long\n"));
1017 scd_exit (2);
1019 return name;
1024 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1025 whether a non-random socket is used. Returns the file descriptor
1026 or terminates the process in case of an error. */
1027 static gnupg_fd_t
1028 create_server_socket (int is_standard_name, const char *name,
1029 assuan_sock_nonce_t *nonce)
1031 struct sockaddr_un *serv_addr;
1032 socklen_t len;
1033 gnupg_fd_t fd;
1034 int rc;
1036 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1037 if (fd == GNUPG_INVALID_FD)
1039 log_error (_("can't create socket: %s\n"), strerror (errno));
1040 scd_exit (2);
1043 serv_addr = xmalloc (sizeof (*serv_addr));
1044 memset (serv_addr, 0, sizeof *serv_addr);
1045 serv_addr->sun_family = AF_UNIX;
1046 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
1047 strcpy (serv_addr->sun_path, name);
1048 len = SUN_LEN (serv_addr);
1050 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1051 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
1053 remove (name);
1054 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1056 if (rc != -1
1057 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1058 log_error (_("error getting nonce for the socket\n"));
1059 if (rc == -1)
1061 log_error (_("error binding socket to `%s': %s\n"),
1062 serv_addr->sun_path,
1063 gpg_strerror (gpg_error_from_syserror ()));
1064 assuan_sock_close (fd);
1065 scd_exit (2);
1068 if (listen (FD2INT(fd), 5 ) == -1)
1070 log_error (_("listen() failed: %s\n"),
1071 gpg_strerror (gpg_error_from_syserror ()));
1072 assuan_sock_close (fd);
1073 scd_exit (2);
1076 if (opt.verbose)
1077 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1079 return fd;
1084 /* This is the standard connection thread's main function. */
1085 static void *
1086 start_connection_thread (void *arg)
1088 ctrl_t ctrl = arg;
1090 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1091 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1093 log_info (_("error reading nonce on fd %d: %s\n"),
1094 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1095 assuan_sock_close (ctrl->thread_startup.fd);
1096 xfree (ctrl);
1097 return NULL;
1100 scd_init_default_ctrl (ctrl);
1101 if (opt.verbose)
1102 log_info (_("handler for fd %d started\n"),
1103 FD2INT(ctrl->thread_startup.fd));
1105 /* If this is a pipe server, we request a shutdown if the command
1106 handler asked for it. With the next ticker event and given that
1107 no other connections are running the shutdown will then
1108 happen. */
1109 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1110 && pipe_server)
1111 shutdown_pending = 1;
1113 if (opt.verbose)
1114 log_info (_("handler for fd %d terminated\n"),
1115 FD2INT (ctrl->thread_startup.fd));
1117 scd_deinit_default_ctrl (ctrl);
1118 xfree (ctrl);
1119 return NULL;
1123 /* Connection handler loop. Wait for connection requests and spawn a
1124 thread after accepting a connection. LISTEN_FD is allowed to be -1
1125 in which case this code will only do regular timeouts and handle
1126 signals. */
1127 static void
1128 handle_connections (int listen_fd)
1130 pth_attr_t tattr;
1131 pth_event_t ev, time_ev;
1132 sigset_t sigs;
1133 int signo;
1134 struct sockaddr_un paddr;
1135 socklen_t plen;
1136 fd_set fdset, read_fdset;
1137 int ret;
1138 int fd;
1139 int nfd;
1141 tattr = pth_attr_new();
1142 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1143 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
1145 #ifndef HAVE_W32_SYSTEM /* fixme */
1146 sigemptyset (&sigs );
1147 sigaddset (&sigs, SIGHUP);
1148 sigaddset (&sigs, SIGUSR1);
1149 sigaddset (&sigs, SIGUSR2);
1150 sigaddset (&sigs, SIGINT);
1151 sigaddset (&sigs, SIGTERM);
1152 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1153 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1154 #else
1155 sigs = 0;
1156 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1157 #endif
1158 time_ev = NULL;
1160 FD_ZERO (&fdset);
1161 nfd = 0;
1162 if (listen_fd != -1)
1164 FD_SET (listen_fd, &fdset);
1165 nfd = listen_fd;
1168 for (;;)
1170 sigset_t oldsigs;
1172 if (shutdown_pending)
1174 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1175 break; /* ready */
1177 /* Do not accept anymore connections but wait for existing
1178 connections to terminate. We do this by clearing out all
1179 file descriptors to wait for, so that the select will be
1180 used to just wait on a signal or timeout event. */
1181 FD_ZERO (&fdset);
1182 listen_fd = -1;
1185 /* Create a timeout event if needed. Round it up to the next
1186 microsecond interval to help with power saving. */
1187 if (!time_ev)
1189 pth_time_t nexttick = pth_timeout (TIMERTICK_INTERVAL_SEC,
1190 TIMERTICK_INTERVAL_USEC/2);
1191 if ((nexttick.tv_usec % (TIMERTICK_INTERVAL_USEC/2)) > 10)
1193 nexttick.tv_usec = ((nexttick.tv_usec
1194 /(TIMERTICK_INTERVAL_USEC/2))
1195 + 1) * (TIMERTICK_INTERVAL_USEC/2);
1196 if (nexttick.tv_usec >= 1000000)
1198 nexttick.tv_sec++;
1199 nexttick.tv_usec = 0;
1202 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1205 /* POSIX says that fd_set should be implemented as a structure,
1206 thus a simple assignment is fine to copy the entire set. */
1207 read_fdset = fdset;
1209 if (time_ev)
1210 pth_event_concat (ev, time_ev, NULL);
1211 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1212 if (time_ev)
1213 pth_event_isolate (time_ev);
1215 if (ret == -1)
1217 if (pth_event_occurred (ev)
1218 || (time_ev && pth_event_occurred (time_ev)))
1220 if (pth_event_occurred (ev))
1221 handle_signal (signo);
1222 if (time_ev && pth_event_occurred (time_ev))
1224 pth_event_free (time_ev, PTH_FREE_ALL);
1225 time_ev = NULL;
1226 handle_tick ();
1228 continue;
1230 log_error (_("pth_select failed: %s - waiting 1s\n"),
1231 strerror (errno));
1232 pth_sleep (1);
1233 continue;
1236 if (pth_event_occurred (ev))
1238 handle_signal (signo);
1241 if (time_ev && pth_event_occurred (time_ev))
1243 pth_event_free (time_ev, PTH_FREE_ALL);
1244 time_ev = NULL;
1245 handle_tick ();
1248 /* We now might create new threads and because we don't want any
1249 signals - we are handling here - to be delivered to a new
1250 thread. Thus we need to block those signals. */
1251 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1253 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1255 ctrl_t ctrl;
1257 plen = sizeof paddr;
1258 fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1259 if (fd == -1)
1261 log_error ("accept failed: %s\n", strerror (errno));
1263 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1265 log_error ("error allocating connection control data: %s\n",
1266 strerror (errno) );
1267 close (fd);
1269 else
1271 char threadname[50];
1273 snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd);
1274 threadname[sizeof threadname -1] = 0;
1275 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1276 ctrl->thread_startup.fd = INT2FD (fd);
1277 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1279 log_error ("error spawning connection handler: %s\n",
1280 strerror (errno) );
1281 xfree (ctrl);
1282 close (fd);
1285 fd = -1;
1288 /* Restore the signal mask. */
1289 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1293 pth_event_free (ev, PTH_FREE_ALL);
1294 if (time_ev)
1295 pth_event_free (time_ev, PTH_FREE_ALL);
1296 cleanup ();
1297 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));