2007-09-14 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / scdaemon.c
blob34f6e70d2411aea85a49405af3a76e6096dff7ef
1 /* scdaemon.c - The GnuPG Smartcard Daemon
2 * Copyright (C) 2001, 2002, 2004, 2005,
3 * 2007 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 #ifdef HAVE_W32_SYSTEM
51 #include "../jnlib/w32-afunix.h"
52 #endif
53 #include "ccid-driver.h"
54 #include "mkdtemp.h"
55 #include "gc-opt-flags.h"
58 enum cmd_and_opt_values
59 { aNull = 0,
60 oCsh = 'c',
61 oQuiet = 'q',
62 oSh = 's',
63 oVerbose = 'v',
65 oNoVerbose = 500,
66 aGPGConfList,
67 aGPGConfTest,
68 oOptions,
69 oDebug,
70 oDebugAll,
71 oDebugLevel,
72 oDebugWait,
73 oDebugAllowCoreDump,
74 oDebugCCIDDriver,
75 oNoGreeting,
76 oNoOptions,
77 oHomedir,
78 oNoDetach,
79 oNoGrab,
80 oLogFile,
81 oServer,
82 oMultiServer,
83 oDaemon,
84 oBatch,
85 oReaderPort,
86 octapiDriver,
87 opcscDriver,
88 oDisableCCID,
89 oDisableOpenSC,
90 oDisableKeypad,
91 oAllowAdmin,
92 oDenyAdmin,
93 oDisableApplication,
94 oDebugDisableTicker
99 static ARGPARSE_OPTS opts[] = {
101 { aGPGConfList, "gpgconf-list", 256, "@" },
102 { aGPGConfTest, "gpgconf-test", 256, "@" },
104 { 301, NULL, 0, N_("@Options:\n ") },
106 { oServer, "server", 0, N_("run in server mode (foreground)") },
107 { oMultiServer, "multi-server", 0,
108 N_("run in multi server mode (foreground)") },
109 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
110 { oVerbose, "verbose", 0, N_("verbose") },
111 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
112 { oSh, "sh", 0, N_("sh-style command output") },
113 { oCsh, "csh", 0, N_("csh-style command output") },
114 { oOptions, "options" , 2, N_("read options from file")},
115 { oDebug, "debug" ,4|16, "@"},
116 { oDebugAll, "debug-all" ,0, "@"},
117 { oDebugLevel, "debug-level" ,2, "@"},
118 { oDebugWait,"debug-wait",1, "@"},
119 { oDebugAllowCoreDump, "debug-allow-core-dump", 0, "@" },
120 { oDebugCCIDDriver, "debug-ccid-driver", 0, "@"},
121 { oDebugDisableTicker, "debug-disable-ticker", 0, "@"},
122 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
123 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
124 { oReaderPort, "reader-port", 2, N_("|N|connect to reader at port N")},
125 { octapiDriver, "ctapi-driver", 2, N_("|NAME|use NAME as ct-API driver")},
126 { opcscDriver, "pcsc-driver", 2, N_("|NAME|use NAME as PC/SC driver")},
127 { oDisableCCID, "disable-ccid", 0,
128 #ifdef HAVE_LIBUSB
129 N_("do not use the internal CCID driver")
130 #else
132 #endif
133 /* end --disable-ccid */},
134 { oDisableKeypad, "disable-keypad", 0, N_("do not use a reader's keypad")},
135 { oAllowAdmin, "allow-admin", 0, N_("allow the use of admin card commands")},
136 { oDenyAdmin, "deny-admin", 0, "@" },
137 { oDisableApplication, "disable-application", 2, "@"},
143 /* The card driver we use by default for PC/SC. */
144 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
145 #define DEFAULT_PCSC_DRIVER "winscard.dll"
146 #elif defined(__APPLE__)
147 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
148 #elif defined(__GLIBC__)
149 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
150 #else
151 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
152 #endif
154 /* The timer tick used for housekeeping stuff. For Windows we use a
155 longer period as the SetWaitableTimer seems to signal earlier than
156 the 2 seconds. */
157 #ifdef HAVE_W32_SYSTEM
158 #define TIMERTICK_INTERVAL (4)
159 #else
160 #define TIMERTICK_INTERVAL (2) /* Seconds. */
161 #endif
164 /* Flag to indicate that a shutdown was requested. */
165 static int shutdown_pending;
167 /* It is possible that we are currently running under setuid permissions */
168 static int maybe_setuid = 1;
170 /* Name of the communication socket */
171 static char *socket_name;
174 /* Debug flag to disable the ticker. The ticker is in fact not
175 disabled but it won't perform any ticker specific actions. */
176 static int ticker_disabled;
180 static char *create_socket_name (int use_standard_socket,
181 char *standard_name, char *template);
182 static int create_server_socket (int is_standard_name, const char *name);
184 static void *start_connection_thread (void *arg);
185 static void handle_connections (int listen_fd);
187 /* Pth wrapper function definitions. */
188 GCRY_THREAD_OPTION_PTH_IMPL;
189 static int fixed_gcry_pth_init (void)
191 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
196 static const char *
197 my_strusage (int level)
199 const char *p;
200 switch (level)
202 case 11: p = "scdaemon (GnuPG)";
203 break;
204 case 13: p = VERSION; break;
205 case 17: p = PRINTABLE_OS_NAME; break;
206 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
207 break;
208 case 1:
209 case 40: p = _("Usage: scdaemon [options] (-h for help)");
210 break;
211 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
212 "Smartcard daemon for GnuPG\n");
213 break;
215 default: p = NULL;
217 return p;
224 /* Setup the debugging. With a LEVEL of NULL only the active debug
225 flags are propagated to the subsystems. With LEVEL set, a specific
226 set of debug flags is set; thus overriding all flags already
227 set. */
228 static void
229 set_debug (const char *level)
231 if (!level)
233 else if (!strcmp (level, "none"))
234 opt.debug = 0;
235 else if (!strcmp (level, "basic"))
236 opt.debug = DBG_ASSUAN_VALUE;
237 else if (!strcmp (level, "advanced"))
238 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
239 else if (!strcmp (level, "expert"))
240 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
241 |DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
242 else if (!strcmp (level, "guru"))
243 opt.debug = ~0;
244 else
246 log_error (_("invalid debug-level `%s' given\n"), level);
247 scd_exit(2);
251 if (opt.debug && !opt.verbose)
252 opt.verbose = 1;
253 if (opt.debug && opt.quiet)
254 opt.quiet = 0;
256 if (opt.debug & DBG_MPI_VALUE)
257 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
258 if (opt.debug & DBG_CRYPTO_VALUE )
259 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
260 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
265 static void
266 cleanup (void)
268 if (socket_name && *socket_name)
270 char *p;
272 remove (socket_name);
273 p = strrchr (socket_name, '/');
274 if (p)
276 *p = 0;
277 rmdir (socket_name);
278 *p = '/';
280 *socket_name = 0;
287 main (int argc, char **argv )
289 ARGPARSE_ARGS pargs;
290 int orig_argc;
291 gpg_error_t err;
292 int may_coredump;
293 char **orig_argv;
294 FILE *configfp = NULL;
295 char *configname = NULL;
296 const char *shell;
297 unsigned int configlineno;
298 int parse_debug = 0;
299 const char *debug_level = NULL;
300 int default_config =1;
301 int greeting = 0;
302 int nogreeting = 0;
303 int pipe_server = 0;
304 int multi_server = 0;
305 int is_daemon = 0;
306 int nodetach = 0;
307 int csh_style = 0;
308 char *logfile = NULL;
309 int debug_wait = 0;
310 int gpgconf_list = 0;
311 const char *config_filename = NULL;
312 int allow_coredump = 0;
314 set_strusage (my_strusage);
315 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
316 /* Please note that we may running SUID(ROOT), so be very CAREFUL
317 when adding any stuff between here and the call to INIT_SECMEM()
318 somewhere after the option parsing */
319 log_set_prefix ("scdaemon", 1|4);
321 /* Make sure that our subsystems are ready. */
322 init_common_subsystems ();
324 i18n_init ();
326 /* Libgcrypt requires us to register the threading model first.
327 Note that this will also do the pth_init. */
328 gcry_threads_pth.init = fixed_gcry_pth_init;
329 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
330 if (err)
332 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
333 gpg_strerror (err));
336 /* Check that the libraries are suitable. Do it here because
337 the option parsing may need services of the library */
338 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
340 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
341 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
344 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
346 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
347 assuan_set_assuan_log_stream (log_get_stream ());
348 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
349 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
351 setup_libgcrypt_logging ();
352 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
354 may_coredump = disable_core_dumps ();
356 /* Set default options. */
357 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
360 shell = getenv ("SHELL");
361 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
362 csh_style = 1;
364 opt.homedir = default_homedir ();
366 /* Check whether we have a config file on the commandline */
367 orig_argc = argc;
368 orig_argv = argv;
369 pargs.argc = &argc;
370 pargs.argv = &argv;
371 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
372 while (arg_parse( &pargs, opts))
374 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
375 parse_debug++;
376 else if (pargs.r_opt == oOptions)
377 { /* yes there is one, so we do not try the default one, but
378 read the option file when it is encountered at the
379 commandline */
380 default_config = 0;
382 else if (pargs.r_opt == oNoOptions)
383 default_config = 0; /* --no-options */
384 else if (pargs.r_opt == oHomedir)
385 opt.homedir = pargs.r.ret_str;
388 /* initialize the secure memory. */
389 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
390 maybe_setuid = 0;
393 Now we are working under our real uid
397 if (default_config)
398 configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
401 argc = orig_argc;
402 argv = orig_argv;
403 pargs.argc = &argc;
404 pargs.argv = &argv;
405 pargs.flags= 1; /* do not remove the args */
406 next_pass:
407 if (configname)
409 configlineno = 0;
410 configfp = fopen (configname, "r");
411 if (!configfp)
413 if (default_config)
415 if( parse_debug )
416 log_info (_("NOTE: no default option file `%s'\n"),
417 configname );
419 else
421 log_error (_("option file `%s': %s\n"),
422 configname, strerror(errno) );
423 exit(2);
425 xfree (configname);
426 configname = NULL;
428 if (parse_debug && configname )
429 log_info (_("reading options from `%s'\n"), configname );
430 default_config = 0;
433 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
435 switch (pargs.r_opt)
437 case aGPGConfList: gpgconf_list = 1; break;
438 case aGPGConfTest: gpgconf_list = 2; break;
439 case oQuiet: opt.quiet = 1; break;
440 case oVerbose: opt.verbose++; break;
441 case oBatch: opt.batch=1; break;
443 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
444 case oDebugAll: opt.debug = ~0; break;
445 case oDebugLevel: debug_level = pargs.r.ret_str; break;
446 case oDebugWait: debug_wait = pargs.r.ret_int; break;
447 case oDebugAllowCoreDump:
448 enable_core_dumps ();
449 allow_coredump = 1;
450 break;
451 case oDebugCCIDDriver:
452 #ifdef HAVE_LIBUSB
453 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
454 #endif /*HAVE_LIBUSB*/
455 break;
456 case oDebugDisableTicker: ticker_disabled = 1; break;
458 case oOptions:
459 /* config files may not be nested (silently ignore them) */
460 if (!configfp)
462 xfree(configname);
463 configname = xstrdup(pargs.r.ret_str);
464 goto next_pass;
466 break;
467 case oNoGreeting: nogreeting = 1; break;
468 case oNoVerbose: opt.verbose = 0; break;
469 case oNoOptions: break; /* no-options */
470 case oHomedir: opt.homedir = pargs.r.ret_str; break;
471 case oNoDetach: nodetach = 1; break;
472 case oLogFile: logfile = pargs.r.ret_str; break;
473 case oCsh: csh_style = 1; break;
474 case oSh: csh_style = 0; break;
475 case oServer: pipe_server = 1; break;
476 case oMultiServer: pipe_server = 1; multi_server = 1; break;
477 case oDaemon: is_daemon = 1; break;
479 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
480 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
481 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
482 case oDisableCCID: opt.disable_ccid = 1; break;
483 case oDisableOpenSC: break;
485 case oDisableKeypad: opt.disable_keypad = 1; break;
487 case oAllowAdmin: opt.allow_admin = 1; break;
488 case oDenyAdmin: opt.allow_admin = 0; break;
490 case oDisableApplication:
491 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
492 break;
494 default : pargs.err = configfp? 1:2; break;
497 if (configfp)
499 fclose( configfp );
500 configfp = NULL;
501 /* Keep a copy of the config name for use by --gpgconf-list. */
502 config_filename = configname;
503 configname = NULL;
504 goto next_pass;
506 xfree (configname);
507 configname = NULL;
508 if (log_get_errorcount(0))
509 exit(2);
510 if (nogreeting )
511 greeting = 0;
513 if (greeting)
515 fprintf (stderr, "%s %s; %s\n",
516 strusage(11), strusage(13), strusage(14) );
517 fprintf (stderr, "%s\n", strusage(15) );
519 #ifdef IS_DEVELOPMENT_VERSION
520 log_info ("NOTE: this is a development version!\n");
521 #endif
524 if (atexit (cleanup))
526 log_error ("atexit failed\n");
527 cleanup ();
528 exit (1);
531 set_debug (debug_level);
533 if (debug_wait && pipe_server)
535 log_debug ("waiting for debugger - my pid is %u .....\n",
536 (unsigned int)getpid());
537 gnupg_sleep (debug_wait);
538 log_debug ("... okay\n");
541 initialize_module_command ();
543 if (gpgconf_list == 2)
544 scd_exit (0);
545 if (gpgconf_list)
547 /* List options and default values in the GPG Conf format. */
548 char *filename = NULL;
549 char *filename_esc;
551 if (!config_filename)
552 filename = make_filename (opt.homedir, "scdaemon.conf", NULL );
553 filename_esc = percent_escape (filename, NULL);
555 printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
556 GC_OPT_FLAG_DEFAULT, filename_esc);
557 xfree (filename_esc);
558 xfree (filename);
560 printf ("verbose:%lu:\n"
561 "quiet:%lu:\n"
562 "debug-level:%lu:\"none:\n"
563 "log-file:%lu:\n",
564 GC_OPT_FLAG_NONE,
565 GC_OPT_FLAG_NONE,
566 GC_OPT_FLAG_DEFAULT,
567 GC_OPT_FLAG_NONE );
569 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
570 printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
571 printf ("pcsc-driver:%lu:\"%s:\n",
572 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
573 #ifdef HAVE_LIBUSB
574 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
575 #endif
576 printf ("allow-admin:%lu:\n", GC_OPT_FLAG_NONE );
577 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE );
579 scd_exit (0);
582 /* now start with logging to a file if this is desired */
583 if (logfile)
585 log_set_file (logfile);
586 log_set_prefix (NULL, 1|2|4);
589 if (pipe_server)
591 /* This is the simple pipe based server */
592 ctrl_t ctrl;
593 pth_attr_t tattr;
594 int fd = -1;
596 #ifndef HAVE_W32_SYSTEM
598 struct sigaction sa;
600 sa.sa_handler = SIG_IGN;
601 sigemptyset (&sa.sa_mask);
602 sa.sa_flags = 0;
603 sigaction (SIGPIPE, &sa, NULL);
605 #endif
607 /* If --debug-allow-core-dump has been given we also need to
608 switch the working directory to a place where we can actually
609 write. */
610 if (allow_coredump)
612 if (chdir("/tmp"))
613 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno));
614 else
615 log_debug ("changed working directory to `/tmp'\n");
618 /* In multi server mode we need to listen on an additional
619 socket. Create that socket now before starting the handler
620 for the pipe connection. This allows that handler to send
621 back the name of that socket. */
622 if (multi_server)
624 socket_name = create_socket_name (0,
625 "S.scdaemon",
626 "/tmp/gpg-XXXXXX/S.scdaemon");
628 fd = create_server_socket (0, socket_name);
631 tattr = pth_attr_new();
632 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
633 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
634 pth_attr_set (tattr, PTH_ATTR_NAME, "pipe-connection");
636 ctrl = xtrycalloc (1, sizeof *ctrl);
637 if ( !ctrl )
639 log_error ("error allocating connection control data: %s\n",
640 strerror (errno) );
641 scd_exit (2);
643 ctrl->thread_startup.fd = -1;
644 if ( !pth_spawn (tattr, start_connection_thread, ctrl) )
646 log_error ("error spawning pipe connection handler: %s\n",
647 strerror (errno) );
648 xfree (ctrl);
649 scd_exit (2);
652 handle_connections (fd);
653 if (fd != -1)
654 close (fd);
656 else if (!is_daemon)
658 log_info (_("please use the option `--daemon'"
659 " to run the program in the background\n"));
661 else
662 { /* Regular server mode */
663 int fd;
664 pid_t pid;
665 int i;
667 /* Create the socket. */
668 socket_name = create_socket_name (0,
669 "S.scdaemon",
670 "/tmp/gpg-XXXXXX/S.scdaemon");
672 fd = create_server_socket (0, socket_name);
675 fflush (NULL);
676 #ifndef HAVE_W32_SYSTEM
677 pid = fork ();
678 if (pid == (pid_t)-1)
680 log_fatal ("fork failed: %s\n", strerror (errno) );
681 exit (1);
683 else if (pid)
684 { /* we are the parent */
685 char *infostr;
687 close (fd);
689 /* create the info string: <name>:<pid>:<protocol_version> */
690 if (asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
691 socket_name, (ulong)pid ) < 0)
693 log_error ("out of core\n");
694 kill (pid, SIGTERM);
695 exit (1);
697 *socket_name = 0; /* don't let cleanup() remove the socket -
698 the child should do this from now on */
699 if (argc)
700 { /* run the program given on the commandline */
701 if (putenv (infostr))
703 log_error ("failed to set environment: %s\n",
704 strerror (errno) );
705 kill (pid, SIGTERM );
706 exit (1);
708 execvp (argv[0], argv);
709 log_error ("failed to run the command: %s\n", strerror (errno));
710 kill (pid, SIGTERM);
711 exit (1);
713 else
715 /* Print the environment string, so that the caller can use
716 shell's eval to set it */
717 if (csh_style)
719 *strchr (infostr, '=') = ' ';
720 printf ( "setenv %s\n", infostr);
722 else
724 printf ( "%s; export SCDAEMON_INFO;\n", infostr);
726 free (infostr);
727 exit (0);
729 /* NOTREACHED */
730 } /* end parent */
732 /* This is the child. */
734 /* Detach from tty and put process into a new session. */
735 if (!nodetach )
737 /* Close stdin, stdout and stderr unless it is the log stream. */
738 for (i=0; i <= 2; i++)
740 if ( log_test_fd (i) && i != fd)
741 close (i);
743 if (setsid() == -1)
745 log_error ("setsid() failed: %s\n", strerror(errno) );
746 cleanup ();
747 exit (1);
752 struct sigaction sa;
754 sa.sa_handler = SIG_IGN;
755 sigemptyset (&sa.sa_mask);
756 sa.sa_flags = 0;
757 sigaction (SIGPIPE, &sa, NULL);
760 if (chdir("/"))
762 log_error ("chdir to / failed: %s\n", strerror (errno));
763 exit (1);
766 #endif /*!HAVE_W32_SYSTEM*/
768 handle_connections (fd);
770 close (fd);
773 return 0;
776 void
777 scd_exit (int rc)
779 #if 0
780 #warning no update_random_seed_file
781 update_random_seed_file();
782 #endif
783 #if 0
784 /* at this time a bit annoying */
785 if (opt.debug & DBG_MEMSTAT_VALUE)
787 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
788 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
790 if (opt.debug)
791 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
792 #endif
793 gcry_control (GCRYCTL_TERM_SECMEM );
794 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
795 exit (rc);
799 static void
800 scd_init_default_ctrl (ctrl_t ctrl)
802 ctrl->reader_slot = -1;
805 static void
806 scd_deinit_default_ctrl (ctrl_t ctrl)
812 /* Return the name of the socket to be used to connect to this
813 process. If no socket is available, return NULL. */
814 const char *
815 scd_get_socket_name ()
817 if (socket_name && *socket_name)
818 return socket_name;
819 return NULL;
823 static void
824 handle_signal (int signo)
826 switch (signo)
828 #ifndef HAVE_W32_SYSTEM
829 case SIGHUP:
830 log_info ("SIGHUP received - "
831 "re-reading configuration and resetting cards\n");
832 /* reread_configuration (); */
833 break;
835 case SIGUSR1:
836 log_info ("SIGUSR1 received - printing internal information:\n");
837 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
838 app_dump_state ();
839 break;
841 case SIGUSR2:
842 log_info ("SIGUSR2 received - no action defined\n");
843 break;
845 case SIGTERM:
846 if (!shutdown_pending)
847 log_info ("SIGTERM received - shutting down ...\n");
848 else
849 log_info ("SIGTERM received - still %ld running threads\n",
850 pth_ctrl( PTH_CTRL_GETTHREADS ));
851 shutdown_pending++;
852 if (shutdown_pending > 2)
854 log_info ("shutdown forced\n");
855 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
856 cleanup ();
857 scd_exit (0);
859 break;
861 case SIGINT:
862 log_info ("SIGINT received - immediate shutdown\n");
863 log_info( "%s %s stopped\n", strusage(11), strusage(13));
864 cleanup ();
865 scd_exit (0);
866 break;
867 #endif /*!HAVE_W32_SYSTEM*/
869 default:
870 log_info ("signal %d received - no action defined\n", signo);
875 static void
876 handle_tick (void)
878 if (!ticker_disabled)
879 scd_update_reader_status_file ();
883 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
884 true using STANDARD_NAME in the home directory or if given has
885 false from the mkdir type name TEMPLATE. In the latter case a
886 unique name in a unique new directory will be created. In both
887 cases check for valid characters as well as against a maximum
888 allowed length for a unix domain socket is done. The function
889 terminates the process in case of an error. Retunrs: Pointer to an
890 allcoated string with the absolute name of the socket used. */
891 static char *
892 create_socket_name (int use_standard_socket,
893 char *standard_name, char *template)
895 char *name, *p;
897 if (use_standard_socket)
898 name = make_filename (opt.homedir, standard_name, NULL);
899 else
901 name = xstrdup (template);
902 p = strrchr (name, '/');
903 if (!p)
904 BUG ();
905 *p = 0;
906 if (!mkdtemp (name))
908 log_error (_("can't create directory `%s': %s\n"),
909 name, strerror (errno));
910 scd_exit (2);
912 *p = '/';
915 if (strchr (name, PATHSEP_C))
917 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
918 scd_exit (2);
920 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
922 log_error (_("name of socket too long\n"));
923 scd_exit (2);
925 return name;
930 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
931 whether a non-random socket is used. Returns the file descriptor
932 or terminates the process in case of an error. */
933 static int
934 create_server_socket (int is_standard_name, const char *name)
936 struct sockaddr_un *serv_addr;
937 socklen_t len;
938 int fd;
939 int rc;
941 #ifdef HAVE_W32_SYSTEM
942 fd = _w32_sock_new (AF_UNIX, SOCK_STREAM, 0);
943 #else
944 fd = socket (AF_UNIX, SOCK_STREAM, 0);
945 #endif
946 if (fd == -1)
948 log_error (_("can't create socket: %s\n"), strerror (errno));
949 scd_exit (2);
952 serv_addr = xmalloc (sizeof (*serv_addr));
953 memset (serv_addr, 0, sizeof *serv_addr);
954 serv_addr->sun_family = AF_UNIX;
955 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
956 strcpy (serv_addr->sun_path, name);
957 len = (offsetof (struct sockaddr_un, sun_path)
958 + strlen (serv_addr->sun_path) + 1);
960 #ifdef HAVE_W32_SYSTEM
961 rc = _w32_sock_bind (fd, (struct sockaddr*) serv_addr, len);
962 if (is_standard_name && rc == -1 )
964 remove (name);
965 rc = bind (fd, (struct sockaddr*) serv_addr, len);
967 #else
968 rc = bind (fd, (struct sockaddr*) serv_addr, len);
969 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
971 remove (name);
972 rc = bind (fd, (struct sockaddr*) serv_addr, len);
974 #endif
975 if (rc == -1)
977 log_error (_("error binding socket to `%s': %s\n"),
978 serv_addr->sun_path, strerror (errno));
979 close (fd);
980 scd_exit (2);
983 if (listen (fd, 5 ) == -1)
985 log_error (_("listen() failed: %s\n"), strerror (errno));
986 close (fd);
987 scd_exit (2);
990 if (opt.verbose)
991 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
993 return fd;
998 /* This is the standard connection thread's main function. */
999 static void *
1000 start_connection_thread (void *arg)
1002 ctrl_t ctrl = arg;
1004 scd_init_default_ctrl (ctrl);
1005 if (opt.verbose)
1006 log_info (_("handler for fd %d started\n"), ctrl->thread_startup.fd);
1008 scd_command_handler (ctrl, ctrl->thread_startup.fd);
1010 if (opt.verbose)
1011 log_info (_("handler for fd %d terminated\n"), ctrl->thread_startup.fd);
1013 /* If this thread is the pipe connection thread, flag that a
1014 shutdown is required. With the next ticker event and given that
1015 no other connections are running the shutdown will then
1016 happen. */
1017 if (ctrl->thread_startup.fd == -1)
1018 shutdown_pending = 1;
1020 scd_deinit_default_ctrl (ctrl);
1021 xfree (ctrl);
1022 return NULL;
1026 /* Connection handler loop. Wait for connection requests and spawn a
1027 thread after accepting a connection. LISTEN_FD is allowed to be -1
1028 in which case this code will only do regular timeouts and handle
1029 signals. */
1030 static void
1031 handle_connections (int listen_fd)
1033 pth_attr_t tattr;
1034 pth_event_t ev, time_ev;
1035 sigset_t sigs;
1036 int signo;
1037 struct sockaddr_un paddr;
1038 socklen_t plen;
1039 fd_set fdset, read_fdset;
1040 int ret;
1041 int fd;
1042 int nfd;
1044 tattr = pth_attr_new();
1045 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1046 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
1048 #ifndef HAVE_W32_SYSTEM /* fixme */
1049 sigemptyset (&sigs );
1050 sigaddset (&sigs, SIGHUP);
1051 sigaddset (&sigs, SIGUSR1);
1052 sigaddset (&sigs, SIGUSR2);
1053 sigaddset (&sigs, SIGINT);
1054 sigaddset (&sigs, SIGTERM);
1055 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1056 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1057 #else
1058 sigs = 0;
1059 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1060 #endif
1061 time_ev = NULL;
1063 FD_ZERO (&fdset);
1064 nfd = 0;
1065 if (listen_fd != -1)
1067 FD_SET (listen_fd, &fdset);
1068 nfd = listen_fd;
1071 for (;;)
1073 sigset_t oldsigs;
1075 if (shutdown_pending)
1077 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1078 break; /* ready */
1080 /* Do not accept anymore connections but wait for existing
1081 connections to terminate. We do this by clearing out all
1082 file descriptors to wait for, so that the select will be
1083 used to just wait on a signal or timeout event. */
1084 FD_ZERO (&fdset);
1087 /* Create a timeout event if needed. */
1088 if (!time_ev)
1089 time_ev = pth_event (PTH_EVENT_TIME,
1090 pth_timeout (TIMERTICK_INTERVAL, 0));
1092 /* POSIX says that fd_set should be implemented as a structure,
1093 thus a simple assignment is fine to copy the entire set. */
1094 read_fdset = fdset;
1096 if (time_ev)
1097 pth_event_concat (ev, time_ev, NULL);
1098 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1099 if (time_ev)
1100 pth_event_isolate (time_ev);
1102 if (ret == -1)
1104 if (pth_event_occurred (ev)
1105 || (time_ev && pth_event_occurred (time_ev)))
1107 if (pth_event_occurred (ev))
1108 handle_signal (signo);
1109 if (time_ev && pth_event_occurred (time_ev))
1111 pth_event_free (time_ev, PTH_FREE_ALL);
1112 time_ev = NULL;
1113 handle_tick ();
1115 continue;
1117 log_error (_("pth_select failed: %s - waiting 1s\n"),
1118 strerror (errno));
1119 pth_sleep (1);
1120 continue;
1123 if (pth_event_occurred (ev))
1125 handle_signal (signo);
1128 if (time_ev && pth_event_occurred (time_ev))
1130 pth_event_free (time_ev, PTH_FREE_ALL);
1131 time_ev = NULL;
1132 handle_tick ();
1135 /* We now might create new threads and because we don't want any
1136 signals - we are handling here - to be delivered to a new
1137 thread. Thus we need to block those signals. */
1138 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1140 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1142 ctrl_t ctrl;
1144 plen = sizeof paddr;
1145 fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1146 if (fd == -1)
1148 log_error ("accept failed: %s\n", strerror (errno));
1150 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1152 log_error ("error allocating connection control data: %s\n",
1153 strerror (errno) );
1154 close (fd);
1156 else
1158 char threadname[50];
1160 snprintf (threadname, sizeof threadname-1, "conn fd=%d", fd);
1161 threadname[sizeof threadname -1] = 0;
1162 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1163 ctrl->thread_startup.fd = fd;
1164 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1166 log_error ("error spawning connection handler: %s\n",
1167 strerror (errno) );
1168 xfree (ctrl);
1169 close (fd);
1172 fd = -1;
1175 /* Restore the signal mask. */
1176 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1180 pth_event_free (ev, PTH_FREE_ALL);
1181 if (time_ev)
1182 pth_event_free (time_ev, PTH_FREE_ALL);
1183 cleanup ();
1184 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));