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/>.
32 #ifndef HAVE_W32_SYSTEM
33 #include <sys/socket.h>
35 #endif /*HAVE_W32_SYSTEM*/
40 #define JNLIB_NEED_LOG_LOGV
45 #include <assuan.h> /* malloc hooks */
49 #include "app-common.h"
50 #ifdef HAVE_W32_SYSTEM
51 #include "../jnlib/w32-afunix.h"
53 #include "ccid-driver.h"
55 #include "gc-opt-flags.h"
58 enum cmd_and_opt_values
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,
129 N_("do not use the internal CCID driver")
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"
151 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
154 /* The timer tick used for housekeeping stuff. For Windows we use a
155 longer period as the SetWaitableTimer seems to signal earlier than
157 #ifdef HAVE_W32_SYSTEM
158 #define TIMERTICK_INTERVAL (4)
160 #define TIMERTICK_INTERVAL (2) /* Seconds. */
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;
197 my_strusage (int level
)
202 case 11: p
= "scdaemon (GnuPG)";
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");
209 case 40: p
= _("Usage: scdaemon [options] (-h for help)");
211 case 41: p
= _("Syntax: scdaemon [options] [command [args]]\n"
212 "Smartcard daemon for GnuPG\n");
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
229 set_debug (const char *level
)
233 else if (!strcmp (level
, "none"))
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"))
246 log_error (_("invalid debug-level `%s' given\n"), level
);
251 if (opt
.debug
&& !opt
.verbose
)
253 if (opt
.debug
&& opt
.quiet
)
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
);
268 if (socket_name
&& *socket_name
)
272 remove (socket_name
);
273 p
= strrchr (socket_name
, '/');
287 main (int argc
, char **argv
)
294 FILE *configfp
= NULL
;
295 char *configname
= NULL
;
297 unsigned int configlineno
;
299 const char *debug_level
= NULL
;
300 int default_config
=1;
304 int multi_server
= 0;
308 char *logfile
= NULL
;
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 ();
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
);
332 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
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") )
364 opt
.homedir
= default_homedir ();
366 /* Check whether we have a config file on the commandline */
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
)
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
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);
393 Now we are working under our real uid
398 configname
= make_filename (opt
.homedir
, "scdaemon.conf", NULL
);
405 pargs
.flags
= 1; /* do not remove the args */
410 configfp
= fopen (configname
, "r");
416 log_info (_("NOTE: no default option file `%s'\n"),
421 log_error (_("option file `%s': %s\n"),
422 configname
, strerror(errno
) );
428 if (parse_debug
&& configname
)
429 log_info (_("reading options from `%s'\n"), configname
);
433 while (optfile_parse( configfp
, configname
, &configlineno
, &pargs
, opts
) )
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 ();
451 case oDebugCCIDDriver
:
453 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
454 #endif /*HAVE_LIBUSB*/
456 case oDebugDisableTicker
: ticker_disabled
= 1; break;
459 /* config files may not be nested (silently ignore them) */
463 configname
= xstrdup(pargs
.r
.ret_str
);
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
);
494 default : pargs
.err
= configfp
? 1:2; break;
501 /* Keep a copy of the config name for use by --gpgconf-list. */
502 config_filename
= configname
;
508 if (log_get_errorcount(0))
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");
524 if (atexit (cleanup
))
526 log_error ("atexit failed\n");
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)
547 /* List options and default values in the GPG Conf format. */
548 char *filename
= NULL
;
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
);
560 printf ("verbose:%lu:\n"
562 "debug-level:%lu:\"none:\n"
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
);
574 printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE
);
576 printf ("allow-admin:%lu:\n", GC_OPT_FLAG_NONE
);
577 printf ("disable-keypad:%lu:\n", GC_OPT_FLAG_NONE
);
582 /* now start with logging to a file if this is desired */
585 log_set_file (logfile
);
586 log_set_prefix (NULL
, 1|2|4);
591 /* This is the simple pipe based server */
596 #ifndef HAVE_W32_SYSTEM
600 sa
.sa_handler
= SIG_IGN
;
601 sigemptyset (&sa
.sa_mask
);
603 sigaction (SIGPIPE
, &sa
, NULL
);
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
613 log_debug ("chdir to `/tmp' failed: %s\n", strerror (errno
));
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. */
624 socket_name
= create_socket_name (0,
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
);
639 log_error ("error allocating connection control data: %s\n",
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",
652 handle_connections (fd
);
658 log_info (_("please use the option `--daemon'"
659 " to run the program in the background\n"));
662 { /* Regular server mode */
667 /* Create the socket. */
668 socket_name
= create_socket_name (0,
670 "/tmp/gpg-XXXXXX/S.scdaemon");
672 fd
= create_server_socket (0, socket_name
);
676 #ifndef HAVE_W32_SYSTEM
678 if (pid
== (pid_t
)-1)
680 log_fatal ("fork failed: %s\n", strerror (errno
) );
684 { /* we are the parent */
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");
697 *socket_name
= 0; /* don't let cleanup() remove the socket -
698 the child should do this from now on */
700 { /* run the program given on the commandline */
701 if (putenv (infostr
))
703 log_error ("failed to set environment: %s\n",
705 kill (pid
, SIGTERM
);
708 execvp (argv
[0], argv
);
709 log_error ("failed to run the command: %s\n", strerror (errno
));
715 /* Print the environment string, so that the caller can use
716 shell's eval to set it */
719 *strchr (infostr
, '=') = ' ';
720 printf ( "setenv %s\n", infostr
);
724 printf ( "%s; export SCDAEMON_INFO;\n", infostr
);
732 /* This is the child. */
734 /* Detach from tty and put process into a new session. */
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
)
745 log_error ("setsid() failed: %s\n", strerror(errno
) );
754 sa
.sa_handler
= SIG_IGN
;
755 sigemptyset (&sa
.sa_mask
);
757 sigaction (SIGPIPE
, &sa
, NULL
);
762 log_error ("chdir to / failed: %s\n", strerror (errno
));
766 #endif /*!HAVE_W32_SYSTEM*/
768 handle_connections (fd
);
780 #warning no update_random_seed_file
781 update_random_seed_file();
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
);
791 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
793 gcry_control (GCRYCTL_TERM_SECMEM
);
794 rc
= rc
? rc
: log_get_errorcount(0)? 2 : 0;
800 scd_init_default_ctrl (ctrl_t ctrl
)
802 ctrl
->reader_slot
= -1;
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. */
815 scd_get_socket_name ()
817 if (socket_name
&& *socket_name
)
824 handle_signal (int signo
)
828 #ifndef HAVE_W32_SYSTEM
830 log_info ("SIGHUP received - "
831 "re-reading configuration and resetting cards\n");
832 /* reread_configuration (); */
836 log_info ("SIGUSR1 received - printing internal information:\n");
837 pth_ctrl (PTH_CTRL_DUMPSTATE
, log_get_stream ());
842 log_info ("SIGUSR2 received - no action defined\n");
846 if (!shutdown_pending
)
847 log_info ("SIGTERM received - shutting down ...\n");
849 log_info ("SIGTERM received - still %ld running threads\n",
850 pth_ctrl( PTH_CTRL_GETTHREADS
));
852 if (shutdown_pending
> 2)
854 log_info ("shutdown forced\n");
855 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
862 log_info ("SIGINT received - immediate shutdown\n");
863 log_info( "%s %s stopped\n", strusage(11), strusage(13));
867 #endif /*!HAVE_W32_SYSTEM*/
870 log_info ("signal %d received - no action defined\n", signo
);
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. */
892 create_socket_name (int use_standard_socket
,
893 char *standard_name
, char *template)
897 if (use_standard_socket
)
898 name
= make_filename (opt
.homedir
, standard_name
, NULL
);
901 name
= xstrdup (template);
902 p
= strrchr (name
, '/');
908 log_error (_("can't create directory `%s': %s\n"),
909 name
, strerror (errno
));
915 if (strchr (name
, PATHSEP_C
))
917 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S
);
920 if (strlen (name
) + 1 >= DIMof (struct sockaddr_un
, sun_path
) )
922 log_error (_("name of socket too long\n"));
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. */
934 create_server_socket (int is_standard_name
, const char *name
)
936 struct sockaddr_un
*serv_addr
;
941 #ifdef HAVE_W32_SYSTEM
942 fd
= _w32_sock_new (AF_UNIX
, SOCK_STREAM
, 0);
944 fd
= socket (AF_UNIX
, SOCK_STREAM
, 0);
948 log_error (_("can't create socket: %s\n"), strerror (errno
));
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 )
965 rc
= bind (fd
, (struct sockaddr
*) serv_addr
, len
);
968 rc
= bind (fd
, (struct sockaddr
*) serv_addr
, len
);
969 if (is_standard_name
&& rc
== -1 && errno
== EADDRINUSE
)
972 rc
= bind (fd
, (struct sockaddr
*) serv_addr
, len
);
977 log_error (_("error binding socket to `%s': %s\n"),
978 serv_addr
->sun_path
, strerror (errno
));
983 if (listen (fd
, 5 ) == -1)
985 log_error (_("listen() failed: %s\n"), strerror (errno
));
991 log_info (_("listening on socket `%s'\n"), serv_addr
->sun_path
);
998 /* This is the standard connection thread's main function. */
1000 start_connection_thread (void *arg
)
1004 scd_init_default_ctrl (ctrl
);
1006 log_info (_("handler for fd %d started\n"), ctrl
->thread_startup
.fd
);
1008 scd_command_handler (ctrl
, ctrl
->thread_startup
.fd
);
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
1017 if (ctrl
->thread_startup
.fd
== -1)
1018 shutdown_pending
= 1;
1020 scd_deinit_default_ctrl (ctrl
);
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
1031 handle_connections (int listen_fd
)
1034 pth_event_t ev
, time_ev
;
1037 struct sockaddr_un paddr
;
1039 fd_set fdset
, read_fdset
;
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
);
1059 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1065 if (listen_fd
!= -1)
1067 FD_SET (listen_fd
, &fdset
);
1075 if (shutdown_pending
)
1077 if (pth_ctrl (PTH_CTRL_GETTHREADS
) == 1)
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. */
1087 /* Create a timeout event if needed. */
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. */
1097 pth_event_concat (ev
, time_ev
, NULL
);
1098 ret
= pth_select_ev (nfd
+1, &read_fdset
, NULL
, NULL
, NULL
, ev
);
1100 pth_event_isolate (time_ev
);
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
);
1117 log_error (_("pth_select failed: %s - waiting 1s\n"),
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
);
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
))
1144 plen
= sizeof paddr
;
1145 fd
= pth_accept (listen_fd
, (struct sockaddr
*)&paddr
, &plen
);
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",
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",
1175 /* Restore the signal mask. */
1176 pth_sigmask (SIG_SETMASK
, &oldsigs
, NULL
);
1180 pth_event_free (ev
, PTH_FREE_ALL
);
1182 pth_event_free (time_ev
, PTH_FREE_ALL
);
1184 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));