1 /* scdaemon.c - The GnuPG Smartcard Daemon
2 * Copyright (C) 2001-2002, 2004-2005, 2007-2009 Free Software Foundation, Inc.
3 * Copyright (C) 2001-2002, 2004-2005, 2007-2014 Werner Koch
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 <https://www.gnu.org/licenses/>.
32 #ifndef HAVE_W32_SYSTEM
33 #include <sys/socket.h>
35 #endif /*HAVE_W32_SYSTEM*/
40 #define GNUPG_COMMON_NEED_AFLOCAL
45 #include <assuan.h> /* malloc hooks */
49 #include "app-common.h"
52 #include "ccid-driver.h"
53 #include "gc-opt-flags.h"
56 #include "../common/init.h"
59 # define ENAMETOOLONG EINVAL
62 enum cmd_and_opt_values
107 static ARGPARSE_OPTS opts[] = {
108 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
109 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
111 ARGPARSE_group (301, N_("@Options:\n ")),
113 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
114 ARGPARSE_s_n (oMultiServer, "multi-server",
115 N_("run in multi server mode (foreground)")),
116 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
117 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
118 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
119 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
120 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
121 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
122 ARGPARSE_s_s (oDebug, "debug", "@"),
123 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
124 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
125 N_("|LEVEL|set the debugging level to LEVEL")),
126 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
127 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
128 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
129 ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
130 ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
131 ARGPARSE_p_u (oDebugAssuanLogCats, "debug-assuan-log-cats", "@"),
132 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
133 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
134 ARGPARSE_s_s (oReaderPort, "reader-port",
135 N_("|N|connect to reader at port N")),
136 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
137 N_("|NAME|use NAME as ct-API driver")),
138 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
139 N_("|NAME|use NAME as PC/SC driver")),
140 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
142 N_("do not use the internal CCID driver")
146 /* end --disable-ccid */),
147 ARGPARSE_s_u (oCardTimeout, "card-timeout",
148 N_("|N|disconnect the card after N seconds of inactivity")),
150 ARGPARSE_s_n (oDisablePinpad, "disable-pinpad",
151 N_("do not use a reader's pinpad")),
152 ARGPARSE_ignore (300, "disable-keypad"),
154 ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
155 ARGPARSE_s_n (oDenyAdmin, "deny-admin",
156 N_("deny the use of admin card commands")),
157 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
158 ARGPARSE_s_n (oEnablePinpadVarlen, "enable-pinpad-varlen",
159 N_("use variable length input for pinpad")),
160 ARGPARSE_s_s (oHomedir, "homedir", "@"),
166 /* The list of supported debug flags. */
167 static struct debug_flags_s debug_flags [] =
169 { DBG_MPI_VALUE , "mpi" },
170 { DBG_CRYPTO_VALUE , "crypto" },
171 { DBG_MEMORY_VALUE , "memory" },
172 { DBG_CACHE_VALUE , "cache" },
173 { DBG_MEMSTAT_VALUE, "memstat" },
174 { DBG_HASHING_VALUE, "hashing" },
175 { DBG_IPC_VALUE , "ipc" },
176 { DBG_CARD_IO_VALUE, "cardio" },
177 { DBG_READER_VALUE , "reader" },
182 /* The card driver we use by default for PC/SC. */
183 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
184 #define DEFAULT_PCSC_DRIVER "winscard.dll"
185 #elif defined(__APPLE__)
186 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
187 #elif defined(__GLIBC__)
188 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
190 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
193 /* The timer tick used for housekeeping stuff. We poll every 500ms to
194 let the user immediately know a status change.
196 This is not too good for power saving but given that there is no
197 easy way to block on card status changes it is the best we can do.
198 For PC/SC we could in theory use an extra thread to wait for status
199 changes but that requires a native thread because there is no way
200 to make the underlying PC/SC card change function block using a Npth
201 mechanism. Given that a native thread could only be used under W32
202 we don't do that at all. */
203 #define TIMERTICK_INTERVAL_SEC (0)
204 #define TIMERTICK_INTERVAL_USEC (500000)
206 /* Flag to indicate that a shutdown was requested. */
207 static int shutdown_pending;
209 /* It is possible that we are currently running under setuid permissions */
210 static int maybe_setuid = 1;
212 /* Flag telling whether we are running as a pipe server. */
213 static int pipe_server;
215 /* Name of the communication socket */
216 static char *socket_name;
217 /* Name of the redirected socket or NULL. */
218 static char *redir_socket_name;
220 /* We need to keep track of the server's nonces (these are dummies for
222 static assuan_sock_nonce_t socket_nonce;
224 /* Debug flag to disable the ticker. The ticker is in fact not
225 disabled but it won't perform any ticker specific actions. */
226 static int ticker_disabled;
228 /* FD to notify update of usb devices. */
229 static int notify_fd;
231 static char *create_socket_name (char *standard_name);
232 static gnupg_fd_t create_server_socket (const char *name,
234 assuan_sock_nonce_t *nonce);
236 static void *start_connection_thread (void *arg);
237 static void handle_connections (int listen_fd);
239 /* Pth wrapper function definitions. */
240 ASSUAN_SYSTEM_NPTH_IMPL;
242 static int active_connections;
246 make_libversion (const char *libname, const char *(*getfnc)(const char*))
253 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
257 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
258 strcpy (stpcpy (stpcpy (result, libname), " "), s);
264 my_strusage (int level)
266 static char *ver_gcry, *ver_ksba;
271 case 11: p = "@SCDAEMON@ (@GNUPG@)";
273 case 13: p = VERSION; break;
274 case 17: p = PRINTABLE_OS_NAME; break;
275 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
279 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
284 ver_ksba = make_libversion ("libksba", ksba_check_version);
288 case 40: p = _("Usage: @SCDAEMON@ [options] (-h for help)");
290 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
291 "Smartcard daemon for @GNUPG@\n");
301 tid_log_callback (unsigned long *rvalue)
303 int len = sizeof (*rvalue);
306 thread = npth_self ();
307 if (sizeof (thread) < len)
308 len = sizeof (thread);
309 memcpy (rvalue, &thread, len);
311 return 2; /* Use use hex representation. */
315 /* Setup the debugging. With a LEVEL of NULL only the active debug
316 flags are propagated to the subsystems. With LEVEL set, a specific
317 set of debug flags is set; thus overriding all flags already
320 set_debug (const char *level)
322 int numok = (level && digitp (level));
323 int numlvl = numok? atoi (level) : 0;
327 else if (!strcmp (level, "none") || (numok && numlvl < 1))
329 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
330 opt.debug = DBG_IPC_VALUE;
331 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
332 opt.debug = DBG_IPC_VALUE;
333 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
334 opt.debug = (DBG_IPC_VALUE|DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
335 else if (!strcmp (level, "guru") || numok)
338 /* Unless the "guru" string has been used we don't want to allow
339 hashing debugging. The rationale is that people tend to
340 select the highest debug value and would then clutter their
341 disk with debug files which may reveal confidential data. */
343 opt.debug &= ~(DBG_HASHING_VALUE);
347 log_error (_("invalid debug-level '%s' given\n"), level);
352 if (opt.debug && !opt.verbose)
354 if (opt.debug && opt.quiet)
357 if (opt.debug & DBG_MPI_VALUE)
358 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
359 if (opt.debug & DBG_CRYPTO_VALUE )
360 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
361 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
364 parse_debug_flag (NULL, &opt.debug, debug_flags);
372 if (socket_name && *socket_name)
376 name = redir_socket_name? redir_socket_name : socket_name;
386 main (int argc, char **argv )
391 FILE *configfp = NULL;
392 char *configname = NULL;
394 unsigned int configlineno;
396 const char *debug_level = NULL;
397 int default_config =1;
400 int multi_server = 0;
404 char *logfile = NULL;
406 int gpgconf_list = 0;
407 const char *config_filename = NULL;
408 int allow_coredump = 0;
409 struct assuan_malloc_hooks malloc_hooks;
411 npth_t pipecon_handler;
413 early_system_init ();
414 set_strusage (my_strusage);
415 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
416 /* Please note that we may running SUID(ROOT), so be very CAREFUL
417 when adding any stuff between here and the call to INIT_SECMEM()
418 somewhere after the option parsing */
419 log_set_prefix ("scdaemon", GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
421 /* Make sure that our subsystems are ready. */
423 init_common_subsystems (&argc, &argv);
425 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
427 malloc_hooks.malloc = gcry_malloc;
428 malloc_hooks.realloc = gcry_realloc;
429 malloc_hooks.free = gcry_free;
430 assuan_set_malloc_hooks (&malloc_hooks);
431 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
432 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
434 setup_libassuan_logging (&opt.debug, NULL);
436 setup_libgcrypt_logging ();
437 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
439 disable_core_dumps ();
441 /* Set default options. */
443 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
445 shell = getenv ("SHELL");
446 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
449 /* Check whether we have a config file on the commandline */
454 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
455 while (arg_parse( &pargs, opts))
457 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
459 else if (pargs.r_opt == oOptions)
460 { /* yes there is one, so we do not try the default one, but
461 read the option file when it is encountered at the
465 else if (pargs.r_opt == oNoOptions)
466 default_config = 0; /* --no-options */
467 else if (pargs.r_opt == oHomedir)
468 gnupg_set_homedir (pargs.r.ret_str);
471 /* initialize the secure memory. */
472 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
476 Now we are working under our real uid
481 configname = make_filename (gnupg_homedir (), SCDAEMON_NAME EXTSEP_S "conf",
489 pargs.flags= 1; /* do not remove the args */
494 configfp = fopen (configname, "r");
500 log_info (_("Note: no default option file '%s'\n"),
505 log_error (_("option file '%s': %s\n"),
506 configname, strerror(errno) );
512 if (parse_debug && configname )
513 log_info (_("reading options from '%s'\n"), configname );
517 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
521 case aGPGConfList: gpgconf_list = 1; break;
522 case aGPGConfTest: gpgconf_list = 2; break;
523 case oQuiet: opt.quiet = 1; break;
524 case oVerbose: opt.verbose++; break;
525 case oBatch: opt.batch=1; break;
528 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
530 pargs.r_opt = ARGPARSE_INVALID_ARG;
531 pargs.err = ARGPARSE_PRINT_ERROR;
534 case oDebugAll: opt.debug = ~0; break;
535 case oDebugLevel: debug_level = pargs.r.ret_str; break;
536 case oDebugWait: debug_wait = pargs.r.ret_int; break;
537 case oDebugAllowCoreDump:
538 enable_core_dumps ();
541 case oDebugCCIDDriver:
543 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
544 #endif /*HAVE_LIBUSB*/
546 case oDebugDisableTicker: ticker_disabled = 1; break;
548 log_set_pid_suffix_cb (tid_log_callback);
550 case oDebugAssuanLogCats:
551 set_libassuan_log_cats (pargs.r.ret_ulong);
555 /* config files may not be nested (silently ignore them) */
559 configname = xstrdup(pargs.r.ret_str);
563 case oNoGreeting: nogreeting = 1; break;
564 case oNoVerbose: opt.verbose = 0; break;
565 case oNoOptions: break; /* no-options */
566 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
567 case oNoDetach: nodetach = 1; break;
568 case oLogFile: logfile = pargs.r.ret_str; break;
569 case oCsh: csh_style = 1; break;
570 case oSh: csh_style = 0; break;
571 case oServer: pipe_server = 1; break;
572 case oMultiServer: pipe_server = 1; multi_server = 1; break;
573 case oDaemon: is_daemon = 1; break;
575 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
576 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
577 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
578 case oDisableCCID: opt.disable_ccid = 1; break;
579 case oDisableOpenSC: break;
581 case oDisablePinpad: opt.disable_pinpad = 1; break;
583 case oAllowAdmin: /* Dummy because allow is now the default. */
585 case oDenyAdmin: opt.allow_admin = 0; break;
587 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
589 case oDisableApplication:
590 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
593 case oEnablePinpadVarlen: opt.enable_pinpad_varlen = 1; break;
596 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
604 /* Keep a copy of the config name for use by --gpgconf-list. */
605 config_filename = configname;
611 if (log_get_errorcount(0))
618 es_fprintf (es_stderr, "%s %s; %s\n",
619 strusage(11), strusage(13), strusage(14) );
620 es_fprintf (es_stderr, "%s\n", strusage(15) );
622 #ifdef IS_DEVELOPMENT_VERSION
623 log_info ("NOTE: this is a development version!\n");
626 /* Print a warning if an argument looks like an option. */
627 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
631 for (i=0; i < argc; i++)
632 if (argv[i][0] == '-' && argv[i][1] == '-')
633 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
636 if (atexit (cleanup))
638 log_error ("atexit failed\n");
643 set_debug (debug_level);
645 if (initialize_module_command ())
647 log_error ("initialization failed\n");
652 if (gpgconf_list == 2)
656 /* List options and default values in the GPG Conf format. */
657 char *filename = NULL;
661 filename = xstrdup (config_filename);
663 filename = make_filename (gnupg_homedir (),
664 SCDAEMON_NAME EXTSEP_S "conf", NULL);
665 filename_esc = percent_escape (filename, NULL);
667 es_printf ("%s-%s.conf:%lu:\"%s\n",
668 GPGCONF_NAME, SCDAEMON_NAME,
669 GC_OPT_FLAG_DEFAULT, filename_esc);
670 xfree (filename_esc);
673 es_printf ("verbose:%lu:\n"
675 "debug-level:%lu:\"none:\n"
682 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
683 es_printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
684 es_printf ("pcsc-driver:%lu:\"%s:\n",
685 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
687 es_printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
689 es_printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
690 es_printf ("disable-pinpad:%lu:\n", GC_OPT_FLAG_NONE );
691 es_printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
692 es_printf ("enable-pinpad-varlen:%lu:\n", GC_OPT_FLAG_NONE );
697 /* Now start with logging to a file if this is desired. */
700 log_set_file (logfile);
701 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
704 if (debug_wait && pipe_server)
706 log_debug ("waiting for debugger - my pid is %u .....\n",
707 (unsigned int)getpid());
708 gnupg_sleep (debug_wait);
709 log_debug ("... okay\n");
714 /* This is the simple pipe based server */
719 #ifndef HAVE_W32_SYSTEM
723 sa.sa_handler = SIG_IGN;
724 sigemptyset (&sa.sa_mask);
726 sigaction (SIGPIPE, &sa, NULL);
731 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
733 /* If --debug-allow-core-dump has been given we also need to
734 switch the working directory to a place where we can actually
739 log_debug ("chdir to '/tmp' failed: %s\n", strerror (errno));
741 log_debug ("changed working directory to '/tmp'\n");
744 /* In multi server mode we need to listen on an additional
745 socket. Create that socket now before starting the handler
746 for the pipe connection. This allows that handler to send
747 back the name of that socket. */
750 socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
751 fd = FD2INT(create_server_socket (socket_name,
752 &redir_socket_name, &socket_nonce));
755 res = npth_attr_init (&tattr);
758 log_error ("error allocating thread attributes: %s\n",
762 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
764 ctrl = xtrycalloc (1, sizeof *ctrl);
767 log_error ("error allocating connection control data: %s\n",
771 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
772 res = npth_create (&pipecon_handler, &tattr, start_connection_thread, ctrl);
775 log_error ("error spawning pipe connection handler: %s\n",
780 npth_setname_np (pipecon_handler, "pipe-connection");
781 npth_attr_destroy (&tattr);
783 /* We run handle_connection to wait for the shutdown signal and
784 to run the ticker stuff. */
785 handle_connections (fd);
791 log_info (_("please use the option '--daemon'"
792 " to run the program in the background\n"));
795 { /* Regular server mode */
797 #ifndef HAVE_W32_SYSTEM
802 /* Create the socket. */
803 socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
804 fd = FD2INT (create_server_socket (socket_name,
805 &redir_socket_name, &socket_nonce));
809 #ifdef HAVE_W32_SYSTEM
814 if (pid == (pid_t)-1)
816 log_fatal ("fork failed: %s\n", strerror (errno) );
820 { /* we are the parent */
825 /* create the info string: <name>:<pid>:<protocol_version> */
826 if (gpgrt_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
827 socket_name, (ulong) pid) < 0)
829 log_error ("out of core\n");
833 *socket_name = 0; /* don't let cleanup() remove the socket -
834 the child should do this from now on */
836 { /* run the program given on the commandline */
837 if (putenv (infostr))
839 log_error ("failed to set environment: %s\n",
841 kill (pid, SIGTERM );
844 execvp (argv[0], argv);
845 log_error ("failed to run the command: %s\n", strerror (errno));
851 /* Print the environment string, so that the caller can use
852 shell's eval to set it */
855 *strchr (infostr, '=') = ' ';
856 es_printf ( "setenv %s;\n", infostr);
860 es_printf ( "%s; export SCDAEMON_INFO;\n", infostr);
868 /* This is the child. */
871 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
873 /* Detach from tty and put process into a new session. */
876 /* Close stdin, stdout and stderr unless it is the log stream. */
877 for (i=0; i <= 2; i++)
879 if (!log_test_fd (i) && i != fd )
882 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
884 log_error ("failed to open '%s': %s\n",
885 "/dev/null", strerror (errno));
894 log_error ("setsid() failed: %s\n", strerror(errno) );
903 sa.sa_handler = SIG_IGN;
904 sigemptyset (&sa.sa_mask);
906 sigaction (SIGPIPE, &sa, NULL);
911 log_error ("chdir to / failed: %s\n", strerror (errno));
915 #endif /*!HAVE_W32_SYSTEM*/
917 handle_connections (fd);
928 apdu_prepare_exit ();
930 #warning no update_random_seed_file
931 update_random_seed_file();
934 /* at this time a bit annoying */
935 if (opt.debug & DBG_MEMSTAT_VALUE)
937 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
938 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
941 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
943 gcry_control (GCRYCTL_TERM_SECMEM );
944 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
950 scd_init_default_ctrl (ctrl_t ctrl)
956 scd_deinit_default_ctrl (ctrl_t ctrl)
960 xfree (ctrl->in_data.value);
961 ctrl->in_data.value = NULL;
962 ctrl->in_data.valuelen = 0;
966 /* Return the name of the socket to be used to connect to this
967 process. If no socket is available, return NULL. */
969 scd_get_socket_name ()
971 if (socket_name && *socket_name)
977 #ifndef HAVE_W32_SYSTEM
979 handle_signal (int signo)
984 log_info ("SIGHUP received - "
985 "re-reading configuration and resetting cards\n");
986 /* reread_configuration (); */
990 log_info ("SIGUSR1 received - printing internal information:\n");
991 /* Fixme: We need to see how to integrate pth dumping into our
993 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
998 log_info ("SIGUSR2 received - no action defined\n");
1002 if (!shutdown_pending)
1003 log_info ("SIGTERM received - shutting down ...\n");
1005 log_info ("SIGTERM received - still %i running threads\n",
1006 active_connections);
1008 if (shutdown_pending > 2)
1010 log_info ("shutdown forced\n");
1011 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1018 log_info ("SIGINT received - immediate shutdown\n");
1019 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1025 log_info ("signal %d received - no action defined\n", signo);
1028 #endif /*!HAVE_W32_SYSTEM*/
1034 if (!ticker_disabled)
1035 scd_update_reader_status_file ();
1039 /* Create a name for the socket. We check for valid characters as
1040 well as against a maximum allowed length for a unix domain socket
1041 is done. The function terminates the process in case of an error.
1042 Retunrs: Pointer to an allcoated string with the absolute name of
1045 create_socket_name (char *standard_name)
1049 name = make_filename (gnupg_socketdir (), standard_name, NULL);
1050 if (strchr (name, PATHSEP_C))
1052 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1060 /* Create a Unix domain socket with NAME. Returns the file descriptor
1061 or terminates the process in case of an error. If the socket has
1062 been redirected the name of the real socket is stored as a malloced
1063 string at R_REDIR_NAME. */
1065 create_server_socket (const char *name, char **r_redir_name,
1066 assuan_sock_nonce_t *nonce)
1068 struct sockaddr *addr;
1069 struct sockaddr_un *unaddr;
1074 xfree (*r_redir_name);
1075 *r_redir_name = NULL;
1077 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1078 if (fd == GNUPG_INVALID_FD)
1080 log_error (_("can't create socket: %s\n"), strerror (errno));
1084 unaddr = xmalloc (sizeof (*unaddr));
1085 addr = (struct sockaddr*)unaddr;
1090 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1092 if (errno == ENAMETOOLONG)
1093 log_error (_("socket name '%s' is too long\n"), name);
1095 log_error ("error preparing socket '%s': %s\n",
1096 name, gpg_strerror (gpg_error_from_syserror ()));
1101 *r_redir_name = xstrdup (unaddr->sun_path);
1103 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1107 len = SUN_LEN (unaddr);
1109 rc = assuan_sock_bind (fd, addr, len);
1110 if (rc == -1 && errno == EADDRINUSE)
1112 gnupg_remove (unaddr->sun_path);
1113 rc = assuan_sock_bind (fd, addr, len);
1116 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1117 log_error (_("error getting nonce for the socket\n"));
1120 log_error (_("error binding socket to '%s': %s\n"),
1122 gpg_strerror (gpg_error_from_syserror ()));
1123 assuan_sock_close (fd);
1127 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
1128 log_error (_("can't set permissions of '%s': %s\n"),
1129 unaddr->sun_path, strerror (errno));
1131 if (listen (FD2INT(fd), 5 ) == -1)
1133 log_error (_("listen() failed: %s\n"),
1134 gpg_strerror (gpg_error_from_syserror ()));
1135 assuan_sock_close (fd);
1140 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1147 /* This is the standard connection thread's main function. */
1149 start_connection_thread (void *arg)
1153 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1154 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1156 log_info (_("error reading nonce on fd %d: %s\n"),
1157 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1158 assuan_sock_close (ctrl->thread_startup.fd);
1163 scd_init_default_ctrl (ctrl);
1165 log_info (_("handler for fd %d started\n"),
1166 FD2INT(ctrl->thread_startup.fd));
1168 /* If this is a pipe server, we request a shutdown if the command
1169 handler asked for it. With the next ticker event and given that
1170 no other connections are running the shutdown will then
1172 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1174 shutdown_pending = 1;
1177 log_info (_("handler for fd %d terminated\n"),
1178 FD2INT (ctrl->thread_startup.fd));
1180 scd_deinit_default_ctrl (ctrl);
1187 scd_kick_the_loop (void)
1191 /* Kick the select loop. */
1192 ret = write (notify_fd, "", 1);
1196 /* Connection handler loop. Wait for connection requests and spawn a
1197 thread after accepting a connection. LISTEN_FD is allowed to be -1
1198 in which case this code will only do regular timeouts and handle
1201 handle_connections (int listen_fd)
1204 struct sockaddr_un paddr;
1206 fd_set fdset, read_fdset;
1210 struct timespec abstime;
1211 struct timespec curtime;
1212 struct timespec timeout;
1214 #ifndef HAVE_W32_SYSTEM
1219 ret = gnupg_create_pipe (pipe_fd);
1222 log_error ("pipe creation failed: %s\n", gpg_strerror (ret));
1225 notify_fd = pipe_fd[1];
1227 ret = npth_attr_init(&tattr);
1230 log_error ("npth_attr_init failed: %s\n", strerror (ret));
1234 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1236 #ifndef HAVE_W32_SYSTEM
1238 npth_sigev_add (SIGHUP);
1239 npth_sigev_add (SIGUSR1);
1240 npth_sigev_add (SIGUSR2);
1241 npth_sigev_add (SIGINT);
1242 npth_sigev_add (SIGTERM);
1248 if (listen_fd != -1)
1250 FD_SET (listen_fd, &fdset);
1254 npth_clock_gettime (&curtime);
1255 timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1256 timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1257 npth_timeradd (&curtime, &timeout, &abstime);
1258 /* We only require abstime here. The others will be reused. */
1264 if (shutdown_pending)
1266 if (active_connections == 0)
1269 /* Do not accept anymore connections but wait for existing
1270 connections to terminate. We do this by clearing out all
1271 file descriptors to wait for, so that the select will be
1272 used to just wait on a signal or timeout event. */
1277 npth_clock_gettime (&curtime);
1278 if (!(npth_timercmp (&curtime, &abstime, <)))
1282 timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1283 timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1284 npth_timeradd (&curtime, &timeout, &abstime);
1286 npth_timersub (&abstime, &curtime, &timeout);
1288 /* POSIX says that fd_set should be implemented as a structure,
1289 thus a simple assignment is fine to copy the entire set. */
1292 FD_SET (pipe_fd[0], &read_fdset);
1293 if (nfd < pipe_fd[0])
1294 max_fd = pipe_fd[0];
1298 #ifndef HAVE_W32_SYSTEM
1299 ret = npth_pselect (max_fd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask());
1300 saved_errno = errno;
1302 while (npth_sigev_get_pending(&signo))
1303 handle_signal (signo);
1305 ret = npth_eselect (max_fd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
1306 saved_errno = errno;
1309 if (ret == -1 && saved_errno != EINTR)
1311 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1312 strerror (saved_errno));
1318 /* Timeout. Will be handled when calculating the next timeout. */
1321 if (FD_ISSET (pipe_fd[0], &read_fdset))
1325 ret = read (pipe_fd[0], buf, sizeof buf);
1328 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1332 plen = sizeof paddr;
1333 fd = npth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1336 log_error ("accept failed: %s\n", strerror (errno));
1338 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1340 log_error ("error allocating connection control data: %s\n",
1346 char threadname[50];
1349 snprintf (threadname, sizeof threadname, "conn fd=%d", fd);
1350 ctrl->thread_startup.fd = INT2FD (fd);
1351 ret = npth_create (&thread, &tattr, start_connection_thread, ctrl);
1354 log_error ("error spawning connection handler: %s\n",
1360 npth_setname_np (thread, threadname);
1369 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1370 npth_attr_destroy (&tattr);