1 /* scdaemon.c - The GnuPG Smartcard Daemon
2 * Copyright (C) 2001-2002, 2004-2005, 2007-2020 Free Software Foundation, Inc.
3 * Copyright (C) 2001-2002, 2004-2005, 2007-2019 Werner Koch
4 * Copyright (C) 2020 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20 * SPDX-License-Identifier: GPL-3.0-or-later
34 #ifndef HAVE_W32_SYSTEM
35 #include <sys/socket.h>
37 #endif /*HAVE_W32_SYSTEM*/
42 #define INCLUDED_BY_MAIN_MODULE 1
43 #define GNUPG_COMMON_NEED_AFLOCAL
48 #include <assuan.h> /* malloc hooks */
50 #include "../common/i18n.h"
51 #include "../common/sysutils.h"
54 #include "ccid-driver.h"
55 #include "../common/gc-opt-flags.h"
56 #include "../common/asshelp.h"
57 #include "../common/exechelp.h"
58 #include "../common/init.h"
61 # define ENAMETOOLONG EINVAL
64 enum cmd_and_opt_values
112 static ARGPARSE_OPTS opts[] = {
113 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
114 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
116 ARGPARSE_header (NULL, N_("Options used for startup")),
118 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
119 ARGPARSE_s_n (oMultiServer, "multi-server",
120 N_("run in multi server mode (foreground)")),
121 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
122 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
123 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
124 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
125 ARGPARSE_s_s (oHomedir, "homedir", "@"),
126 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
127 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
130 ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
132 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
133 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
134 ARGPARSE_s_s (oDebug, "debug", "@"),
135 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
136 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
137 N_("|LEVEL|set the debugging level to LEVEL")),
138 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
139 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
140 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
141 ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
142 ARGPARSE_p_u (oDebugAssuanLogCats, "debug-assuan-log-cats", "@"),
143 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
146 ARGPARSE_header ("Configuration",
147 N_("Options controlling the configuration")),
149 ARGPARSE_s_s (oReaderPort, "reader-port",
150 N_("|N|connect to reader at port N")),
151 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
152 N_("|NAME|use NAME as ct-API driver")),
153 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
154 N_("|NAME|use NAME as PC/SC driver")),
155 ARGPARSE_s_n (opcscShared, "pcsc-shared", "@"),
156 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
158 N_("do not use the internal CCID driver")
162 /* end --disable-ccid */),
163 ARGPARSE_s_u (oCardTimeout, "card-timeout",
164 N_("|N|disconnect the card after N seconds of inactivity")),
166 ARGPARSE_s_n (oDisablePinpad, "disable-pinpad",
167 N_("do not use a reader's pinpad")),
168 ARGPARSE_ignore (300, "disable-keypad"),
169 ARGPARSE_s_n (oEnablePinpadVarlen, "enable-pinpad-varlen",
170 N_("use variable length input for pinpad")),
171 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
172 ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
175 ARGPARSE_header("Security", N_("Options controlling the security")),
177 ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
178 ARGPARSE_s_n (oDenyAdmin, "deny-admin",
179 N_("deny the use of admin card commands")),
181 /* Stubs for options which are implemented by 2.3 or later. */
182 ARGPARSE_s_s (oNoop, "application-priority", "@"),
188 /* The list of supported debug flags. */
189 static struct debug_flags_s debug_flags [] =
191 { DBG_MPI_VALUE , "mpi" },
192 { DBG_CRYPTO_VALUE , "crypto" },
193 { DBG_MEMORY_VALUE , "memory" },
194 { DBG_CACHE_VALUE , "cache" },
195 { DBG_MEMSTAT_VALUE, "memstat" },
196 { DBG_HASHING_VALUE, "hashing" },
197 { DBG_IPC_VALUE , "ipc" },
198 { DBG_CARD_VALUE , "card" },
199 { DBG_CARD_IO_VALUE, "cardio" },
200 { DBG_READER_VALUE , "reader" },
205 /* The card driver we use by default for PC/SC. */
206 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
207 #define DEFAULT_PCSC_DRIVER "winscard.dll"
208 #elif defined(__APPLE__)
209 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
210 #elif defined(__GLIBC__)
211 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
213 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
216 /* The timer tick used to check card removal.
218 We poll every 500ms to let the user immediately know a status
221 For a card reader with an interrupt endpoint, this timer is not
222 used with the internal CCID driver.
224 This is not too good for power saving but given that there is no
225 easy way to block on card status changes it is the best we can do.
226 For PC/SC we could in theory use an extra thread to wait for status
227 changes but that requires a native thread because there is no way
228 to make the underlying PC/SC card change function block using a Npth
229 mechanism. Given that a native thread could only be used under W32
230 we don't do that at all. */
231 #define TIMERTICK_INTERVAL_SEC (0)
232 #define TIMERTICK_INTERVAL_USEC (500000)
234 /* Flag to indicate that a shutdown was requested. */
235 static int shutdown_pending;
237 /* It is possible that we are currently running under setuid permissions */
238 static int maybe_setuid = 1;
240 /* Flag telling whether we are running as a pipe server. */
241 static int pipe_server;
243 /* Name of the communication socket */
244 static char *socket_name;
245 /* Name of the redirected socket or NULL. */
246 static char *redir_socket_name;
248 /* We need to keep track of the server's nonces (these are dummies for
250 static assuan_sock_nonce_t socket_nonce;
252 /* Value for the listen() backlog argument. Change at runtime with
253 * --listen-backlog. */
254 static int listen_backlog = 64;
256 #ifdef HAVE_W32_SYSTEM
257 static HANDLE the_event;
259 /* PID to notify update of usb devices. */
260 static pid_t main_thread_pid;
262 #ifdef HAVE_PSELECT_NO_EINTR
263 /* FD to notify changes. */
264 static int notify_fd;
267 static char *create_socket_name (char *standard_name);
268 static gnupg_fd_t create_server_socket (const char *name,
270 assuan_sock_nonce_t *nonce);
272 static void *start_connection_thread (void *arg);
273 static void handle_connections (int listen_fd);
275 /* Pth wrapper function definitions. */
276 ASSUAN_SYSTEM_NPTH_IMPL;
278 static int active_connections;
282 make_libversion (const char *libname, const char *(*getfnc)(const char*))
289 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
293 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
294 strcpy (stpcpy (stpcpy (result, libname), " "), s);
300 my_strusage (int level)
302 static char *ver_gcry, *ver_ksba;
307 case 9: p = "GPL-3.0-or-later"; break;
308 case 11: p = "@SCDAEMON@ (@GNUPG@)";
310 case 13: p = VERSION; break;
311 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
312 case 17: p = PRINTABLE_OS_NAME; break;
313 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
317 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
322 ver_ksba = make_libversion ("libksba", ksba_check_version);
326 case 40: p = _("Usage: @SCDAEMON@ [options] (-h for help)");
328 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
329 "Smartcard daemon for @GNUPG@\n");
339 tid_log_callback (unsigned long *rvalue)
341 int len = sizeof (*rvalue);
344 thread = npth_self ();
345 if (sizeof (thread) < len)
346 len = sizeof (thread);
347 memcpy (rvalue, &thread, len);
349 return 2; /* Use use hex representation. */
353 /* Setup the debugging. With a LEVEL of NULL only the active debug
354 flags are propagated to the subsystems. With LEVEL set, a specific
355 set of debug flags is set; thus overriding all flags already
358 set_debug (const char *level)
360 int numok = (level && digitp (level));
361 int numlvl = numok? atoi (level) : 0;
365 else if (!strcmp (level, "none") || (numok && numlvl < 1))
367 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
368 opt.debug = DBG_IPC_VALUE;
369 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
370 opt.debug = DBG_IPC_VALUE;
371 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
372 opt.debug = (DBG_IPC_VALUE|DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
373 else if (!strcmp (level, "guru") || numok)
376 /* Unless the "guru" string has been used we don't want to allow
377 hashing debugging. The rationale is that people tend to
378 select the highest debug value and would then clutter their
379 disk with debug files which may reveal confidential data. */
381 opt.debug &= ~(DBG_HASHING_VALUE);
385 log_error (_("invalid debug-level '%s' given\n"), level);
390 if (opt.debug && !opt.verbose)
392 if (opt.debug && opt.quiet)
395 if (opt.debug & DBG_MPI_VALUE)
396 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
397 if (opt.debug & DBG_CRYPTO_VALUE )
398 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
399 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
402 parse_debug_flag (NULL, &opt.debug, debug_flags);
410 if (socket_name && *socket_name)
414 name = redir_socket_name? redir_socket_name : socket_name;
422 setup_signal_mask (void)
424 #ifndef HAVE_W32_SYSTEM
426 npth_sigev_add (SIGHUP);
427 npth_sigev_add (SIGUSR1);
428 npth_sigev_add (SIGUSR2);
429 npth_sigev_add (SIGINT);
430 npth_sigev_add (SIGCONT);
431 npth_sigev_add (SIGTERM);
433 main_thread_pid = getpid ();
438 main (int argc, char **argv )
443 char *last_configname = NULL;
444 const char *configname = NULL;
446 int debug_argparser = 0;
447 const char *debug_level = NULL;
450 int multi_server = 0;
454 char *logfile = NULL;
456 int gpgconf_list = 0;
457 char *config_filename = NULL;
458 int allow_coredump = 0;
459 struct assuan_malloc_hooks malloc_hooks;
461 npth_t pipecon_handler;
463 early_system_init ();
464 set_strusage (my_strusage);
465 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
466 /* Please note that we may running SUID(ROOT), so be very CAREFUL
467 when adding any stuff between here and the call to INIT_SECMEM()
468 somewhere after the option parsing */
469 log_set_prefix ("scdaemon", GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
471 /* Make sure that our subsystems are ready. */
473 init_common_subsystems (&argc, &argv);
475 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
477 malloc_hooks.malloc = gcry_malloc;
478 malloc_hooks.realloc = gcry_realloc;
479 malloc_hooks.free = gcry_free;
480 assuan_set_malloc_hooks (&malloc_hooks);
481 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
482 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
484 setup_libassuan_logging (&opt.debug, NULL);
486 setup_libgcrypt_logging ();
487 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
489 disable_core_dumps ();
491 /* Set default options. */
493 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
495 shell = getenv ("SHELL");
496 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
499 /* Check whether we have a config file on the commandline */
504 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
505 while (gnupg_argparse (NULL, &pargs, opts))
514 gnupg_set_homedir (pargs.r.ret_str);
518 /* Reset the flags. */
519 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
521 /* Initialize the secure memory. */
522 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
526 * Now we are working under our real uid
529 /* The configuraton directories for use by gpgrt_argparser. */
530 gnupg_set_confdir (GNUPG_CONFDIR_SYS, gnupg_sysconfdir ());
531 gnupg_set_confdir (GNUPG_CONFDIR_USER, gnupg_homedir ());
537 pargs.flags |= (ARGPARSE_FLAG_RESET
540 | ARGPARSE_FLAG_USER);
541 while (gnupg_argparser (&pargs, opts, SCDAEMON_NAME EXTSEP_S "conf"))
545 case ARGPARSE_CONFFILE:
547 log_info (_("reading options from '%s'\n"),
548 pargs.r_type? pargs.r.ret_str: "[cmdline]");
551 xfree (last_configname);
552 last_configname = xstrdup (pargs.r.ret_str);
553 configname = last_configname;
559 case aGPGConfList: gpgconf_list = 1; break;
560 case aGPGConfTest: gpgconf_list = 2; break;
561 case oQuiet: opt.quiet = 1; break;
562 case oVerbose: opt.verbose++; break;
563 case oBatch: opt.batch=1; break;
566 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
568 pargs.r_opt = ARGPARSE_INVALID_ARG;
569 pargs.err = ARGPARSE_PRINT_ERROR;
572 case oDebugAll: opt.debug = ~0; break;
573 case oDebugLevel: debug_level = pargs.r.ret_str; break;
574 case oDebugWait: debug_wait = pargs.r.ret_int; break;
575 case oDebugAllowCoreDump:
576 enable_core_dumps ();
579 case oDebugCCIDDriver:
581 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
582 #endif /*HAVE_LIBUSB*/
585 log_set_pid_suffix_cb (tid_log_callback);
587 case oDebugAssuanLogCats:
588 set_libassuan_log_cats (pargs.r.ret_ulong);
591 case oNoGreeting: nogreeting = 1; break;
592 case oNoVerbose: opt.verbose = 0; break;
593 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
594 case oNoDetach: nodetach = 1; break;
595 case oLogFile: logfile = pargs.r.ret_str; break;
596 case oCsh: csh_style = 1; break;
597 case oSh: csh_style = 0; break;
598 case oServer: pipe_server = 1; break;
599 case oMultiServer: pipe_server = 1; multi_server = 1; break;
600 case oDaemon: is_daemon = 1; break;
602 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
603 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
604 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
605 case opcscShared: opt.pcsc_shared = 1; break;
606 case oDisableCCID: opt.disable_ccid = 1; break;
607 case oDisableOpenSC: break;
609 case oDisablePinpad: opt.disable_pinpad = 1; break;
611 case oAllowAdmin: /* Dummy because allow is now the default. */
613 case oDenyAdmin: opt.allow_admin = 0; break;
615 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
617 case oDisableApplication:
618 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
621 case oEnablePinpadVarlen: opt.enable_pinpad_varlen = 1; break;
624 listen_backlog = pargs.r.ret_int;
631 pargs.err = ARGPARSE_PRINT_WARNING;
633 pargs.err = ARGPARSE_PRINT_ERROR;
637 gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */
639 if (!last_configname)
640 config_filename = make_filename (gnupg_homedir (),
641 SCDAEMON_NAME EXTSEP_S "conf",
645 config_filename = last_configname;
646 last_configname = NULL;
649 if (log_get_errorcount(0))
656 es_fprintf (es_stderr, "%s %s; %s\n",
657 strusage(11), strusage(13), strusage(14) );
658 es_fprintf (es_stderr, "%s\n", strusage(15) );
660 #ifdef IS_DEVELOPMENT_VERSION
661 log_info ("NOTE: this is a development version!\n");
664 /* Print a warning if an argument looks like an option. */
665 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
669 for (i=0; i < argc; i++)
670 if (argv[i][0] == '-' && argv[i][1] == '-')
671 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
674 if (atexit (cleanup))
676 log_error ("atexit failed\n");
681 set_debug (debug_level);
683 if (initialize_module_command ())
685 log_error ("initialization failed\n");
690 if (gpgconf_list == 2)
694 /* List options and default values in the GPG Conf format. */
697 filename_esc = percent_escape (config_filename, NULL);
698 es_printf ("%s-%s.conf:%lu:\"%s\n",
699 GPGCONF_NAME, SCDAEMON_NAME,
700 GC_OPT_FLAG_DEFAULT, filename_esc);
701 xfree (filename_esc);
703 es_printf ("verbose:%lu:\n"
705 "debug-level:%lu:\"none:\n"
712 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
713 es_printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
714 es_printf ("pcsc-driver:%lu:\"%s:\n",
715 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
717 es_printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
719 es_printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
720 es_printf ("disable-pinpad:%lu:\n", GC_OPT_FLAG_NONE );
721 es_printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
722 es_printf ("enable-pinpad-varlen:%lu:\n", GC_OPT_FLAG_NONE );
727 /* Now start with logging to a file if this is desired. */
730 log_set_file (logfile);
731 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
734 if (debug_wait && pipe_server)
736 log_debug ("waiting for debugger - my pid is %u .....\n",
737 (unsigned int)getpid());
738 gnupg_sleep (debug_wait);
739 log_debug ("... okay\n");
744 /* This is the simple pipe based server */
749 #ifndef HAVE_W32_SYSTEM
753 sa.sa_handler = SIG_IGN;
754 sigemptyset (&sa.sa_mask);
756 sigaction (SIGPIPE, &sa, NULL);
761 setup_signal_mask ();
762 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
764 /* If --debug-allow-core-dump has been given we also need to
765 switch the working directory to a place where we can actually
770 log_debug ("chdir to '/tmp' failed: %s\n", strerror (errno));
772 log_debug ("changed working directory to '/tmp'\n");
775 /* In multi server mode we need to listen on an additional
776 socket. Create that socket now before starting the handler
777 for the pipe connection. This allows that handler to send
778 back the name of that socket. */
781 socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
782 fd = FD2INT(create_server_socket (socket_name,
783 &redir_socket_name, &socket_nonce));
786 res = npth_attr_init (&tattr);
789 log_error ("error allocating thread attributes: %s\n",
793 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
795 ctrl = xtrycalloc (1, sizeof *ctrl);
798 log_error ("error allocating connection control data: %s\n",
802 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
803 res = npth_create (&pipecon_handler, &tattr, start_connection_thread, ctrl);
806 log_error ("error spawning pipe connection handler: %s\n",
811 npth_setname_np (pipecon_handler, "pipe-connection");
812 npth_attr_destroy (&tattr);
814 /* We run handle_connection to wait for the shutdown signal and
815 to run the ticker stuff. */
816 handle_connections (fd);
822 log_info (_("please use the option '--daemon'"
823 " to run the program in the background\n"));
826 { /* Regular server mode */
828 #ifndef HAVE_W32_SYSTEM
833 /* Create the socket. */
834 socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
835 fd = FD2INT (create_server_socket (socket_name,
836 &redir_socket_name, &socket_nonce));
840 #ifdef HAVE_W32_SYSTEM
845 if (pid == (pid_t)-1)
847 log_fatal ("fork failed: %s\n", strerror (errno) );
851 { /* we are the parent */
856 /* create the info string: <name>:<pid>:<protocol_version> */
857 if (gpgrt_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
858 socket_name, (ulong) pid) < 0)
860 log_error ("out of core\n");
864 *socket_name = 0; /* don't let cleanup() remove the socket -
865 the child should do this from now on */
867 { /* run the program given on the commandline */
868 if (putenv (infostr))
870 log_error ("failed to set environment: %s\n",
872 kill (pid, SIGTERM );
875 execvp (argv[0], argv);
876 log_error ("failed to run the command: %s\n", strerror (errno));
882 /* Print the environment string, so that the caller can use
883 shell's eval to set it */
886 *strchr (infostr, '=') = ' ';
887 es_printf ( "setenv %s;\n", infostr);
891 es_printf ( "%s; export SCDAEMON_INFO;\n", infostr);
899 /* This is the child. */
902 setup_signal_mask ();
903 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
905 /* Detach from tty and put process into a new session. */
908 /* Close stdin, stdout and stderr unless it is the log stream. */
909 for (i=0; i <= 2; i++)
911 if (!log_test_fd (i) && i != fd )
914 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
916 log_error ("failed to open '%s': %s\n",
917 "/dev/null", strerror (errno));
926 log_error ("setsid() failed: %s\n", strerror(errno) );
935 sa.sa_handler = SIG_IGN;
936 sigemptyset (&sa.sa_mask);
938 sigaction (SIGPIPE, &sa, NULL);
941 #endif /*!HAVE_W32_SYSTEM*/
943 if (gnupg_chdir (gnupg_daemon_rootdir ()))
945 log_error ("chdir to '%s' failed: %s\n",
946 gnupg_daemon_rootdir (), strerror (errno));
950 handle_connections (fd);
955 xfree (config_filename);
963 apdu_prepare_exit ();
965 #warning no update_random_seed_file
966 update_random_seed_file();
969 /* at this time a bit annoying */
970 if (opt.debug & DBG_MEMSTAT_VALUE)
972 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
973 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
976 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
978 gcry_control (GCRYCTL_TERM_SECMEM );
979 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
985 scd_init_default_ctrl (ctrl_t ctrl)
991 scd_deinit_default_ctrl (ctrl_t ctrl)
995 xfree (ctrl->in_data.value);
996 ctrl->in_data.value = NULL;
997 ctrl->in_data.valuelen = 0;
1001 /* Return the name of the socket to be used to connect to this
1002 process. If no socket is available, return NULL. */
1004 scd_get_socket_name ()
1006 if (socket_name && *socket_name)
1012 #ifndef HAVE_W32_SYSTEM
1014 handle_signal (int signo)
1019 log_info ("SIGHUP received - "
1020 "re-reading configuration and resetting cards\n");
1021 /* reread_configuration (); */
1025 log_info ("SIGUSR1 received - printing internal information:\n");
1026 /* Fixme: We need to see how to integrate pth dumping into our
1028 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1033 log_info ("SIGUSR2 received - no action defined\n");
1038 log_debug ("SIGCONT received - breaking select\n");
1042 if (!shutdown_pending)
1043 log_info ("SIGTERM received - shutting down ...\n");
1045 log_info ("SIGTERM received - still %i running threads\n",
1046 active_connections);
1048 if (shutdown_pending > 2)
1050 log_info ("shutdown forced\n");
1051 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1058 log_info ("SIGINT received - immediate shutdown\n");
1059 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1065 log_info ("signal %d received - no action defined\n", signo);
1068 #endif /*!HAVE_W32_SYSTEM*/
1071 /* Create a name for the socket. We check for valid characters as
1072 well as against a maximum allowed length for a unix domain socket
1073 is done. The function terminates the process in case of an error.
1074 Retunrs: Pointer to an allcoated string with the absolute name of
1077 create_socket_name (char *standard_name)
1081 name = make_filename (gnupg_socketdir (), standard_name, NULL);
1082 if (strchr (name, PATHSEP_C))
1084 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1092 /* Create a Unix domain socket with NAME. Returns the file descriptor
1093 or terminates the process in case of an error. If the socket has
1094 been redirected the name of the real socket is stored as a malloced
1095 string at R_REDIR_NAME. */
1097 create_server_socket (const char *name, char **r_redir_name,
1098 assuan_sock_nonce_t *nonce)
1100 struct sockaddr *addr;
1101 struct sockaddr_un *unaddr;
1106 xfree (*r_redir_name);
1107 *r_redir_name = NULL;
1109 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1110 if (fd == GNUPG_INVALID_FD)
1112 log_error (_("can't create socket: %s\n"), strerror (errno));
1116 unaddr = xmalloc (sizeof (*unaddr));
1117 addr = (struct sockaddr*)unaddr;
1122 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1124 if (errno == ENAMETOOLONG)
1125 log_error (_("socket name '%s' is too long\n"), name);
1127 log_error ("error preparing socket '%s': %s\n",
1128 name, gpg_strerror (gpg_error_from_syserror ()));
1133 *r_redir_name = xstrdup (unaddr->sun_path);
1135 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1139 len = SUN_LEN (unaddr);
1141 rc = assuan_sock_bind (fd, addr, len);
1142 if (rc == -1 && errno == EADDRINUSE)
1144 gnupg_remove (unaddr->sun_path);
1145 rc = assuan_sock_bind (fd, addr, len);
1148 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1149 log_error (_("error getting nonce for the socket\n"));
1152 log_error (_("error binding socket to '%s': %s\n"),
1154 gpg_strerror (gpg_error_from_syserror ()));
1155 assuan_sock_close (fd);
1159 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
1160 log_error (_("can't set permissions of '%s': %s\n"),
1161 unaddr->sun_path, strerror (errno));
1163 if (listen (FD2INT(fd), listen_backlog) == -1)
1165 log_error ("listen(fd, %d) failed: %s\n",
1166 listen_backlog, gpg_strerror (gpg_error_from_syserror ()));
1167 assuan_sock_close (fd);
1172 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1179 /* This is the standard connection thread's main function. */
1181 start_connection_thread (void *arg)
1185 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1186 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1188 log_info (_("error reading nonce on fd %d: %s\n"),
1189 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1190 assuan_sock_close (ctrl->thread_startup.fd);
1195 active_connections++;
1197 scd_init_default_ctrl (ctrl);
1199 log_info (_("handler for fd %d started\n"),
1200 FD2INT(ctrl->thread_startup.fd));
1202 /* If this is a pipe server, we request a shutdown if the command
1203 handler asked for it. With the next ticker event and given that
1204 no other connections are running the shutdown will then
1206 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1208 shutdown_pending = 1;
1211 log_info (_("handler for fd %d terminated\n"),
1212 FD2INT (ctrl->thread_startup.fd));
1214 scd_deinit_default_ctrl (ctrl);
1217 if (--active_connections == 0)
1218 scd_kick_the_loop ();
1225 scd_kick_the_loop (void)
1227 /* Kick the select loop. */
1228 #ifdef HAVE_W32_SYSTEM
1229 int ret = SetEvent (the_event);
1231 log_error ("SetEvent for scd_kick_the_loop failed: %s\n",
1233 #elif defined(HAVE_PSELECT_NO_EINTR)
1234 write (notify_fd, "", 1);
1236 int ret = kill (main_thread_pid, SIGCONT);
1238 log_error ("sending signal for scd_kick_the_loop failed: %s\n",
1239 gpg_strerror (gpg_error_from_syserror ()));
1243 /* Connection handler loop. Wait for connection requests and spawn a
1244 thread after accepting a connection. LISTEN_FD is allowed to be -1
1245 in which case this code will only do regular timeouts and handle
1248 handle_connections (int listen_fd)
1251 struct sockaddr_un paddr;
1253 fd_set fdset, read_fdset;
1257 struct timespec timeout;
1260 #ifdef HAVE_W32_SYSTEM
1262 unsigned int events_set;
1266 #ifdef HAVE_PSELECT_NO_EINTR
1269 ret = gnupg_create_pipe (pipe_fd);
1272 log_error ("pipe creation failed: %s\n", gpg_strerror (ret));
1275 notify_fd = pipe_fd[1];
1278 ret = npth_attr_init(&tattr);
1281 log_error ("npth_attr_init failed: %s\n", strerror (ret));
1285 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1287 #ifdef HAVE_W32_SYSTEM
1290 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1292 events[0] = the_event = INVALID_HANDLE_VALUE;
1293 events[1] = INVALID_HANDLE_VALUE;
1294 /* Create event for manual reset, initially non-signaled. Make it
1295 * waitable and inheritable. */
1296 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1298 log_error ("can't create scd event: %s\n", w32_strerror (-1) );
1299 else if (!DuplicateHandle (GetCurrentProcess(), h,
1300 GetCurrentProcess(), &h2,
1301 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1303 log_error ("setting synchronize for scd_kick_the_loop failed: %s\n",
1304 w32_strerror (-1) );
1310 events[0] = the_event = h2;
1317 if (listen_fd != -1)
1319 FD_SET (listen_fd, &fdset);
1325 int periodical_check;
1328 if (shutdown_pending)
1330 if (active_connections == 0)
1333 /* Do not accept anymore connections but wait for existing
1334 connections to terminate. We do this by clearing out all
1335 file descriptors to wait for, so that the select will be
1336 used to just wait on a signal or timeout event. */
1341 periodical_check = scd_update_reader_status_file ();
1343 timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1344 timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1346 if (shutdown_pending || periodical_check)
1351 /* POSIX says that fd_set should be implemented as a structure,
1352 thus a simple assignment is fine to copy the entire set. */
1355 #ifdef HAVE_PSELECT_NO_EINTR
1356 FD_SET (pipe_fd[0], &read_fdset);
1357 if (max_fd < pipe_fd[0])
1358 max_fd = pipe_fd[0];
1363 #ifndef HAVE_W32_SYSTEM
1364 ret = npth_pselect (max_fd+1, &read_fdset, NULL, NULL, t,
1365 npth_sigev_sigmask ());
1366 saved_errno = errno;
1368 while (npth_sigev_get_pending(&signo))
1369 handle_signal (signo);
1371 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, t,
1372 events, &events_set);
1373 saved_errno = errno;
1378 if (ret == -1 && saved_errno != EINTR)
1380 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1381 strerror (saved_errno));
1387 /* Timeout. Will be handled when calculating the next timeout. */
1390 #ifdef HAVE_PSELECT_NO_EINTR
1391 if (FD_ISSET (pipe_fd[0], &read_fdset))
1395 read (pipe_fd[0], buf, sizeof buf);
1399 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1403 plen = sizeof paddr;
1404 fd = npth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1407 log_error ("accept failed: %s\n", strerror (errno));
1409 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1411 log_error ("error allocating connection control data: %s\n",
1417 char threadname[50];
1420 snprintf (threadname, sizeof threadname, "conn fd=%d", fd);
1421 ctrl->thread_startup.fd = INT2FD (fd);
1422 ret = npth_create (&thread, &tattr, start_connection_thread, ctrl);
1425 log_error ("error spawning connection handler: %s\n",
1431 npth_setname_np (thread, threadname);
1436 #ifdef HAVE_W32_SYSTEM
1437 if (the_event != INVALID_HANDLE_VALUE)
1438 CloseHandle (the_event);
1440 #ifdef HAVE_PSELECT_NO_EINTR
1445 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1446 npth_attr_destroy (&tattr);
1449 /* Return the number of active connections. */
1451 get_active_connection_count (void)
1453 return active_connections;