Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / scd / scdaemon.c
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
5  *
6  * This file is part of GnuPG.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <config.h>
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #ifndef HAVE_W32_SYSTEM
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 #endif /*HAVE_W32_SYSTEM*/
38 #include <unistd.h>
39 #include <signal.h>
40 #include <npth.h>
41
42 #define INCLUDED_BY_MAIN_MODULE 1
43 #define GNUPG_COMMON_NEED_AFLOCAL
44 #include "scdaemon.h"
45 #include <ksba.h>
46 #include <gcrypt.h>
47
48 #include <assuan.h> /* malloc hooks */
49
50 #include "../common/i18n.h"
51 #include "../common/sysutils.h"
52 #include "iso7816.h"
53 #include "apdu.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"
59
60 #ifndef ENAMETOOLONG
61 # define ENAMETOOLONG EINVAL
62 #endif
63
64 enum cmd_and_opt_values
65 { aNull = 0,
66   oCsh            = 'c',
67   oQuiet          = 'q',
68   oSh             = 's',
69   oVerbose        = 'v',
70
71   oNoVerbose = 500,
72   aGPGConfList,
73   aGPGConfTest,
74   oOptions,
75   oDebug,
76   oDebugAll,
77   oDebugLevel,
78   oDebugWait,
79   oDebugAllowCoreDump,
80   oDebugCCIDDriver,
81   oDebugLogTid,
82   oDebugAssuanLogCats,
83   oNoGreeting,
84   oNoOptions,
85   oHomedir,
86   oNoDetach,
87   oNoGrab,
88   oLogFile,
89   oServer,
90   oMultiServer,
91   oDaemon,
92   oBatch,
93   oReaderPort,
94   oCardTimeout,
95   octapiDriver,
96   opcscDriver,
97   opcscShared,
98   oDisableCCID,
99   oDisableOpenSC,
100   oDisablePinpad,
101   oAllowAdmin,
102   oDenyAdmin,
103   oDisableApplication,
104   oEnablePinpadVarlen,
105   oListenBacklog,
106
107   oNoop
108 };
109
110
111
112 static ARGPARSE_OPTS opts[] = {
113   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
114   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
115
116   ARGPARSE_header (NULL, N_("Options used for startup")),
117
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", "@"),
128
129
130   ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
131
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")),
144
145
146   ARGPARSE_header ("Configuration",
147                    N_("Options controlling the configuration")),
148
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",
157 #ifdef HAVE_LIBUSB
158                                     N_("do not use the internal CCID driver")
159 #else
160                                     "@"
161 #endif
162                 /* end --disable-ccid */),
163   ARGPARSE_s_u (oCardTimeout, "card-timeout",
164                 N_("|N|disconnect the card after N seconds of inactivity")),
165
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", "@"),
173
174
175   ARGPARSE_header("Security", N_("Options controlling the security")),
176
177   ARGPARSE_s_n (oAllowAdmin, "allow-admin", "@"),
178   ARGPARSE_s_n (oDenyAdmin, "deny-admin",
179                 N_("deny the use of admin card commands")),
180
181   /* Stubs for options which are implemented by 2.3 or later.  */
182   ARGPARSE_s_s (oNoop, "application-priority", "@"),
183
184   ARGPARSE_end ()
185 };
186
187
188 /* The list of supported debug flags.  */
189 static struct debug_flags_s debug_flags [] =
190   {
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"  },
201     { 0, NULL }
202   };
203
204
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"
212 #else
213 #define DEFAULT_PCSC_DRIVER "libpcsclite.so"
214 #endif
215
216 /* The timer tick used to check card removal.
217
218    We poll every 500ms to let the user immediately know a status
219    change.
220
221    For a card reader with an interrupt endpoint, this timer is not
222    used with the internal CCID driver.
223
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)
233
234 /* Flag to indicate that a shutdown was requested. */
235 static int shutdown_pending;
236
237 /* It is possible that we are currently running under setuid permissions */
238 static int maybe_setuid = 1;
239
240 /* Flag telling whether we are running as a pipe server.  */
241 static int pipe_server;
242
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;
247
248 /* We need to keep track of the server's nonces (these are dummies for
249    POSIX systems). */
250 static assuan_sock_nonce_t socket_nonce;
251
252 /* Value for the listen() backlog argument.  Change at runtime with
253  * --listen-backlog.  */
254 static int listen_backlog = 64;
255
256 #ifdef HAVE_W32_SYSTEM
257 static HANDLE the_event;
258 #else
259 /* PID to notify update of usb devices.  */
260 static pid_t main_thread_pid;
261 #endif
262 #ifdef HAVE_PSELECT_NO_EINTR
263 /* FD to notify changes.  */
264 static int notify_fd;
265 #endif
266 \f
267 static char *create_socket_name (char *standard_name);
268 static gnupg_fd_t create_server_socket (const char *name,
269                                         char **r_redir_name,
270                                         assuan_sock_nonce_t *nonce);
271
272 static void *start_connection_thread (void *arg);
273 static void handle_connections (int listen_fd);
274
275 /* Pth wrapper function definitions. */
276 ASSUAN_SYSTEM_NPTH_IMPL;
277
278 static int active_connections;
279
280 \f
281 static char *
282 make_libversion (const char *libname, const char *(*getfnc)(const char*))
283 {
284   const char *s;
285   char *result;
286
287   if (maybe_setuid)
288     {
289       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
290       maybe_setuid = 0;
291     }
292   s = getfnc (NULL);
293   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
294   strcpy (stpcpy (stpcpy (result, libname), " "), s);
295   return result;
296 }
297
298
299 static const char *
300 my_strusage (int level)
301 {
302   static char *ver_gcry, *ver_ksba;
303   const char *p;
304
305   switch (level)
306     {
307     case  9: p = "GPL-3.0-or-later"; break;
308     case 11: p = "@SCDAEMON@ (@GNUPG@)";
309       break;
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;
314
315     case 20:
316       if (!ver_gcry)
317         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
318       p = ver_gcry;
319       break;
320     case 21:
321       if (!ver_ksba)
322         ver_ksba = make_libversion ("libksba", ksba_check_version);
323       p = ver_ksba;
324       break;
325     case 1:
326     case 40: p =  _("Usage: @SCDAEMON@ [options] (-h for help)");
327       break;
328     case 41: p =  _("Syntax: scdaemon [options] [command [args]]\n"
329                     "Smartcard daemon for @GNUPG@\n");
330     break;
331
332     default: p = NULL;
333     }
334   return p;
335 }
336
337
338 static int
339 tid_log_callback (unsigned long *rvalue)
340 {
341   int len = sizeof (*rvalue);
342   npth_t thread;
343
344   thread = npth_self ();
345   if (sizeof (thread) < len)
346     len = sizeof (thread);
347   memcpy (rvalue, &thread, len);
348
349   return 2; /* Use use hex representation.  */
350 }
351
352
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
356    set. */
357 static void
358 set_debug (const char *level)
359 {
360   int numok = (level && digitp (level));
361   int numlvl = numok? atoi (level) : 0;
362
363   if (!level)
364     ;
365   else if (!strcmp (level, "none") || (numok && numlvl < 1))
366     opt.debug = 0;
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)
374     {
375       opt.debug = ~0;
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.  */
380       if (numok)
381         opt.debug &= ~(DBG_HASHING_VALUE);
382     }
383   else
384     {
385       log_error (_("invalid debug-level '%s' given\n"), level);
386       scd_exit(2);
387     }
388
389
390   if (opt.debug && !opt.verbose)
391     opt.verbose = 1;
392   if (opt.debug && opt.quiet)
393     opt.quiet = 0;
394
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);
400
401   if (opt.debug)
402     parse_debug_flag (NULL, &opt.debug, debug_flags);
403 }
404
405
406
407 static void
408 cleanup (void)
409 {
410   if (socket_name && *socket_name)
411     {
412       char *name;
413
414       name = redir_socket_name? redir_socket_name : socket_name;
415
416       gnupg_remove (name);
417       *socket_name = 0;
418     }
419 }
420
421 static void
422 setup_signal_mask (void)
423 {
424 #ifndef HAVE_W32_SYSTEM
425   npth_sigev_init ();
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);
432   npth_sigev_fini ();
433   main_thread_pid = getpid ();
434 #endif
435 }
436
437 int
438 main (int argc, char **argv )
439 {
440   ARGPARSE_ARGS pargs;
441   int orig_argc;
442   char **orig_argv;
443   char *last_configname = NULL;
444   const char *configname = NULL;
445   const char *shell;
446   int debug_argparser = 0;
447   const char *debug_level = NULL;
448   int greeting = 0;
449   int nogreeting = 0;
450   int multi_server = 0;
451   int is_daemon = 0;
452   int nodetach = 0;
453   int csh_style = 0;
454   char *logfile = NULL;
455   int debug_wait = 0;
456   int gpgconf_list = 0;
457   char *config_filename = NULL;
458   int allow_coredump = 0;
459   struct assuan_malloc_hooks malloc_hooks;
460   int res;
461   npth_t pipecon_handler;
462
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);
470
471   /* Make sure that our subsystems are ready.  */
472   i18n_init ();
473   init_common_subsystems (&argc, &argv);
474
475   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
476
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);
483   assuan_sock_init ();
484   setup_libassuan_logging (&opt.debug, NULL);
485
486   setup_libgcrypt_logging ();
487   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
488
489   disable_core_dumps ();
490
491   /* Set default options. */
492   opt.allow_admin = 1;
493   opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
494
495   shell = getenv ("SHELL");
496   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
497     csh_style = 1;
498
499   /* Check whether we have a config file on the commandline */
500   orig_argc = argc;
501   orig_argv = argv;
502   pargs.argc = &argc;
503   pargs.argv = &argv;
504   pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
505   while (gnupg_argparse (NULL, &pargs, opts))
506     {
507       switch (pargs.r_opt)
508         {
509         case oDebug:
510         case oDebugAll:
511           debug_argparser++;
512           break;
513         case oHomedir:
514           gnupg_set_homedir (pargs.r.ret_str);
515           break;
516         }
517     }
518   /* Reset the flags.  */
519   pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
520
521   /* Initialize the secure memory. */
522   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
523   maybe_setuid = 0;
524
525   /*
526    * Now we are working under our real uid
527    */
528
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 ());
532
533   argc = orig_argc;
534   argv = orig_argv;
535   pargs.argc = &argc;
536   pargs.argv = &argv;
537   pargs.flags |=  (ARGPARSE_FLAG_RESET
538                    | ARGPARSE_FLAG_KEEP
539                    | ARGPARSE_FLAG_SYS
540                    | ARGPARSE_FLAG_USER);
541   while (gnupg_argparser (&pargs, opts, SCDAEMON_NAME EXTSEP_S "conf"))
542     {
543       switch (pargs.r_opt)
544         {
545         case ARGPARSE_CONFFILE:
546           if (debug_argparser)
547             log_info (_("reading options from '%s'\n"),
548                       pargs.r_type? pargs.r.ret_str: "[cmdline]");
549           if (pargs.r_type)
550             {
551               xfree (last_configname);
552               last_configname = xstrdup (pargs.r.ret_str);
553               configname = last_configname;
554             }
555           else
556             configname = NULL;
557           break;
558
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;
564
565         case oDebug:
566           if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
567             {
568               pargs.r_opt = ARGPARSE_INVALID_ARG;
569               pargs.err = ARGPARSE_PRINT_ERROR;
570             }
571           break;
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 ();
577           allow_coredump = 1;
578           break;
579         case oDebugCCIDDriver:
580 #ifdef HAVE_LIBUSB
581           ccid_set_debug_level (ccid_set_debug_level (-1)+1);
582 #endif /*HAVE_LIBUSB*/
583           break;
584         case oDebugLogTid:
585           log_set_pid_suffix_cb (tid_log_callback);
586           break;
587         case oDebugAssuanLogCats:
588           set_libassuan_log_cats (pargs.r.ret_ulong);
589           break;
590
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;
601
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;
608
609         case oDisablePinpad: opt.disable_pinpad = 1; break;
610
611         case oAllowAdmin: /* Dummy because allow is now the default.  */
612           break;
613         case oDenyAdmin: opt.allow_admin = 0; break;
614
615         case oCardTimeout: opt.card_timeout = pargs.r.ret_ulong; break;
616
617         case oDisableApplication:
618           add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
619           break;
620
621         case oEnablePinpadVarlen: opt.enable_pinpad_varlen = 1; break;
622
623         case oListenBacklog:
624           listen_backlog = pargs.r.ret_int;
625           break;
626
627         case oNoop: break;
628
629         default:
630           if (configname)
631             pargs.err = ARGPARSE_PRINT_WARNING;
632           else
633             pargs.err = ARGPARSE_PRINT_ERROR;
634           break;
635         }
636     }
637   gnupg_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
638
639   if (!last_configname)
640     config_filename = make_filename (gnupg_homedir (),
641                                      SCDAEMON_NAME EXTSEP_S "conf",
642                                      NULL);
643   else
644     {
645       config_filename = last_configname;
646       last_configname = NULL;
647     }
648
649   if (log_get_errorcount(0))
650     exit(2);
651   if (nogreeting )
652     greeting = 0;
653
654   if (greeting)
655     {
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) );
659     }
660 #ifdef IS_DEVELOPMENT_VERSION
661   log_info ("NOTE: this is a development version!\n");
662 #endif
663
664   /* Print a warning if an argument looks like an option.  */
665   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
666     {
667       int i;
668
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]);
672     }
673
674   if (atexit (cleanup))
675     {
676       log_error ("atexit failed\n");
677       cleanup ();
678       exit (1);
679     }
680
681   set_debug (debug_level);
682
683   if (initialize_module_command ())
684     {
685       log_error ("initialization failed\n");
686       cleanup ();
687       exit (1);
688     }
689
690   if (gpgconf_list == 2)
691     scd_exit (0);
692   if (gpgconf_list)
693     {
694       /* List options and default values in the GPG Conf format.  */
695       char *filename_esc;
696
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);
702
703       es_printf ("verbose:%lu:\n"
704                  "quiet:%lu:\n"
705                  "debug-level:%lu:\"none:\n"
706                  "log-file:%lu:\n",
707                  GC_OPT_FLAG_NONE,
708                  GC_OPT_FLAG_NONE,
709                  GC_OPT_FLAG_DEFAULT,
710                  GC_OPT_FLAG_NONE );
711
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 );
716 #ifdef HAVE_LIBUSB
717       es_printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
718 #endif
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 );
723
724       scd_exit (0);
725     }
726
727   /* Now start with logging to a file if this is desired.  */
728   if (logfile)
729     {
730       log_set_file (logfile);
731       log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
732     }
733
734   if (debug_wait && pipe_server)
735     {
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");
740     }
741
742   if (pipe_server)
743     {
744       /* This is the simple pipe based server */
745       ctrl_t ctrl;
746       npth_attr_t tattr;
747       int fd = -1;
748
749 #ifndef HAVE_W32_SYSTEM
750       {
751         struct sigaction sa;
752
753         sa.sa_handler = SIG_IGN;
754         sigemptyset (&sa.sa_mask);
755         sa.sa_flags = 0;
756         sigaction (SIGPIPE, &sa, NULL);
757       }
758 #endif
759
760       npth_init ();
761       setup_signal_mask ();
762       gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
763
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
766          write. */
767       if (allow_coredump)
768         {
769           if (chdir("/tmp"))
770             log_debug ("chdir to '/tmp' failed: %s\n", strerror (errno));
771           else
772             log_debug ("changed working directory to '/tmp'\n");
773         }
774
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. */
779       if (multi_server)
780         {
781           socket_name = create_socket_name (SCDAEMON_SOCK_NAME);
782           fd = FD2INT(create_server_socket (socket_name,
783                                             &redir_socket_name, &socket_nonce));
784         }
785
786       res = npth_attr_init (&tattr);
787       if (res)
788         {
789           log_error ("error allocating thread attributes: %s\n",
790                      strerror (res));
791           scd_exit (2);
792         }
793       npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
794
795       ctrl = xtrycalloc (1, sizeof *ctrl);
796       if ( !ctrl )
797         {
798           log_error ("error allocating connection control data: %s\n",
799                      strerror (errno) );
800           scd_exit (2);
801         }
802       ctrl->thread_startup.fd = GNUPG_INVALID_FD;
803       res = npth_create (&pipecon_handler, &tattr, start_connection_thread, ctrl);
804       if (res)
805         {
806           log_error ("error spawning pipe connection handler: %s\n",
807                      strerror (res) );
808           xfree (ctrl);
809           scd_exit (2);
810         }
811       npth_setname_np (pipecon_handler, "pipe-connection");
812       npth_attr_destroy (&tattr);
813
814       /* We run handle_connection to wait for the shutdown signal and
815          to run the ticker stuff.  */
816       handle_connections (fd);
817       if (fd != -1)
818         close (fd);
819     }
820   else if (!is_daemon)
821     {
822       log_info (_("please use the option '--daemon'"
823                   " to run the program in the background\n"));
824     }
825   else
826     { /* Regular server mode */
827       int fd;
828 #ifndef HAVE_W32_SYSTEM
829       pid_t pid;
830       int i;
831 #endif
832
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));
837
838
839       fflush (NULL);
840 #ifdef HAVE_W32_SYSTEM
841       (void)csh_style;
842       (void)nodetach;
843 #else
844       pid = fork ();
845       if (pid == (pid_t)-1)
846         {
847           log_fatal ("fork failed: %s\n", strerror (errno) );
848           exit (1);
849         }
850       else if (pid)
851         { /* we are the parent */
852           char *infostr;
853
854           close (fd);
855
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)
859             {
860               log_error ("out of core\n");
861               kill (pid, SIGTERM);
862               exit (1);
863             }
864           *socket_name = 0; /* don't let cleanup() remove the socket -
865                                the child should do this from now on */
866           if (argc)
867             { /* run the program given on the commandline */
868               if (putenv (infostr))
869                 {
870                   log_error ("failed to set environment: %s\n",
871                              strerror (errno) );
872                   kill (pid, SIGTERM );
873                   exit (1);
874                 }
875               execvp (argv[0], argv);
876               log_error ("failed to run the command: %s\n", strerror (errno));
877               kill (pid, SIGTERM);
878               exit (1);
879             }
880           else
881             {
882               /* Print the environment string, so that the caller can use
883                  shell's eval to set it */
884               if (csh_style)
885                 {
886                   *strchr (infostr, '=') = ' ';
887                   es_printf ( "setenv %s;\n", infostr);
888                 }
889               else
890                 {
891                   es_printf ( "%s; export SCDAEMON_INFO;\n", infostr);
892                 }
893               xfree (infostr);
894               exit (0);
895             }
896           /* NOTREACHED */
897         } /* end parent */
898
899       /* This is the child. */
900
901       npth_init ();
902       setup_signal_mask ();
903       gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
904
905       /* Detach from tty and put process into a new session. */
906       if (!nodetach )
907         {
908           /* Close stdin, stdout and stderr unless it is the log stream. */
909           for (i=0; i <= 2; i++)
910             {
911               if (!log_test_fd (i) && i != fd )
912                 {
913                   if ( !close (i)
914                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
915                     {
916                       log_error ("failed to open '%s': %s\n",
917                                  "/dev/null", strerror (errno));
918                       cleanup ();
919                       exit (1);
920                     }
921                 }
922             }
923
924           if (setsid() == -1)
925             {
926               log_error ("setsid() failed: %s\n", strerror(errno) );
927               cleanup ();
928               exit (1);
929             }
930         }
931
932       {
933         struct sigaction sa;
934
935         sa.sa_handler = SIG_IGN;
936         sigemptyset (&sa.sa_mask);
937         sa.sa_flags = 0;
938         sigaction (SIGPIPE, &sa, NULL);
939       }
940
941 #endif /*!HAVE_W32_SYSTEM*/
942
943       if (gnupg_chdir (gnupg_daemon_rootdir ()))
944         {
945           log_error ("chdir to '%s' failed: %s\n",
946                      gnupg_daemon_rootdir (), strerror (errno));
947           exit (1);
948         }
949
950       handle_connections (fd);
951
952       close (fd);
953     }
954
955   xfree (config_filename);
956   return 0;
957 }
958
959
960 void
961 scd_exit (int rc)
962 {
963   apdu_prepare_exit ();
964 #if 0
965 #warning no update_random_seed_file
966   update_random_seed_file();
967 #endif
968 #if 0
969   /* at this time a bit annoying */
970   if (opt.debug & DBG_MEMSTAT_VALUE)
971     {
972       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
973       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
974     }
975   if (opt.debug)
976     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
977 #endif
978   gcry_control (GCRYCTL_TERM_SECMEM );
979   rc = rc? rc : log_get_errorcount(0)? 2 : 0;
980   exit (rc);
981 }
982
983
984 static void
985 scd_init_default_ctrl (ctrl_t ctrl)
986 {
987   (void)ctrl;
988 }
989
990 static void
991 scd_deinit_default_ctrl (ctrl_t ctrl)
992 {
993   if (!ctrl)
994     return;
995   xfree (ctrl->in_data.value);
996   ctrl->in_data.value = NULL;
997   ctrl->in_data.valuelen = 0;
998 }
999
1000
1001 /* Return the name of the socket to be used to connect to this
1002    process.  If no socket is available, return NULL. */
1003 const char *
1004 scd_get_socket_name ()
1005 {
1006   if (socket_name && *socket_name)
1007     return socket_name;
1008   return NULL;
1009 }
1010
1011
1012 #ifndef HAVE_W32_SYSTEM
1013 static void
1014 handle_signal (int signo)
1015 {
1016   switch (signo)
1017     {
1018     case SIGHUP:
1019       log_info ("SIGHUP received - "
1020                 "re-reading configuration and resetting cards\n");
1021 /*       reread_configuration (); */
1022       break;
1023
1024     case SIGUSR1:
1025       log_info ("SIGUSR1 received - printing internal information:\n");
1026       /* Fixme: We need to see how to integrate pth dumping into our
1027          logging system.  */
1028       /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1029       app_dump_state ();
1030       break;
1031
1032     case SIGUSR2:
1033       log_info ("SIGUSR2 received - no action defined\n");
1034       break;
1035
1036     case SIGCONT:
1037       /* Nothing.  */
1038       log_debug ("SIGCONT received - breaking select\n");
1039       break;
1040
1041     case SIGTERM:
1042       if (!shutdown_pending)
1043         log_info ("SIGTERM received - shutting down ...\n");
1044       else
1045         log_info ("SIGTERM received - still %i running threads\n",
1046                   active_connections);
1047       shutdown_pending++;
1048       if (shutdown_pending > 2)
1049         {
1050           log_info ("shutdown forced\n");
1051           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1052           cleanup ();
1053           scd_exit (0);
1054         }
1055       break;
1056
1057     case SIGINT:
1058       log_info ("SIGINT received - immediate shutdown\n");
1059       log_info( "%s %s stopped\n", strusage(11), strusage(13));
1060       cleanup ();
1061       scd_exit (0);
1062       break;
1063
1064     default:
1065       log_info ("signal %d received - no action defined\n", signo);
1066     }
1067 }
1068 #endif /*!HAVE_W32_SYSTEM*/
1069
1070
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
1075    the socket used.  */
1076 static char *
1077 create_socket_name (char *standard_name)
1078 {
1079   char *name;
1080
1081   name = make_filename (gnupg_socketdir (), standard_name, NULL);
1082   if (strchr (name, PATHSEP_C))
1083     {
1084       log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1085       scd_exit (2);
1086     }
1087   return name;
1088 }
1089
1090
1091
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. */
1096 static gnupg_fd_t
1097 create_server_socket (const char *name, char **r_redir_name,
1098                       assuan_sock_nonce_t *nonce)
1099 {
1100   struct sockaddr *addr;
1101   struct sockaddr_un *unaddr;
1102   socklen_t len;
1103   gnupg_fd_t fd;
1104   int rc;
1105
1106   xfree (*r_redir_name);
1107   *r_redir_name = NULL;
1108
1109   fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1110   if (fd == GNUPG_INVALID_FD)
1111     {
1112       log_error (_("can't create socket: %s\n"), strerror (errno));
1113       scd_exit (2);
1114     }
1115
1116   unaddr = xmalloc (sizeof (*unaddr));
1117   addr = (struct sockaddr*)unaddr;
1118
1119   {
1120     int redirected;
1121
1122     if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1123       {
1124         if (errno == ENAMETOOLONG)
1125           log_error (_("socket name '%s' is too long\n"), name);
1126         else
1127           log_error ("error preparing socket '%s': %s\n",
1128                      name, gpg_strerror (gpg_error_from_syserror ()));
1129         scd_exit (2);
1130       }
1131     if (redirected)
1132       {
1133         *r_redir_name = xstrdup (unaddr->sun_path);
1134         if (opt.verbose)
1135           log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1136       }
1137   }
1138
1139   len = SUN_LEN (unaddr);
1140
1141   rc = assuan_sock_bind (fd, addr, len);
1142   if (rc == -1 && errno == EADDRINUSE)
1143     {
1144       gnupg_remove (unaddr->sun_path);
1145       rc = assuan_sock_bind (fd, addr, len);
1146     }
1147   if (rc != -1
1148       && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1149     log_error (_("error getting nonce for the socket\n"));
1150  if (rc == -1)
1151     {
1152       log_error (_("error binding socket to '%s': %s\n"),
1153                  unaddr->sun_path,
1154                  gpg_strerror (gpg_error_from_syserror ()));
1155       assuan_sock_close (fd);
1156       scd_exit (2);
1157     }
1158
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));
1162
1163   if (listen (FD2INT(fd), listen_backlog) == -1)
1164     {
1165       log_error ("listen(fd, %d) failed: %s\n",
1166                  listen_backlog, gpg_strerror (gpg_error_from_syserror ()));
1167       assuan_sock_close (fd);
1168       scd_exit (2);
1169     }
1170
1171   if (opt.verbose)
1172     log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1173
1174   return fd;
1175 }
1176
1177
1178
1179 /* This is the standard connection thread's main function.  */
1180 static void *
1181 start_connection_thread (void *arg)
1182 {
1183   ctrl_t ctrl = arg;
1184
1185   if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1186       && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1187     {
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);
1191       xfree (ctrl);
1192       return NULL;
1193     }
1194
1195   active_connections++;
1196
1197   scd_init_default_ctrl (ctrl);
1198   if (opt.verbose)
1199     log_info (_("handler for fd %d started\n"),
1200               FD2INT(ctrl->thread_startup.fd));
1201
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
1205      happen.  */
1206   if (scd_command_handler (ctrl, FD2INT(ctrl->thread_startup.fd))
1207       && pipe_server)
1208     shutdown_pending = 1;
1209
1210   if (opt.verbose)
1211     log_info (_("handler for fd %d terminated\n"),
1212               FD2INT (ctrl->thread_startup.fd));
1213
1214   scd_deinit_default_ctrl (ctrl);
1215   xfree (ctrl);
1216
1217   if (--active_connections == 0)
1218     scd_kick_the_loop ();
1219
1220   return NULL;
1221 }
1222
1223
1224 void
1225 scd_kick_the_loop (void)
1226 {
1227   /* Kick the select loop.  */
1228 #ifdef HAVE_W32_SYSTEM
1229   int ret = SetEvent (the_event);
1230   if (ret == 0)
1231     log_error ("SetEvent for scd_kick_the_loop failed: %s\n",
1232                w32_strerror (-1));
1233 #elif defined(HAVE_PSELECT_NO_EINTR)
1234   write (notify_fd, "", 1);
1235 #else
1236   int ret = kill (main_thread_pid, SIGCONT);
1237   if (ret < 0)
1238     log_error ("sending signal for scd_kick_the_loop failed: %s\n",
1239                gpg_strerror (gpg_error_from_syserror ()));
1240 #endif
1241 }
1242
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
1246    signals. */
1247 static void
1248 handle_connections (int listen_fd)
1249 {
1250   npth_attr_t tattr;
1251   struct sockaddr_un paddr;
1252   socklen_t plen;
1253   fd_set fdset, read_fdset;
1254   int nfd;
1255   int ret;
1256   int fd;
1257   struct timespec timeout;
1258   struct timespec *t;
1259   int saved_errno;
1260 #ifdef HAVE_W32_SYSTEM
1261   HANDLE events[2];
1262   unsigned int events_set;
1263 #else
1264   int signo;
1265 #endif
1266 #ifdef HAVE_PSELECT_NO_EINTR
1267   int pipe_fd[2];
1268
1269   ret = gnupg_create_pipe (pipe_fd);
1270   if (ret)
1271     {
1272       log_error ("pipe creation failed: %s\n", gpg_strerror (ret));
1273       return;
1274     }
1275   notify_fd = pipe_fd[1];
1276 #endif
1277
1278   ret = npth_attr_init(&tattr);
1279   if (ret)
1280     {
1281       log_error ("npth_attr_init failed: %s\n", strerror (ret));
1282       return;
1283     }
1284
1285   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1286
1287 #ifdef HAVE_W32_SYSTEM
1288   {
1289     HANDLE h, h2;
1290     SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1291
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);
1297     if (!h)
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))
1302       {
1303         log_error ("setting synchronize for scd_kick_the_loop failed: %s\n",
1304                    w32_strerror (-1) );
1305         CloseHandle (h);
1306       }
1307     else
1308       {
1309         CloseHandle (h);
1310         events[0] = the_event = h2;
1311       }
1312   }
1313 #endif
1314
1315   FD_ZERO (&fdset);
1316   nfd = 0;
1317   if (listen_fd != -1)
1318     {
1319       FD_SET (listen_fd, &fdset);
1320       nfd = listen_fd;
1321     }
1322
1323   for (;;)
1324     {
1325       int periodical_check;
1326       int max_fd = nfd;
1327
1328       if (shutdown_pending)
1329         {
1330           if (active_connections == 0)
1331             break; /* ready */
1332
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. */
1337           FD_ZERO (&fdset);
1338           listen_fd = -1;
1339         }
1340
1341       periodical_check = scd_update_reader_status_file ();
1342
1343       timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1344       timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1345
1346       if (shutdown_pending || periodical_check)
1347         t = &timeout;
1348       else
1349         t = NULL;
1350
1351       /* POSIX says that fd_set should be implemented as a structure,
1352          thus a simple assignment is fine to copy the entire set.  */
1353       read_fdset = fdset;
1354
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];
1359 #else
1360       (void)max_fd;
1361 #endif
1362
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;
1367
1368       while (npth_sigev_get_pending(&signo))
1369         handle_signal (signo);
1370 #else
1371       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, t,
1372                           events, &events_set);
1373       saved_errno = errno;
1374       if (events_set & 1)
1375         continue;
1376 #endif
1377
1378       if (ret == -1 && saved_errno != EINTR)
1379         {
1380           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1381                      strerror (saved_errno));
1382           npth_sleep (1);
1383           continue;
1384         }
1385
1386       if (ret <= 0)
1387         /* Timeout.  Will be handled when calculating the next timeout.  */
1388         continue;
1389
1390 #ifdef HAVE_PSELECT_NO_EINTR
1391       if (FD_ISSET (pipe_fd[0], &read_fdset))
1392         {
1393           char buf[256];
1394
1395           read (pipe_fd[0], buf, sizeof buf);
1396         }
1397 #endif
1398
1399       if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1400         {
1401           ctrl_t ctrl;
1402
1403           plen = sizeof paddr;
1404           fd = npth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1405           if (fd == -1)
1406             {
1407               log_error ("accept failed: %s\n", strerror (errno));
1408             }
1409           else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1410             {
1411               log_error ("error allocating connection control data: %s\n",
1412                          strerror (errno) );
1413               close (fd);
1414             }
1415           else
1416             {
1417               char threadname[50];
1418               npth_t thread;
1419
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);
1423               if (ret)
1424                 {
1425                   log_error ("error spawning connection handler: %s\n",
1426                              strerror (ret));
1427                   xfree (ctrl);
1428                   close (fd);
1429                 }
1430               else
1431                 npth_setname_np (thread, threadname);
1432             }
1433         }
1434     }
1435
1436 #ifdef HAVE_W32_SYSTEM
1437   if (the_event != INVALID_HANDLE_VALUE)
1438     CloseHandle (the_event);
1439 #endif
1440 #ifdef HAVE_PSELECT_NO_EINTR
1441   close (pipe_fd[0]);
1442   close (pipe_fd[1]);
1443 #endif
1444   cleanup ();
1445   log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1446   npth_attr_destroy (&tattr);
1447 }
1448
1449 /* Return the number of active connections. */
1450 int
1451 get_active_connection_count (void)
1452 {
1453   return active_connections;
1454 }