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"
55 #include "../common/init.h"
58 # define ENAMETOOLONG EINVAL
61 enum cmd_and_opt_values
106 static ARGPARSE_OPTS opts[] = {
107 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
108 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
110 ARGPARSE_group (301, N_("@Options:\n ")),
112 ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
113 ARGPARSE_s_n (oMultiServer, "multi-server",
114 N_("run in multi server mode (foreground)")),
115 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
116 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
117 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
118 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
119 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
120 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
121 ARGPARSE_s_s (oDebug, "debug", "@"),
122 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
123 ARGPARSE_s_s (oDebugLevel, "debug-level" ,
124 N_("|LEVEL|set the debugging level to LEVEL")),
125 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
126 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
127 ARGPARSE_s_n (oDebugCCIDDriver, "debug-ccid-driver", "@"),
128 ARGPARSE_s_n (oDebugDisableTicker, "debug-disable-ticker", "@"),
129 ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
130 ARGPARSE_p_u (oDebugAssuanLogCats, "debug-assuan-log-cats", "@"),
131 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
132 ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write a log to FILE")),
133 ARGPARSE_s_s (oReaderPort, "reader-port",
134 N_("|N|connect to reader at port N")),
135 ARGPARSE_s_s (octapiDriver, "ctapi-driver",
136 N_("|NAME|use NAME as ct-API driver")),
137 ARGPARSE_s_s (opcscDriver, "pcsc-driver",
138 N_("|NAME|use NAME as PC/SC driver")),
139 ARGPARSE_s_n (oDisableCCID, "disable-ccid",
141 N_("do not use the internal CCID driver")
145 /* end --disable-ccid */),
146 ARGPARSE_s_u (oCardTimeout, "card-timeout",
147 N_("|N|disconnect the card after N seconds of inactivity")),
149 ARGPARSE_s_n (oDisablePinpad, "disable-pinpad",
150 N_("do not use a reader's pinpad")),
151 ARGPARSE_ignore (300, "disable-keypad"),
153 ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
154 ARGPARSE_s_n (oDenyAdmin, "deny-admin",
155 N_("deny the use of admin card commands")),
156 ARGPARSE_s_s (oDisableApplication, "disable-application", "@"),
157 ARGPARSE_s_n (oEnablePinpadVarlen, "enable-pinpad-varlen",
158 N_("use variable length input for pinpad")),
159 ARGPARSE_s_s (oHomedir, "homedir", "@"),
165 /* The list of supported debug flags. */
166 static struct debug_flags_s debug_flags [] =
168 { DBG_MPI_VALUE , "mpi" },
169 { DBG_CRYPTO_VALUE , "crypto" },
170 { DBG_MEMORY_VALUE , "memory" },
171 { DBG_CACHE_VALUE , "cache" },
172 { DBG_MEMSTAT_VALUE, "memstat" },
173 { DBG_HASHING_VALUE, "hashing" },
174 { DBG_IPC_VALUE , "ipc" },
175 { DBG_CARD_IO_VALUE, "cardio" },
176 { DBG_READER_VALUE , "reader" },
181 /* The card driver we use by default for PC/SC. */
182 #if defined(HAVE_W32_SYSTEM) || defined(__CYGWIN__)
183 #define DEFAULT_PCSC_DRIVER "winscard.dll"
184 #elif defined(__APPLE__)
185 #define DEFAULT_PCSC_DRIVER "/System/Library/Frameworks/PCSC.framework/PCSC"
186 #elif defined(__GLIBC__)
187 #define DEFAULT_PCSC_DRIVER "libpcsclite.so.1"
189 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
192 /* The timer tick used for housekeeping stuff. We poll every 500ms to
193 let the user immediately know a status change.
195 This is not too good for power saving but given that there is no
196 easy way to block on card status changes it is the best we can do.
197 For PC/SC we could in theory use an extra thread to wait for status
198 changes but that requires a native thread because there is no way
199 to make the underlying PC/SC card change function block using a Npth
200 mechanism. Given that a native thread could only be used under W32
201 we don't do that at all. */
202 #define TIMERTICK_INTERVAL_SEC (0)
203 #define TIMERTICK_INTERVAL_USEC (500000)
205 /* Flag to indicate that a shutdown was requested. */
206 static int shutdown_pending;
208 /* It is possible that we are currently running under setuid permissions */
209 static int maybe_setuid = 1;
211 /* Flag telling whether we are running as a pipe server. */
212 static int pipe_server;
214 /* Name of the communication socket */
215 static char *socket_name;
216 /* Name of the redirected socket or NULL. */
217 static char *redir_socket_name;
219 /* We need to keep track of the server's nonces (these are dummies for
221 static assuan_sock_nonce_t socket_nonce;
223 /* Debug flag to disable the ticker. The ticker is in fact not
224 disabled but it won't perform any ticker specific actions. */
225 static int ticker_disabled;
229 static char *create_socket_name (char *standard_name);
230 static gnupg_fd_t create_server_socket (const char *name,
232 assuan_sock_nonce_t *nonce);
234 static void *start_connection_thread (void *arg);
235 static void handle_connections (int listen_fd);
237 /* Pth wrapper function definitions. */
238 ASSUAN_SYSTEM_NPTH_IMPL;
240 static int active_connections;
244 make_libversion (const char *libname, const char *(*getfnc)(const char*))
251 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
255 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
256 strcpy (stpcpy (stpcpy (result, libname), " "), s);
262 my_strusage (int level)
264 static char *ver_gcry, *ver_ksba;
269 case 11: p = "@SCDAEMON@ (@GNUPG@)";
271 case 13: p = VERSION; break;
272 case 17: p = PRINTABLE_OS_NAME; break;
273 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
277 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
282 ver_ksba = make_libversion ("libksba", ksba_check_version);
286 case 40: p = _("Usage: @SCDAEMON@ [options] (-h for help)");
288 case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
289 "Smartcard daemon for @GNUPG@\n");
299 tid_log_callback (unsigned long *rvalue)
301 int len = sizeof (*rvalue);
304 thread = npth_self ();
305 if (sizeof (thread) < len)
306 len = sizeof (thread);
307 memcpy (rvalue, &thread, len);
309 return 2; /* Use use hex representation. */
313 /* Setup the debugging. With a LEVEL of NULL only the active debug
314 flags are propagated to the subsystems. With LEVEL set, a specific
315 set of debug flags is set; thus overriding all flags already
318 set_debug (const char *level)
320 int numok = (level && digitp (level));
321 int numlvl = numok? atoi (level) : 0;
325 else if (!strcmp (level, "none") || (numok && numlvl < 1))
327 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
328 opt.debug = DBG_IPC_VALUE;
329 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
330 opt.debug = DBG_IPC_VALUE;
331 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
332 opt.debug = (DBG_IPC_VALUE|DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
333 else if (!strcmp (level, "guru") || numok)
336 /* Unless the "guru" string has been used we don't want to allow
337 hashing debugging. The rationale is that people tend to
338 select the highest debug value and would then clutter their
339 disk with debug files which may reveal confidential data. */
341 opt.debug &= ~(DBG_HASHING_VALUE);
345 log_error (_("invalid debug-level '%s' given\n"), level);
350 if (opt.debug && !opt.verbose)
352 if (opt.debug && opt.quiet)
355 if (opt.debug & DBG_MPI_VALUE)
356 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
357 if (opt.debug & DBG_CRYPTO_VALUE )
358 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
359 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
362 parse_debug_flag (NULL, &opt.debug, debug_flags);
370 if (socket_name && *socket_name)
374 name = redir_socket_name? redir_socket_name : socket_name;
384 main (int argc, char **argv )
389 FILE *configfp = NULL;
390 char *configname = NULL;
392 unsigned int configlineno;
394 const char *debug_level = NULL;
395 int default_config =1;
398 int multi_server = 0;
402 char *logfile = NULL;
404 int gpgconf_list = 0;
405 const char *config_filename = NULL;
406 int allow_coredump = 0;
407 struct assuan_malloc_hooks malloc_hooks;
409 npth_t pipecon_handler;
411 early_system_init ();
412 set_strusage (my_strusage);
413 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
414 /* Please note that we may running SUID(ROOT), so be very CAREFUL
415 when adding any stuff between here and the call to INIT_SECMEM()
416 somewhere after the option parsing */
417 log_set_prefix ("scdaemon", GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
419 /* Make sure that our subsystems are ready. */
421 init_common_subsystems (&argc, &argv);
423 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
425 malloc_hooks.malloc = gcry_malloc;
426 malloc_hooks.realloc = gcry_realloc;
427 malloc_hooks.free = gcry_free;
428 assuan_set_malloc_hooks (&malloc_hooks);
429 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
430 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
432 setup_libassuan_logging (&opt.debug, NULL);
434 setup_libgcrypt_logging ();
435 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
437 disable_core_dumps ();
439 /* Set default options. */
441 opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
443 shell = getenv ("SHELL");
444 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
447 /* Check whether we have a config file on the commandline */
452 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
453 while (arg_parse( &pargs, opts))
455 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
457 else if (pargs.r_opt == oOptions)
458 { /* yes there is one, so we do not try the default one, but
459 read the option file when it is encountered at the
463 else if (pargs.r_opt == oNoOptions)
464 default_config = 0; /* --no-options */
465 else if (pargs.r_opt == oHomedir)
466 gnupg_set_homedir (pargs.r.ret_str);
469 /* initialize the secure memory. */
470 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
474 Now we are working under our real uid
479 configname = make_filename (gnupg_homedir (), SCDAEMON_NAME EXTSEP_S "conf",
487 pargs.flags= 1; /* do not remove the args */
492 configfp = fopen (configname, "r");
498 log_info (_("Note: no default option file '%s'\n"),
503 log_error (_("option file '%s': %s\n"),
504 configname, strerror(errno) );
510 if (parse_debug && configname )
511 log_info (_("reading options from '%s'\n"), configname );
515 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
519 case aGPGConfList: gpgconf_list = 1; break;
520 case aGPGConfTest: gpgconf_list = 2; break;
521 case oQuiet: opt.quiet = 1; break;
522 case oVerbose: opt.verbose++; break;
523 case oBatch: opt.batch=1; break;
526 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
528 pargs.r_opt = ARGPARSE_INVALID_ARG;
529 pargs.err = ARGPARSE_PRINT_ERROR;
532 case oDebugAll: opt.debug = ~0; break;
533 case oDebugLevel: debug_level = pargs.r.ret_str; break;
534 case oDebugWait: debug_wait = pargs.r.ret_int; break;
535 case oDebugAllowCoreDump:
536 enable_core_dumps ();
539 case oDebugCCIDDriver:
541 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
542 #endif /*HAVE_LIBUSB*/
544 case oDebugDisableTicker: ticker_disabled = 1; break;
546 log_set_pid_suffix_cb (tid_log_callback);
548 case oDebugAssuanLogCats:
549 set_libassuan_log_cats (pargs.r.ret_ulong);
553 /* config files may not be nested (silently ignore them) */
557 configname = xstrdup(pargs.r.ret_str);
561 case oNoGreeting: nogreeting = 1; break;
562 case oNoVerbose: opt.verbose = 0; break;
563 case oNoOptions: break; /* no-options */
564 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
565 case oNoDetach: nodetach = 1; break;
566 case oLogFile: logfile = pargs.r.ret_str; break;
567 case oCsh: csh_style = 1; break;
568 case oSh: csh_style = 0; break;
569 case oServer: pipe_server = 1; break;
570 case oMultiServer: pipe_server = 1; multi_server = 1; break;
571 case oDaemon: is_daemon = 1; break;
573 case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
574 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
575 case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
576 case oDisableCCID: opt.disable_ccid = 1; break;
577 case oDisableOpenSC: break;
579 case oDisablePinpad: opt.disable_pinpad = 1; break;
581 case oAllowAdmin: /* Dummy because allow is now the default. */
583 case oDenyAdmin: opt.allow_admin = 0; break;
585 case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
587 case oDisableApplication:
588 add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
591 case oEnablePinpadVarlen: opt.enable_pinpad_varlen = 1; break;
594 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
602 /* Keep a copy of the config name for use by --gpgconf-list. */
603 config_filename = configname;
609 if (log_get_errorcount(0))
616 es_fprintf (es_stderr, "%s %s; %s\n",
617 strusage(11), strusage(13), strusage(14) );
618 es_fprintf (es_stderr, "%s\n", strusage(15) );
620 #ifdef IS_DEVELOPMENT_VERSION
621 log_info ("NOTE: this is a development version!\n");
624 /* Print a warning if an argument looks like an option. */
625 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
629 for (i=0; i < argc; i++)
630 if (argv[i][0] == '-' && argv[i][1] == '-')
631 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
634 if (atexit (cleanup))
636 log_error ("atexit failed\n");
641 set_debug (debug_level);
643 initialize_module_command ();
645 if (gpgconf_list == 2)
649 /* List options and default values in the GPG Conf format. */
650 char *filename = NULL;
654 filename = xstrdup (config_filename);
656 filename = make_filename (gnupg_homedir (),
657 SCDAEMON_NAME EXTSEP_S "conf", NULL);
658 filename_esc = percent_escape (filename, NULL);
660 es_printf ("%s-%s.conf:%lu:\"%s\n",
661 GPGCONF_NAME, SCDAEMON_NAME,
662 GC_OPT_FLAG_DEFAULT, filename_esc);
663 xfree (filename_esc);
666 es_printf ("verbose:%lu:\n"
668 "debug-level:%lu:\"none:\n"
675 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
676 es_printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
677 es_printf ("pcsc-driver:%lu:\"%s:\n",
678 GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
680 es_printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
682 es_printf ("deny-admin:%lu:\n", GC_OPT_FLAG_NONE );
683 es_printf ("disable-pinpad:%lu:\n", GC_OPT_FLAG_NONE );
684 es_printf ("card-timeout:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, 0);
685 es_printf ("enable-pinpad-varlen:%lu:\n", GC_OPT_FLAG_NONE );
690 /* Now start with logging to a file if this is desired. */
693 log_set_file (logfile);
694 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
697 if (debug_wait && pipe_server)
699 log_debug ("waiting for debugger - my pid is %u .....\n",
700 (unsigned int)getpid());
701 gnupg_sleep (debug_wait);
702 log_debug ("... okay\n");
707 /* This is the simple pipe based server */
712 #ifndef HAVE_W32_SYSTEM
716 sa.sa_handler = SIG_IGN;
717 sigemptyset (&sa.sa_mask);
719 sigaction (SIGPIPE, &sa, NULL);
724 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
726 /* If --debug-allow-core-dump has been given we also need to
727 switch the working directory to a place where we can actually
732 log_debug ("chdir to '/tmp' failed: %s\n", strerror (errno));
734 log_debug ("changed working directory to '/tmp'\n");
737 /* In multi server mode we need to listen on an additional
738 socket. Create that socket now before starting the handler
739 for the pipe connection. This allows that handler to send
740 back the name of that socket. */
743 socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
744 fd = FD2INT(create_server_socket (socket_name,
745 &redir_socket_name, &socket_nonce));
748 res = npth_attr_init (&tattr);
751 log_error ("error allocating thread attributes: %s\n",
755 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
757 ctrl = xtrycalloc (1, sizeof *ctrl);
760 log_error ("error allocating connection control data: %s\n",
764 ctrl->thread_startup.fd = GNUPG_INVALID_FD;
765 res = npth_create (&pipecon_handler, &tattr, start_connection_thread, ctrl);
768 log_error ("error spawning pipe connection handler: %s\n",
773 npth_setname_np (pipecon_handler, "pipe-connection");
774 npth_attr_destroy (&tattr);
776 /* We run handle_connection to wait for the shutdown signal and
777 to run the ticker stuff. */
778 handle_connections (fd);
784 log_info (_("please use the option '--daemon'"
785 " to run the program in the background\n"));
788 { /* Regular server mode */
790 #ifndef HAVE_W32_SYSTEM
795 /* Create the socket. */
796 socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
797 fd = FD2INT (create_server_socket (socket_name,
798 &redir_socket_name, &socket_nonce));
802 #ifdef HAVE_W32_SYSTEM
807 if (pid == (pid_t)-1)
809 log_fatal ("fork failed: %s\n", strerror (errno) );
813 { /* we are the parent */
818 /* create the info string: <name>:<pid>:<protocol_version> */
819 if (gpgrt_asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
820 socket_name, (ulong) pid) < 0)
822 log_error ("out of core\n");
826 *socket_name = 0; /* don't let cleanup() remove the socket -
827 the child should do this from now on */
829 { /* run the program given on the commandline */
830 if (putenv (infostr))
832 log_error ("failed to set environment: %s\n",
834 kill (pid, SIGTERM );
837 execvp (argv[0], argv);
838 log_error ("failed to run the command: %s\n", strerror (errno));
844 /* Print the environment string, so that the caller can use
845 shell's eval to set it */
848 *strchr (infostr, '=') = ' ';
849 es_printf ( "setenv %s;\n", infostr);
853 es_printf ( "%s; export SCDAEMON_INFO;\n", infostr);
861 /* This is the child. */
864 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
866 /* Detach from tty and put process into a new session. */
869 /* Close stdin, stdout and stderr unless it is the log stream. */
870 for (i=0; i <= 2; i++)
872 if (!log_test_fd (i) && i != fd )
875 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
877 log_error ("failed to open '%s': %s\n",
878 "/dev/null", strerror (errno));
887 log_error ("setsid() failed: %s\n", strerror(errno) );
896 sa.sa_handler = SIG_IGN;
897 sigemptyset (&sa.sa_mask);
899 sigaction (SIGPIPE, &sa, NULL);
904 log_error ("chdir to / failed: %s\n", strerror (errno));
908 #endif /*!HAVE_W32_SYSTEM*/
910 handle_connections (fd);
921 apdu_prepare_exit ();
923 #warning no update_random_seed_file
924 update_random_seed_file();
927 /* at this time a bit annoying */
928 if (opt.debug & DBG_MEMSTAT_VALUE)
930 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
931 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
934 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
936 gcry_control (GCRYCTL_TERM_SECMEM );
937 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
943 scd_init_default_ctrl (ctrl_t ctrl)
949 scd_deinit_default_ctrl (ctrl_t ctrl)
953 xfree (ctrl->in_data.value);
954 ctrl->in_data.value = NULL;
955 ctrl->in_data.valuelen = 0;
959 /* Return the name of the socket to be used to connect to this
960 process. If no socket is available, return NULL. */
962 scd_get_socket_name ()
964 if (socket_name && *socket_name)
970 #ifndef HAVE_W32_SYSTEM
972 handle_signal (int signo)
977 log_info ("SIGHUP received - "
978 "re-reading configuration and resetting cards\n");
979 /* reread_configuration (); */
983 log_info ("SIGUSR1 received - printing internal information:\n");
984 /* Fixme: We need to see how to integrate pth dumping into our
986 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
991 log_info ("SIGUSR2 received - no action defined\n");
995 if (!shutdown_pending)
996 log_info ("SIGTERM received - shutting down ...\n");
998 log_info ("SIGTERM received - still %i running threads\n",
1001 if (shutdown_pending > 2)
1003 log_info ("shutdown forced\n");
1004 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1011 log_info ("SIGINT received - immediate shutdown\n");
1012 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1018 log_info ("signal %d received - no action defined\n", signo);
1021 #endif /*!HAVE_W32_SYSTEM*/
1027 if (!ticker_disabled)
1028 scd_update_reader_status_file ();
1032 /* Create a name for the socket. We check for valid characters as
1033 well as against a maximum allowed length for a unix domain socket
1034 is done. The function terminates the process in case of an error.
1035 Retunrs: Pointer to an allcoated string with the absolute name of
1038 create_socket_name (char *standard_name)
1042 name = make_filename (gnupg_socketdir (), standard_name, NULL);
1043 if (strchr (name, PATHSEP_C))
1045 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1053 /* Create a Unix domain socket with NAME. Returns the file descriptor
1054 or terminates the process in case of an error. If the socket has
1055 been redirected the name of the real socket is stored as a malloced
1056 string at R_REDIR_NAME. */
1058 create_server_socket (const char *name, char **r_redir_name,
1059 assuan_sock_nonce_t *nonce)
1061 struct sockaddr *addr;
1062 struct sockaddr_un *unaddr;
1067 xfree (*r_redir_name);
1068 *r_redir_name = NULL;
1070 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1071 if (fd == GNUPG_INVALID_FD)
1073 log_error (_("can't create socket: %s\n"), strerror (errno));
1077 unaddr = xmalloc (sizeof (*unaddr));
1078 addr = (struct sockaddr*)unaddr;
1083 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1085 if (errno == ENAMETOOLONG)
1086 log_error (_("socket name '%s' is too long\n"), name);
1088 log_error ("error preparing socket '%s': %s\n",
1089 name, gpg_strerror (gpg_error_from_syserror ()));
1094 *r_redir_name = xstrdup (unaddr->sun_path);
1096 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1100 len = SUN_LEN (unaddr);
1102 rc = assuan_sock_bind (fd, addr, len);
1103 if (rc == -1 && errno == EADDRINUSE)
1105 gnupg_remove (unaddr->sun_path);
1106 rc = assuan_sock_bind (fd, addr, len);
1109 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1110 log_error (_("error getting nonce for the socket\n"));
1113 log_error (_("error binding socket to '%s': %s\n"),
1115 gpg_strerror (gpg_error_from_syserror ()));
1116 assuan_sock_close (fd);
1120 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
1121 log_error (_("can't set permissions of '%s': %s\n"),
1122 unaddr->sun_path, strerror (errno));
1124 if (listen (FD2INT(fd), 5 ) == -1)
1126 log_error (_("listen() failed: %s\n"),
1127 gpg_strerror (gpg_error_from_syserror ()));
1128 assuan_sock_close (fd);
1133 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1140 /* This is the standard connection thread's main function. */
1142 start_connection_thread (void *arg)
1146 if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1147 && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1149 log_info (_("error reading nonce on fd %d: %s\n"),
1150 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1151 assuan_sock_close (ctrl->thread_startup.fd);
1156 scd_init_default_ctrl (ctrl);
1158 log_info (_("handler for fd %d started\n"),
1159 FD2INT(ctrl->thread_startup.fd));
1161 /* If this is a pipe server, we request a shutdown if the command
1162 handler asked for it. With the next ticker event and given that
1163 no other connections are running the shutdown will then
1165 if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1167 shutdown_pending = 1;
1170 log_info (_("handler for fd %d terminated\n"),
1171 FD2INT (ctrl->thread_startup.fd));
1173 scd_deinit_default_ctrl (ctrl);
1179 /* Connection handler loop. Wait for connection requests and spawn a
1180 thread after accepting a connection. LISTEN_FD is allowed to be -1
1181 in which case this code will only do regular timeouts and handle
1184 handle_connections (int listen_fd)
1187 struct sockaddr_un paddr;
1189 fd_set fdset, read_fdset;
1193 struct timespec abstime;
1194 struct timespec curtime;
1195 struct timespec timeout;
1197 #ifndef HAVE_W32_SYSTEM
1201 ret = npth_attr_init(&tattr);
1202 /* FIXME: Check error. */
1203 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1205 #ifndef HAVE_W32_SYSTEM
1207 npth_sigev_add (SIGHUP);
1208 npth_sigev_add (SIGUSR1);
1209 npth_sigev_add (SIGUSR2);
1210 npth_sigev_add (SIGINT);
1211 npth_sigev_add (SIGTERM);
1217 if (listen_fd != -1)
1219 FD_SET (listen_fd, &fdset);
1223 npth_clock_gettime (&curtime);
1224 timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1225 timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1226 npth_timeradd (&curtime, &timeout, &abstime);
1227 /* We only require abstime here. The others will be reused. */
1231 if (shutdown_pending)
1233 if (active_connections == 0)
1236 /* Do not accept anymore connections but wait for existing
1237 connections to terminate. We do this by clearing out all
1238 file descriptors to wait for, so that the select will be
1239 used to just wait on a signal or timeout event. */
1244 npth_clock_gettime (&curtime);
1245 if (!(npth_timercmp (&curtime, &abstime, <)))
1249 timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1250 timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1251 npth_timeradd (&curtime, &timeout, &abstime);
1253 npth_timersub (&abstime, &curtime, &timeout);
1255 /* POSIX says that fd_set should be implemented as a structure,
1256 thus a simple assignment is fine to copy the entire set. */
1259 #ifndef HAVE_W32_SYSTEM
1260 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask());
1261 saved_errno = errno;
1263 while (npth_sigev_get_pending(&signo))
1264 handle_signal (signo);
1266 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
1267 saved_errno = errno;
1270 if (ret == -1 && saved_errno != EINTR)
1272 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1273 strerror (saved_errno));
1279 /* Timeout. Will be handled when calculating the next timeout. */
1282 if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1286 plen = sizeof paddr;
1287 fd = npth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1290 log_error ("accept failed: %s\n", strerror (errno));
1292 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1294 log_error ("error allocating connection control data: %s\n",
1300 char threadname[50];
1303 snprintf (threadname, sizeof threadname, "conn fd=%d", fd);
1304 ctrl->thread_startup.fd = INT2FD (fd);
1305 ret = npth_create (&thread, &tattr, start_connection_thread, ctrl);
1308 log_error ("error spawning connection handler: %s\n",
1314 npth_setname_np (thread, threadname);
1321 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1322 npth_attr_destroy (&tattr);