chiark / gitweb /
agent: Allow threads to interrupt main select loop with SIGCONT.
[gnupg2.git] / agent / gpg-agent.c
1 /* gpg-agent.c  -  The GnuPG Agent
2  * Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc.
3  * Copyright (C) 2000-2016 Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <time.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #ifdef HAVE_W32_SYSTEM
34 # ifndef WINVER
35 #  define WINVER 0x0500  /* Same as in common/sysutils.c */
36 # endif
37 # ifdef HAVE_WINSOCK2_H
38 #  include <winsock2.h>
39 # endif
40 # include <aclapi.h>
41 # include <sddl.h>
42 #else /*!HAVE_W32_SYSTEM*/
43 # include <sys/socket.h>
44 # include <sys/un.h>
45 #endif /*!HAVE_W32_SYSTEM*/
46 #include <unistd.h>
47 #ifdef HAVE_SIGNAL_H
48 # include <signal.h>
49 #endif
50 #include <npth.h>
51 #ifdef HAVE_PRCTL
52 # include <sys/prctl.h>
53 #endif
54
55 #define GNUPG_COMMON_NEED_AFLOCAL
56 #include "agent.h"
57 #include <assuan.h> /* Malloc hooks  and socket wrappers. */
58
59 #include "i18n.h"
60 #include "sysutils.h"
61 #include "gc-opt-flags.h"
62 #include "exechelp.h"
63 #include "asshelp.h"
64 #include "../common/init.h"
65
66
67 enum cmd_and_opt_values
68 { aNull = 0,
69   oCsh            = 'c',
70   oQuiet          = 'q',
71   oSh             = 's',
72   oVerbose        = 'v',
73
74   oNoVerbose = 500,
75   aGPGConfList,
76   aGPGConfTest,
77   aUseStandardSocketP,
78   oOptions,
79   oDebug,
80   oDebugAll,
81   oDebugLevel,
82   oDebugWait,
83   oDebugQuickRandom,
84   oDebugPinentry,
85   oNoGreeting,
86   oNoOptions,
87   oHomedir,
88   oNoDetach,
89   oNoGrab,
90   oLogFile,
91   oServer,
92   oDaemon,
93   oSupervised,
94   oBatch,
95
96   oPinentryProgram,
97   oPinentryTouchFile,
98   oPinentryInvisibleChar,
99   oPinentryTimeout,
100   oDisplay,
101   oTTYname,
102   oTTYtype,
103   oLCctype,
104   oLCmessages,
105   oXauthority,
106   oScdaemonProgram,
107   oDefCacheTTL,
108   oDefCacheTTLSSH,
109   oMaxCacheTTL,
110   oMaxCacheTTLSSH,
111   oEnforcePassphraseConstraints,
112   oMinPassphraseLen,
113   oMinPassphraseNonalpha,
114   oCheckPassphrasePattern,
115   oMaxPassphraseDays,
116   oEnablePassphraseHistory,
117   oUseStandardSocket,
118   oNoUseStandardSocket,
119   oExtraSocket,
120   oBrowserSocket,
121   oFakedSystemTime,
122
123   oIgnoreCacheForSigning,
124   oAllowMarkTrusted,
125   oNoAllowMarkTrusted,
126   oAllowPresetPassphrase,
127   oAllowLoopbackPinentry,
128   oNoAllowLoopbackPinentry,
129   oNoAllowExternalCache,
130   oAllowEmacsPinentry,
131   oKeepTTY,
132   oKeepDISPLAY,
133   oSSHSupport,
134   oPuttySupport,
135   oDisableScdaemon,
136   oDisableCheckOwnSocket,
137   oWriteEnvFile
138 };
139
140
141 #ifndef ENAMETOOLONG
142 # define ENAMETOOLONG EINVAL
143 #endif
144
145
146 static ARGPARSE_OPTS opts[] = {
147
148   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
149   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
150   ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
151
152   ARGPARSE_group (301, N_("@Options:\n ")),
153
154   ARGPARSE_s_n (oDaemon,  "daemon", N_("run in daemon mode (background)")),
155   ARGPARSE_s_n (oServer,  "server", N_("run in server mode (foreground)")),
156 #ifndef HAVE_W32_SYSTEM
157   ARGPARSE_s_n (oSupervised,  "supervised", N_("run in supervised mode")),
158 #endif
159   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
160   ARGPARSE_s_n (oQuiet,   "quiet",     N_("be somewhat more quiet")),
161   ARGPARSE_s_n (oSh,      "sh",        N_("sh-style command output")),
162   ARGPARSE_s_n (oCsh,     "csh",       N_("csh-style command output")),
163   ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
164
165   ARGPARSE_s_s (oDebug,      "debug",       "@"),
166   ARGPARSE_s_n (oDebugAll,   "debug-all",   "@"),
167   ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
168   ARGPARSE_s_i (oDebugWait,"  debug-wait",  "@"),
169   ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
170   ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
171
172   ARGPARSE_s_n (oNoDetach,  "no-detach", N_("do not detach from the console")),
173   ARGPARSE_s_n (oNoGrab,    "no-grab",   N_("do not grab keyboard and mouse")),
174   ARGPARSE_s_s (oLogFile,   "log-file",  N_("use a log file for the server")),
175   ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
176                 /* */             N_("|PGM|use PGM as the PIN-Entry program")),
177   ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
178   ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
179   ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
180   ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
181                 /* */             N_("|PGM|use PGM as the SCdaemon program") ),
182   ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
183                 /* */             N_("do not use the SCdaemon") ),
184   ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
185
186   ARGPARSE_s_s (oExtraSocket, "extra-socket",
187                 /* */       N_("|NAME|accept some commands via NAME")),
188
189   ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
190
191   ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
192
193   ARGPARSE_s_n (oBatch,      "batch",        "@"),
194   ARGPARSE_s_s (oHomedir,    "homedir",      "@"),
195
196   ARGPARSE_s_s (oDisplay,    "display",     "@"),
197   ARGPARSE_s_s (oTTYname,    "ttyname",     "@"),
198   ARGPARSE_s_s (oTTYtype,    "ttytype",     "@"),
199   ARGPARSE_s_s (oLCctype,    "lc-ctype",    "@"),
200   ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
201   ARGPARSE_s_s (oXauthority, "xauthority",  "@"),
202   ARGPARSE_s_n (oKeepTTY,    "keep-tty",
203                 /* */        N_("ignore requests to change the TTY")),
204   ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
205                 /* */        N_("ignore requests to change the X display")),
206
207   ARGPARSE_s_u (oDefCacheTTL,    "default-cache-ttl",
208                                  N_("|N|expire cached PINs after N seconds")),
209   ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
210   ARGPARSE_s_u (oMaxCacheTTL,    "max-cache-ttl",         "@" ),
211   ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh",     "@" ),
212
213   ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
214                 /* */                          "@"),
215   ARGPARSE_s_u (oMinPassphraseLen,        "min-passphrase-len", "@"),
216   ARGPARSE_s_u (oMinPassphraseNonalpha,   "min-passphrase-nonalpha", "@"),
217   ARGPARSE_s_s (oCheckPassphrasePattern,  "check-passphrase-pattern", "@"),
218   ARGPARSE_s_u (oMaxPassphraseDays,       "max-passphrase-days", "@"),
219   ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
220
221   ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
222                 /* */    N_("do not use the PIN cache when signing")),
223   ARGPARSE_s_n (oNoAllowExternalCache,  "no-allow-external-cache",
224                 /* */    N_("disallow the use of an external password cache")),
225   ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
226                 /* */    N_("disallow clients to mark keys as \"trusted\"")),
227   ARGPARSE_s_n (oAllowMarkTrusted,   "allow-mark-trusted", "@"),
228   ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
229                 /* */                    N_("allow presetting passphrase")),
230   ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
231                                 N_("disallow caller to override the pinentry")),
232   ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
233   ARGPARSE_s_n (oAllowEmacsPinentry,  "allow-emacs-pinentry",
234                 /* */    N_("allow passphrase to be prompted through Emacs")),
235
236   ARGPARSE_s_n (oSSHSupport,   "enable-ssh-support", N_("enable ssh support")),
237   ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
238 #ifdef HAVE_W32_SYSTEM
239                 /* */           N_("enable putty support")
240 #else
241                 /* */           "@"
242 #endif
243                 ),
244
245   /* Dummy options for backward compatibility.  */
246   ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
247   ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
248   ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
249
250   {0} /* End of list */
251 };
252
253
254 /* The list of supported debug flags.  */
255 static struct debug_flags_s debug_flags [] =
256   {
257     { DBG_MPI_VALUE    , "mpi"     },
258     { DBG_CRYPTO_VALUE , "crypto"  },
259     { DBG_MEMORY_VALUE , "memory"  },
260     { DBG_CACHE_VALUE  , "cache"   },
261     { DBG_MEMSTAT_VALUE, "memstat" },
262     { DBG_HASHING_VALUE, "hashing" },
263     { DBG_IPC_VALUE    , "ipc"     },
264     { 77, NULL } /* 77 := Do not exit on "help" or "?".  */
265   };
266
267
268
269 #define DEFAULT_CACHE_TTL     (10*60)  /* 10 minutes */
270 #define DEFAULT_CACHE_TTL_SSH (30*60)  /* 30 minutes */
271 #define MAX_CACHE_TTL         (120*60) /* 2 hours */
272 #define MAX_CACHE_TTL_SSH     (120*60) /* 2 hours */
273 #define MIN_PASSPHRASE_LEN    (8)
274 #define MIN_PASSPHRASE_NONALPHA (1)
275 #define MAX_PASSPHRASE_DAYS   (0)
276
277 /* The timer tick used for housekeeping stuff.  For Windows we use a
278    longer period as the SetWaitableTimer seems to signal earlier than
279    the 2 seconds.  CHECK_OWN_SOCKET_INTERVAL defines how often we
280    check our own socket in standard socket mode.  If that value is 0
281    we don't check at all.   All values are in seconds. */
282 #if defined(HAVE_W32CE_SYSTEM)
283 # define TIMERTICK_INTERVAL         (60)
284 # define CHECK_OWN_SOCKET_INTERVAL   (0)  /* Never */
285 #elif defined(HAVE_W32_SYSTEM)
286 # define TIMERTICK_INTERVAL          (4)
287 # define CHECK_OWN_SOCKET_INTERVAL  (60)
288 #else
289 # define TIMERTICK_INTERVAL          (2)
290 # define CHECK_OWN_SOCKET_INTERVAL  (60)
291 #endif
292
293
294 /* Flag indicating that the ssh-agent subsystem has been enabled.  */
295 static int ssh_support;
296
297 #ifdef HAVE_W32_SYSTEM
298 /* Flag indicating that support for Putty has been enabled.  */
299 static int putty_support;
300 /* A magic value used with WM_COPYDATA.  */
301 #define PUTTY_IPC_MAGIC 0x804e50ba
302 /* To avoid surprises we limit the size of the mapped IPC file to this
303    value.  Putty currently (0.62) uses 8k, thus 16k should be enough
304    for the foreseeable future.  */
305 #define PUTTY_IPC_MAXLEN 16384
306 #endif /*HAVE_W32_SYSTEM*/
307
308 /* The list of open file descriptors at startup.  Note that this list
309  * has been allocated using the standard malloc.  */
310 #ifndef HAVE_W32_SYSTEM
311 static int *startup_fd_list;
312 #endif
313
314 /* The signal mask at startup and a flag telling whether it is valid.  */
315 #ifdef HAVE_SIGPROCMASK
316 static sigset_t startup_signal_mask;
317 static int startup_signal_mask_valid;
318 #endif
319
320 /* Flag to indicate that a shutdown was requested.  */
321 static int shutdown_pending;
322
323 /* Counter for the currently running own socket checks.  */
324 static int check_own_socket_running;
325
326 /* Flags to indicate that check_own_socket shall not be called.  */
327 static int disable_check_own_socket;
328
329 /* Flag indicating that we are in supervised mode.  */
330 static int is_supervised;
331
332 /* Flag to inhibit socket removal in cleanup.  */
333 static int inhibit_socket_removal;
334
335 /* It is possible that we are currently running under setuid permissions */
336 static int maybe_setuid = 1;
337
338 /* Name of the communication socket used for native gpg-agent
339    requests. The second variable is either NULL or a malloced string
340    with the real socket name in case it has been redirected.  */
341 static char *socket_name;
342 static char *redir_socket_name;
343
344 /* Name of the optional extra socket used for native gpg-agent requests.  */
345 static char *socket_name_extra;
346 static char *redir_socket_name_extra;
347
348 /* Name of the optional browser socket used for native gpg-agent requests.  */
349 static char *socket_name_browser;
350 static char *redir_socket_name_browser;
351
352 /* Name of the communication socket used for ssh-agent protocol.  */
353 static char *socket_name_ssh;
354 static char *redir_socket_name_ssh;
355
356 /* We need to keep track of the server's nonces (these are dummies for
357    POSIX systems). */
358 static assuan_sock_nonce_t socket_nonce;
359 static assuan_sock_nonce_t socket_nonce_extra;
360 static assuan_sock_nonce_t socket_nonce_browser;
361 static assuan_sock_nonce_t socket_nonce_ssh;
362
363
364 /* Default values for options passed to the pinentry. */
365 static char *default_display;
366 static char *default_ttyname;
367 static char *default_ttytype;
368 static char *default_lc_ctype;
369 static char *default_lc_messages;
370 static char *default_xauthority;
371
372 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
373 static char *config_filename;
374
375 /* Helper to implement --debug-level */
376 static const char *debug_level;
377
378 /* Keep track of the current log file so that we can avoid updating
379    the log file after a SIGHUP if it didn't changed. Malloced. */
380 static char *current_logfile;
381
382 /* The handle_tick() function may test whether a parent is still
383    running.  We record the PID of the parent here or -1 if it should be
384    watched. */
385 static pid_t parent_pid = (pid_t)(-1);
386
387 /* Record the pid of the main thread, for easier signalling */
388 static pid_t main_thread_pid = (pid_t)(-1);
389
390 /* Number of active connections.  */
391 static int active_connections;
392
393 /* This object is used to dispatch progress messages from Libgcrypt to
394  * the right thread.  Given that we will have at max only a few dozen
395  * connections at a time, using a linked list is the easiest way to
396  * handle this. */
397 struct progress_dispatch_s
398 {
399   struct progress_dispatch_s *next;
400   /* The control object of the connection.  If this is NULL no
401    * connection is associated with this item and it is free for reuse
402    * by new connections.  */
403   ctrl_t ctrl;
404
405   /* The thread id of (npth_self) of the connection.  */
406   npth_t tid;
407
408   /* The callback set by the connection.  This is similar to the
409    * Libgcrypt callback but with the control object passed as the
410    * first argument.  */
411   void (*cb)(ctrl_t ctrl,
412              const char *what, int printchar,
413              int current, int total);
414 };
415 struct progress_dispatch_s *progress_dispatch_list;
416
417
418
419 \f
420 /*
421    Local prototypes.
422  */
423
424 static char *create_socket_name (char *standard_name, int with_homedir);
425 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
426                                         char **r_redir_name,
427                                         assuan_sock_nonce_t *nonce);
428 static void create_directories (void);
429
430 static void agent_libgcrypt_progress_cb (void *data, const char *what,
431                                          int printchar,
432                                          int current, int total);
433 static void agent_init_default_ctrl (ctrl_t ctrl);
434 static void agent_deinit_default_ctrl (ctrl_t ctrl);
435
436 static void handle_connections (gnupg_fd_t listen_fd,
437                                 gnupg_fd_t listen_fd_extra,
438                                 gnupg_fd_t listen_fd_browser,
439                                 gnupg_fd_t listen_fd_ssh);
440 static void check_own_socket (void);
441 static int check_for_running_agent (int silent);
442
443 /* Pth wrapper function definitions. */
444 ASSUAN_SYSTEM_NPTH_IMPL;
445
446 \f
447 /*
448    Functions.
449  */
450
451 /* Allocate a string describing a library version by calling a GETFNC.
452    This function is expected to be called only once.  GETFNC is
453    expected to have a semantic like gcry_check_version ().  */
454 static char *
455 make_libversion (const char *libname, const char *(*getfnc)(const char*))
456 {
457   const char *s;
458   char *result;
459
460   if (maybe_setuid)
461     {
462       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
463       maybe_setuid = 0;
464     }
465   s = getfnc (NULL);
466   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
467   strcpy (stpcpy (stpcpy (result, libname), " "), s);
468   return result;
469 }
470
471 /* Return strings describing this program.  The case values are
472    described in common/argparse.c:strusage.  The values here override
473    the default values given by strusage.  */
474 static const char *
475 my_strusage (int level)
476 {
477   static char *ver_gcry;
478   const char *p;
479
480   switch (level)
481     {
482     case 11: p = "@GPG_AGENT@ (@GNUPG@)";
483       break;
484     case 13: p = VERSION; break;
485     case 17: p = PRINTABLE_OS_NAME; break;
486       /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
487          reporting address.  This is so that we can change the
488          reporting address without breaking the translations.  */
489     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
490
491     case 20:
492       if (!ver_gcry)
493         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
494       p = ver_gcry;
495       break;
496
497     case 1:
498     case 40: p =  _("Usage: @GPG_AGENT@ [options] (-h for help)");
499       break;
500     case 41: p =  _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
501                     "Secret key management for @GNUPG@\n");
502     break;
503
504     default: p = NULL;
505     }
506   return p;
507 }
508
509
510
511 /* Setup the debugging.  With the global variable DEBUG_LEVEL set to NULL
512    only the active debug flags are propagated to the subsystems.  With
513    DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
514    all flags already set. Note that we don't fail here, because it is
515    important to keep gpg-agent running even after re-reading the
516    options due to a SIGHUP. */
517 static void
518 set_debug (void)
519 {
520   int numok = (debug_level && digitp (debug_level));
521   int numlvl = numok? atoi (debug_level) : 0;
522
523   if (!debug_level)
524     ;
525   else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
526     opt.debug = 0;
527   else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
528     opt.debug = DBG_IPC_VALUE;
529   else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
530     opt.debug = DBG_IPC_VALUE;
531   else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
532     opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE);
533   else if (!strcmp (debug_level, "guru") || numok)
534     {
535       opt.debug = ~0;
536       /* Unless the "guru" string has been used we don't want to allow
537          hashing debugging.  The rationale is that people tend to
538          select the highest debug value and would then clutter their
539          disk with debug files which may reveal confidential data.  */
540       if (numok)
541         opt.debug &= ~(DBG_HASHING_VALUE);
542     }
543   else
544     {
545       log_error (_("invalid debug-level '%s' given\n"), debug_level);
546       opt.debug = 0; /* Reset debugging, so that prior debug
547                         statements won't have an undesired effect. */
548     }
549
550   if (opt.debug && !opt.verbose)
551     opt.verbose = 1;
552   if (opt.debug && opt.quiet)
553     opt.quiet = 0;
554
555   if (opt.debug & DBG_MPI_VALUE)
556     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
557   if (opt.debug & DBG_CRYPTO_VALUE )
558     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
559   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
560
561   if (opt.debug)
562     parse_debug_flag (NULL, &opt.debug, debug_flags);
563 }
564
565
566 /* Helper for cleanup to remove one socket with NAME.  REDIR_NAME is
567    the corresponding real name if the socket has been redirected.  */
568 static void
569 remove_socket (char *name, char *redir_name)
570 {
571   if (name && *name)
572     {
573       if (redir_name)
574         name = redir_name;
575
576       gnupg_remove (name);
577       *name = 0;
578     }
579 }
580
581
582 /* Discover which inherited file descriptors correspond to which
583  * services/sockets offered by gpg-agent, using the LISTEN_FDS and
584  * LISTEN_FDNAMES convention.  The understood labels are "ssh",
585  * "extra", and "browser".  "std" or other labels will be interpreted
586  * as the standard socket.
587  *
588  * This function is designed to log errors when the expected file
589  * descriptors don't make sense, but to do its best to continue to
590  * work even in the face of minor misconfigurations.
591  *
592  * For more information on the LISTEN_FDS convention, see
593  * sd_listen_fds(3) on certain Linux distributions.
594  */
595 #ifndef HAVE_W32_SYSTEM
596 static void
597 map_supervised_sockets (gnupg_fd_t *r_fd,
598                         gnupg_fd_t *r_fd_extra,
599                         gnupg_fd_t *r_fd_browser,
600                         gnupg_fd_t *r_fd_ssh)
601 {
602   struct {
603     const char *label;
604     int **fdaddr;
605     char **nameaddr;
606   } tbl[] = {
607     { "ssh",     &r_fd_ssh,     &socket_name_ssh },
608     { "browser", &r_fd_browser, &socket_name_browser },
609     { "extra",   &r_fd_extra,   &socket_name_extra },
610     { "std",     &r_fd,         &socket_name }  /* (Must be the last item.)  */
611   };
612   const char *envvar;
613   char **fdnames;
614   int nfdnames;
615   int fd_count;
616
617   *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
618
619   /* Print a warning if LISTEN_PID does not match outr pid.  */
620   envvar = getenv ("LISTEN_PID");
621   if (!envvar)
622     log_error ("no LISTEN_PID environment variable found in "
623                "--supervised mode (ignoring)\n");
624   else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
625     log_error ("environment variable LISTEN_PID (%lu) does not match"
626                " our pid (%lu) in --supervised mode (ignoring)\n",
627                (unsigned long)strtoul (envvar, NULL, 10),
628                (unsigned long)getpid ());
629
630   /* Parse LISTEN_FDNAMES into the array FDNAMES.  */
631   envvar = getenv ("LISTEN_FDNAMES");
632   if (envvar)
633     {
634       fdnames = strtokenize (envvar, ":");
635       if (!fdnames)
636         {
637           log_error ("strtokenize failed: %s\n",
638                      gpg_strerror (gpg_error_from_syserror ()));
639           agent_exit (1);
640         }
641       for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
642         ;
643     }
644   else
645     {
646       fdnames = NULL;
647       nfdnames = 0;
648     }
649
650   /* Parse LISTEN_FDS into fd_count or provide a replacement.  */
651   envvar = getenv ("LISTEN_FDS");
652   if (envvar)
653     fd_count = atoi (envvar);
654   else if (fdnames)
655     {
656       log_error ("no LISTEN_FDS environment variable found in --supervised"
657                  " mode (relying on LISTEN_FDNAMES instead)\n");
658       fd_count = nfdnames;
659     }
660   else
661     {
662       log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
663                 "found in --supervised mode"
664                 " (assuming 1 active descriptor)\n");
665       fd_count = 1;
666     }
667
668   if (fd_count < 1)
669     {
670       log_error ("--supervised mode expects at least one file descriptor"
671                  " (was told %d, carrying on as though it were 1)\n",
672                  fd_count);
673       fd_count = 1;
674     }
675
676   /* Assign the descriptors to the return values.  */
677   if (!fdnames)
678     {
679       struct stat statbuf;
680
681       if (fd_count != 1)
682         log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
683                    " in --supervised mode."
684                    " (ignoring all sockets but the first one)\n",
685                    fd_count);
686       if (fstat (3, &statbuf) == -1 && errno ==EBADF)
687         log_fatal ("file descriptor 3 must be valid in --supervised mode"
688                    " if LISTEN_FDNAMES is not set\n");
689       *r_fd = 3;
690       socket_name = gnupg_get_socket_name (3);
691     }
692   else if (fd_count != nfdnames)
693     {
694       log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
695                  "LISTEN_FDS (%d) in --supervised mode\n",
696                  nfdnames, fd_count);
697     }
698   else
699     {
700       int i, j, fd;
701       char *name;
702
703       for (i = 0; i < nfdnames; i++)
704         {
705           for (j = 0; j < DIM (tbl); j++)
706             {
707               if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
708                 {
709                   fd = 3 + i;
710                   if (**tbl[j].fdaddr == -1)
711                     {
712                       name = gnupg_get_socket_name (fd);
713                       if (name)
714                         {
715                           **tbl[j].fdaddr = fd;
716                           *tbl[j].nameaddr = name;
717                           log_info ("using fd %d for %s socket (%s)\n",
718                                     fd, tbl[j].label, name);
719                         }
720                       else
721                         {
722                           log_error ("cannot listen on fd %d for %s socket\n",
723                                      fd, tbl[j].label);
724                           close (fd);
725                         }
726                     }
727                   else
728                     {
729                       log_error ("cannot listen on more than one %s socket\n",
730                                  tbl[j].label);
731                       close (fd);
732                     }
733                   break;
734                 }
735             }
736         }
737     }
738
739   xfree (fdnames);
740 }
741 #endif /*!HAVE_W32_SYSTEM*/
742
743
744 /* Cleanup code for this program.  This is either called has an atexit
745    handler or directly.  */
746 static void
747 cleanup (void)
748 {
749   static int done;
750
751   if (done)
752     return;
753   done = 1;
754   deinitialize_module_cache ();
755   if (!is_supervised && !inhibit_socket_removal)
756     {
757       remove_socket (socket_name, redir_socket_name);
758       if (opt.extra_socket > 1)
759         remove_socket (socket_name_extra, redir_socket_name_extra);
760       if (opt.browser_socket > 1)
761         remove_socket (socket_name_browser, redir_socket_name_browser);
762       remove_socket (socket_name_ssh, redir_socket_name_ssh);
763     }
764 }
765
766
767
768 /* Handle options which are allowed to be reset after program start.
769    Return true when the current option in PARGS could be handled and
770    false if not.  As a special feature, passing a value of NULL for
771    PARGS, resets the options to the default.  REREAD should be set
772    true if it is not the initial option parsing. */
773 static int
774 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
775 {
776   if (!pargs)
777     { /* reset mode */
778       opt.quiet = 0;
779       opt.verbose = 0;
780       opt.debug = 0;
781       opt.no_grab = 0;
782       opt.debug_pinentry = 0;
783       opt.pinentry_program = NULL;
784       opt.pinentry_touch_file = NULL;
785       xfree (opt.pinentry_invisible_char);
786       opt.pinentry_invisible_char = NULL;
787       opt.pinentry_timeout = 0;
788       opt.scdaemon_program = NULL;
789       opt.def_cache_ttl = DEFAULT_CACHE_TTL;
790       opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
791       opt.max_cache_ttl = MAX_CACHE_TTL;
792       opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
793       opt.enforce_passphrase_constraints = 0;
794       opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
795       opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
796       opt.check_passphrase_pattern = NULL;
797       opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
798       opt.enable_passphrase_history = 0;
799       opt.ignore_cache_for_signing = 0;
800       opt.allow_mark_trusted = 1;
801       opt.allow_external_cache = 1;
802       opt.allow_loopback_pinentry = 1;
803       opt.allow_emacs_pinentry = 0;
804       opt.disable_scdaemon = 0;
805       disable_check_own_socket = 0;
806       return 1;
807     }
808
809   switch (pargs->r_opt)
810     {
811     case oQuiet: opt.quiet = 1; break;
812     case oVerbose: opt.verbose++; break;
813
814     case oDebug:
815       parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
816       break;
817     case oDebugAll: opt.debug = ~0; break;
818     case oDebugLevel: debug_level = pargs->r.ret_str; break;
819     case oDebugPinentry: opt.debug_pinentry = 1; break;
820
821     case oLogFile:
822       if (!reread)
823         return 0; /* not handeld */
824       if (!current_logfile || !pargs->r.ret_str
825           || strcmp (current_logfile, pargs->r.ret_str))
826         {
827           log_set_file (pargs->r.ret_str);
828           xfree (current_logfile);
829           current_logfile = xtrystrdup (pargs->r.ret_str);
830         }
831       break;
832
833     case oNoGrab: opt.no_grab = 1; break;
834
835     case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
836     case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
837     case oPinentryInvisibleChar:
838       xfree (opt.pinentry_invisible_char);
839       opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
840       break;
841     case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
842     case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
843     case oDisableScdaemon: opt.disable_scdaemon = 1; break;
844     case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
845
846     case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
847     case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
848     case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
849     case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
850
851     case oEnforcePassphraseConstraints:
852       opt.enforce_passphrase_constraints=1;
853       break;
854     case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
855     case oMinPassphraseNonalpha:
856       opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
857       break;
858     case oCheckPassphrasePattern:
859       opt.check_passphrase_pattern = pargs->r.ret_str;
860       break;
861     case oMaxPassphraseDays:
862       opt.max_passphrase_days = pargs->r.ret_ulong;
863       break;
864     case oEnablePassphraseHistory:
865       opt.enable_passphrase_history = 1;
866       break;
867
868     case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
869
870     case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
871     case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
872
873     case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
874
875     case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
876     case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
877
878     case oNoAllowExternalCache: opt.allow_external_cache = 0;
879       break;
880
881     case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
882       break;
883
884     default:
885       return 0; /* not handled */
886     }
887
888   return 1; /* handled */
889 }
890
891
892 /* Fixup some options after all have been processed.  */
893 static void
894 finalize_rereadable_options (void)
895 {
896 }
897
898
899 static void
900 thread_init_once (void)
901 {
902   static int npth_initialized = 0;
903
904   if (!npth_initialized)
905     {
906       npth_initialized++;
907       npth_init ();
908     }
909   gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
910   /* Now that we have set the syscall clamp we need to tell Libgcrypt
911    * that it should get them from libgpg-error.  Note that Libgcrypt
912    * has already been initialized but at that point nPth was not
913    * initialized and thus Libgcrypt could not set its system call
914    * clamp.  */
915 #if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */
916   gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
917 #endif
918 }
919
920
921 static void
922 initialize_modules (void)
923 {
924   thread_init_once ();
925   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
926   initialize_module_cache ();
927   initialize_module_call_pinentry ();
928   initialize_module_call_scd ();
929   initialize_module_trustlist ();
930 }
931
932
933 /* The main entry point.  */
934 int
935 main (int argc, char **argv )
936 {
937   ARGPARSE_ARGS pargs;
938   int orig_argc;
939   char **orig_argv;
940   FILE *configfp = NULL;
941   char *configname = NULL;
942   const char *shell;
943   unsigned configlineno;
944   int parse_debug = 0;
945   int default_config =1;
946   int pipe_server = 0;
947   int is_daemon = 0;
948   int nodetach = 0;
949   int csh_style = 0;
950   char *logfile = NULL;
951   int debug_wait = 0;
952   int gpgconf_list = 0;
953   gpg_error_t err;
954   struct assuan_malloc_hooks malloc_hooks;
955
956   early_system_init ();
957
958 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
959   /* Disable ptrace on Linux without sgid bit */
960   prctl(PR_SET_DUMPABLE, 0);
961 #endif
962
963   /* Before we do anything else we save the list of currently open
964      file descriptors and the signal mask.  This info is required to
965      do the exec call properly.  We don't need it on Windows.  */
966 #ifndef HAVE_W32_SYSTEM
967   startup_fd_list = get_all_open_fds ();
968 #endif /*!HAVE_W32_SYSTEM*/
969 #ifdef HAVE_SIGPROCMASK
970   if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
971     startup_signal_mask_valid = 1;
972 #endif /*HAVE_SIGPROCMASK*/
973
974   /* Set program name etc.  */
975   set_strusage (my_strusage);
976   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
977   /* Please note that we may running SUID(ROOT), so be very CAREFUL
978      when adding any stuff between here and the call to INIT_SECMEM()
979      somewhere after the option parsing */
980   log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
981
982   /* Make sure that our subsystems are ready.  */
983   i18n_init ();
984   init_common_subsystems (&argc, &argv);
985
986   malloc_hooks.malloc = gcry_malloc;
987   malloc_hooks.realloc = gcry_realloc;
988   malloc_hooks.free = gcry_free;
989   assuan_set_malloc_hooks (&malloc_hooks);
990   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
991   assuan_sock_init ();
992   setup_libassuan_logging (&opt.debug, NULL);
993
994   setup_libgcrypt_logging ();
995   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
996   gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
997
998   disable_core_dumps ();
999
1000   /* Set default options.  */
1001   parse_rereadable_options (NULL, 0); /* Reset them to default values. */
1002
1003   shell = getenv ("SHELL");
1004   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1005     csh_style = 1;
1006
1007   /* Record some of the original environment strings. */
1008   {
1009     const char *s;
1010     int idx;
1011     static const char *names[] =
1012       { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
1013
1014     err = 0;
1015     opt.startup_env = session_env_new ();
1016     if (!opt.startup_env)
1017       err = gpg_error_from_syserror ();
1018     for (idx=0; !err && names[idx]; idx++)
1019       {
1020         s = getenv (names[idx]);
1021         if (s)
1022           err = session_env_setenv (opt.startup_env, names[idx], s);
1023       }
1024     if (!err)
1025       {
1026         s = gnupg_ttyname (0);
1027         if (s)
1028           err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
1029       }
1030     if (err)
1031       log_fatal ("error recording startup environment: %s\n",
1032                  gpg_strerror (err));
1033
1034     /* Fixme: Better use the locale function here.  */
1035     opt.startup_lc_ctype = getenv ("LC_CTYPE");
1036     if (opt.startup_lc_ctype)
1037       opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
1038     opt.startup_lc_messages = getenv ("LC_MESSAGES");
1039     if (opt.startup_lc_messages)
1040       opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
1041   }
1042
1043   /* Check whether we have a config file on the commandline */
1044   orig_argc = argc;
1045   orig_argv = argv;
1046   pargs.argc = &argc;
1047   pargs.argv = &argv;
1048   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
1049   while (arg_parse( &pargs, opts))
1050     {
1051       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
1052         parse_debug++;
1053       else if (pargs.r_opt == oOptions)
1054         { /* yes there is one, so we do not try the default one, but
1055              read the option file when it is encountered at the
1056              commandline */
1057           default_config = 0;
1058         }
1059         else if (pargs.r_opt == oNoOptions)
1060           default_config = 0; /* --no-options */
1061         else if (pargs.r_opt == oHomedir)
1062           gnupg_set_homedir (pargs.r.ret_str);
1063         else if (pargs.r_opt == oDebugQuickRandom)
1064           {
1065             gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
1066           }
1067
1068     }
1069
1070   /* Initialize the secure memory. */
1071   gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0);
1072   maybe_setuid = 0;
1073
1074   /*
1075      Now we are now working under our real uid
1076   */
1077
1078   if (default_config)
1079     configname = make_filename (gnupg_homedir (),
1080                                 GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1081
1082   argc = orig_argc;
1083   argv = orig_argv;
1084   pargs.argc = &argc;
1085   pargs.argv = &argv;
1086   pargs.flags=  1;  /* do not remove the args */
1087  next_pass:
1088   if (configname)
1089     {
1090       configlineno = 0;
1091       configfp = fopen (configname, "r");
1092       if (!configfp)
1093         {
1094           if (default_config)
1095             {
1096               if( parse_debug )
1097                 log_info (_("Note: no default option file '%s'\n"),
1098                           configname );
1099               /* Save the default conf file name so that
1100                  reread_configuration is able to test whether the
1101                  config file has been created in the meantime.  */
1102               xfree (config_filename);
1103               config_filename = configname;
1104               configname = NULL;
1105             }
1106           else
1107             {
1108               log_error (_("option file '%s': %s\n"),
1109                          configname, strerror(errno) );
1110               exit(2);
1111             }
1112           xfree (configname);
1113           configname = NULL;
1114         }
1115       if (parse_debug && configname )
1116         log_info (_("reading options from '%s'\n"), configname );
1117       default_config = 0;
1118     }
1119
1120   while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
1121     {
1122       if (parse_rereadable_options (&pargs, 0))
1123         continue; /* Already handled */
1124       switch (pargs.r_opt)
1125         {
1126         case aGPGConfList: gpgconf_list = 1; break;
1127         case aGPGConfTest: gpgconf_list = 2; break;
1128         case aUseStandardSocketP: gpgconf_list = 3; break;
1129         case oBatch: opt.batch=1; break;
1130
1131         case oDebugWait: debug_wait = pargs.r.ret_int; break;
1132
1133         case oOptions:
1134           /* config files may not be nested (silently ignore them) */
1135           if (!configfp)
1136             {
1137                 xfree(configname);
1138                 configname = xstrdup(pargs.r.ret_str);
1139                 goto next_pass;
1140             }
1141           break;
1142         case oNoGreeting: /* Dummy option.  */ break;
1143         case oNoVerbose: opt.verbose = 0; break;
1144         case oNoOptions: break; /* no-options */
1145         case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1146         case oNoDetach: nodetach = 1; break;
1147         case oLogFile: logfile = pargs.r.ret_str; break;
1148         case oCsh: csh_style = 1; break;
1149         case oSh: csh_style = 0; break;
1150         case oServer: pipe_server = 1; break;
1151         case oDaemon: is_daemon = 1; break;
1152         case oSupervised: is_supervised = 1; break;
1153
1154         case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
1155         case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
1156         case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
1157         case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
1158         case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
1159           break;
1160         case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
1161           break;
1162
1163         case oUseStandardSocket:
1164         case oNoUseStandardSocket:
1165           obsolete_option (configname, configlineno, "use-standard-socket");
1166           break;
1167
1168         case oFakedSystemTime:
1169           {
1170             time_t faked_time = isotime2epoch (pargs.r.ret_str);
1171             if (faked_time == (time_t)(-1))
1172               faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1173             gnupg_set_time (faked_time, 0);
1174           }
1175           break;
1176
1177         case oKeepTTY: opt.keep_tty = 1; break;
1178         case oKeepDISPLAY: opt.keep_display = 1; break;
1179
1180         case oSSHSupport:
1181           ssh_support = 1;
1182           break;
1183         case oPuttySupport:
1184 #        ifdef HAVE_W32_SYSTEM
1185           putty_support = 1;
1186 #        endif
1187           break;
1188
1189         case oExtraSocket:
1190           opt.extra_socket = 1;  /* (1 = points into argv)  */
1191           socket_name_extra = pargs.r.ret_str;
1192           break;
1193
1194         case oBrowserSocket:
1195           opt.browser_socket = 1;  /* (1 = points into argv)  */
1196           socket_name_browser = pargs.r.ret_str;
1197           break;
1198
1199         case oDebugQuickRandom:
1200           /* Only used by the first stage command line parser.  */
1201           break;
1202
1203         case oWriteEnvFile:
1204           obsolete_option (configname, configlineno, "write-env-file");
1205           break;
1206
1207         default : pargs.err = configfp? 1:2; break;
1208         }
1209     }
1210   if (configfp)
1211     {
1212       fclose( configfp );
1213       configfp = NULL;
1214       /* Keep a copy of the name so that it can be read on SIGHUP. */
1215       if (config_filename != configname)
1216         {
1217           xfree (config_filename);
1218           config_filename = configname;
1219         }
1220       configname = NULL;
1221       goto next_pass;
1222     }
1223
1224   xfree (configname);
1225   configname = NULL;
1226   if (log_get_errorcount(0))
1227     exit(2);
1228
1229   finalize_rereadable_options ();
1230
1231   /* Print a warning if an argument looks like an option.  */
1232   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1233     {
1234       int i;
1235
1236       for (i=0; i < argc; i++)
1237         if (argv[i][0] == '-' && argv[i][1] == '-')
1238           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1239     }
1240
1241 #ifdef ENABLE_NLS
1242   /* gpg-agent usually does not output any messages because it runs in
1243      the background.  For log files it is acceptable to have messages
1244      always encoded in utf-8.  We switch here to utf-8, so that
1245      commands like --help still give native messages.  It is far
1246      easier to switch only once instead of for every message and it
1247      actually helps when more then one thread is active (avoids an
1248      extra copy step). */
1249     bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1250 #endif
1251
1252   if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
1253     {
1254      /* We have been called without any command and thus we merely
1255         check whether an agent is already running.  We do this right
1256         here so that we don't clobber a logfile with this check but
1257         print the status directly to stderr. */
1258       opt.debug = 0;
1259       set_debug ();
1260       check_for_running_agent (0);
1261       agent_exit (0);
1262     }
1263
1264   if (is_supervised)
1265     ;
1266   else if (!opt.extra_socket)
1267     opt.extra_socket = 1;
1268   else if (socket_name_extra
1269            && (!strcmp (socket_name_extra, "none")
1270                || !strcmp (socket_name_extra, "/dev/null")))
1271     {
1272       /* User requested not to create this socket.  */
1273       opt.extra_socket = 0;
1274       socket_name_extra = NULL;
1275     }
1276
1277   if (is_supervised)
1278     ;
1279   else if (!opt.browser_socket)
1280     opt.browser_socket = 1;
1281   else if (socket_name_browser
1282            && (!strcmp (socket_name_browser, "none")
1283                || !strcmp (socket_name_browser, "/dev/null")))
1284     {
1285       /* User requested not to create this socket.  */
1286       opt.browser_socket = 0;
1287       socket_name_browser = NULL;
1288     }
1289
1290   set_debug ();
1291
1292   if (atexit (cleanup))
1293     {
1294       log_error ("atexit failed\n");
1295       cleanup ();
1296       exit (1);
1297     }
1298
1299   /* Try to create missing directories. */
1300   create_directories ();
1301
1302   if (debug_wait && pipe_server)
1303     {
1304       thread_init_once ();
1305       log_debug ("waiting for debugger - my pid is %u .....\n",
1306                  (unsigned int)getpid());
1307       gnupg_sleep (debug_wait);
1308       log_debug ("... okay\n");
1309     }
1310
1311   if (gpgconf_list == 3)
1312     {
1313       /* We now use the standard socket always - return true for
1314          backward compatibility.  */
1315       agent_exit (0);
1316     }
1317   else if (gpgconf_list == 2)
1318     agent_exit (0);
1319   else if (gpgconf_list)
1320     {
1321       char *filename;
1322       char *filename_esc;
1323
1324       /* List options and default values in the GPG Conf format.  */
1325       filename = make_filename (gnupg_homedir (),
1326                                 GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1327       filename_esc = percent_escape (filename, NULL);
1328
1329       es_printf ("%s-%s.conf:%lu:\"%s\n",
1330                  GPGCONF_NAME, GPG_AGENT_NAME,
1331                  GC_OPT_FLAG_DEFAULT, filename_esc);
1332       xfree (filename);
1333       xfree (filename_esc);
1334
1335       es_printf ("verbose:%lu:\n"
1336               "quiet:%lu:\n"
1337               "debug-level:%lu:\"none:\n"
1338               "log-file:%lu:\n",
1339               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1340               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1341               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1342               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1343       es_printf ("default-cache-ttl:%lu:%d:\n",
1344               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1345       es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1346               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1347       es_printf ("max-cache-ttl:%lu:%d:\n",
1348               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1349       es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1350               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1351       es_printf ("enforce-passphrase-constraints:%lu:\n",
1352               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1353       es_printf ("min-passphrase-len:%lu:%d:\n",
1354               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1355       es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1356               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1357               MIN_PASSPHRASE_NONALPHA);
1358       es_printf ("check-passphrase-pattern:%lu:\n",
1359               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1360       es_printf ("max-passphrase-days:%lu:%d:\n",
1361               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1362               MAX_PASSPHRASE_DAYS);
1363       es_printf ("enable-passphrase-history:%lu:\n",
1364               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1365       es_printf ("no-grab:%lu:\n",
1366               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1367       es_printf ("ignore-cache-for-signing:%lu:\n",
1368               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1369       es_printf ("no-allow-external-cache:%lu:\n",
1370               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1371       es_printf ("no-allow-mark-trusted:%lu:\n",
1372               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1373       es_printf ("disable-scdaemon:%lu:\n",
1374               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1375       es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1376 #ifdef HAVE_W32_SYSTEM
1377       es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1378 #endif
1379       es_printf ("no-allow-loopback-pinentry:%lu:\n",
1380               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1381       es_printf ("allow-emacs-pinentry:%lu:\n",
1382                  GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1383       es_printf ("pinentry-timeout:%lu:0:\n",
1384                  GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1385
1386       agent_exit (0);
1387     }
1388
1389   /* Now start with logging to a file if this is desired. */
1390   if (logfile)
1391     {
1392       log_set_file (logfile);
1393       log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1394                              | GPGRT_LOG_WITH_TIME
1395                              | GPGRT_LOG_WITH_PID));
1396       current_logfile = xstrdup (logfile);
1397     }
1398
1399   /* Make sure that we have a default ttyname. */
1400   if (!default_ttyname && gnupg_ttyname (1))
1401     default_ttyname = xstrdup (gnupg_ttyname (1));
1402   if (!default_ttytype && getenv ("TERM"))
1403     default_ttytype = xstrdup (getenv ("TERM"));
1404
1405
1406   if (pipe_server)
1407     {
1408       /* This is the simple pipe based server */
1409       ctrl_t ctrl;
1410
1411       initialize_modules ();
1412
1413       ctrl = xtrycalloc (1, sizeof *ctrl);
1414       if (!ctrl)
1415         {
1416           log_error ("error allocating connection control data: %s\n",
1417                      strerror (errno) );
1418           agent_exit (1);
1419         }
1420       ctrl->session_env = session_env_new ();
1421       if (!ctrl->session_env)
1422         {
1423           log_error ("error allocating session environment block: %s\n",
1424                      strerror (errno) );
1425           xfree (ctrl);
1426           agent_exit (1);
1427         }
1428       agent_init_default_ctrl (ctrl);
1429       start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1430       agent_deinit_default_ctrl (ctrl);
1431       xfree (ctrl);
1432     }
1433   else if (is_supervised)
1434     {
1435 #ifndef HAVE_W32_SYSTEM
1436       gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
1437
1438       initialize_modules ();
1439
1440       /* when supervised and sending logs to stderr, the process
1441          supervisor should handle log entry metadata (pid, name,
1442          timestamp) */
1443       if (!logfile)
1444         log_set_prefix (NULL, 0);
1445
1446       log_info ("%s %s starting in supervised mode.\n",
1447                 strusage(11), strusage(13) );
1448
1449       /* See below in "regular server mode" on why we remove certain
1450        * envvars.  */
1451       if (!opt.keep_display)
1452         gnupg_unsetenv ("DISPLAY");
1453       gnupg_unsetenv ("INSIDE_EMACS");
1454
1455       /* Virtually create the sockets.  Note that we use -1 here
1456        * because the whole thing works only on Unix. */
1457       map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
1458       if (fd == -1)
1459         log_fatal ("no standard socket provided\n");
1460
1461 #ifdef HAVE_SIGPROCMASK
1462       if (startup_signal_mask_valid)
1463         {
1464           if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1465             log_error ("error restoring signal mask: %s\n",
1466                        strerror (errno));
1467         }
1468       else
1469         log_info ("no saved signal mask\n");
1470 #endif /*HAVE_SIGPROCMASK*/
1471
1472       log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
1473                 fd, fd_extra, fd_browser, fd_ssh);
1474       handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1475 #endif /*!HAVE_W32_SYSTEM*/
1476     }
1477   else if (!is_daemon)
1478     ; /* NOTREACHED */
1479   else
1480     { /* Regular server mode */
1481       gnupg_fd_t fd;
1482       gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1483       gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1484       gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1485 #ifndef HAVE_W32_SYSTEM
1486       pid_t pid;
1487 #endif
1488
1489       /* Remove the DISPLAY variable so that a pinentry does not
1490          default to a specific display.  There is still a default
1491          display when gpg-agent was started using --display or a
1492          client requested this using an OPTION command.  Note, that we
1493          don't do this when running in reverse daemon mode (i.e. when
1494          exec the program given as arguments). */
1495 #ifndef HAVE_W32_SYSTEM
1496       if (!opt.keep_display && !argc)
1497         gnupg_unsetenv ("DISPLAY");
1498 #endif
1499
1500       /* Remove the INSIDE_EMACS variable so that a pinentry does not
1501          always try to interact with Emacs.  The variable is set when
1502          a client requested this using an OPTION command.  */
1503       gnupg_unsetenv ("INSIDE_EMACS");
1504
1505       /* Create the sockets.  */
1506       socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1507       fd = create_server_socket (socket_name, 1, 0,
1508                                  &redir_socket_name, &socket_nonce);
1509
1510       if (opt.extra_socket)
1511         {
1512           if (socket_name_extra)
1513             socket_name_extra = create_socket_name (socket_name_extra, 0);
1514           else
1515             socket_name_extra = create_socket_name
1516               /**/                (GPG_AGENT_EXTRA_SOCK_NAME, 1);
1517           opt.extra_socket = 2; /* Indicate that it has been malloced.  */
1518           fd_extra = create_server_socket (socket_name_extra, 0, 0,
1519                                            &redir_socket_name_extra,
1520                                            &socket_nonce_extra);
1521         }
1522
1523       if (opt.browser_socket)
1524         {
1525           if (socket_name_browser)
1526             socket_name_browser = create_socket_name (socket_name_browser, 0);
1527           else
1528             socket_name_browser= create_socket_name
1529               /**/                 (GPG_AGENT_BROWSER_SOCK_NAME, 1);
1530           opt.browser_socket = 2; /* Indicate that it has been malloced.  */
1531           fd_browser = create_server_socket (socket_name_browser, 0, 0,
1532                                              &redir_socket_name_browser,
1533                                              &socket_nonce_browser);
1534         }
1535
1536       socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1537       fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1538                                      &redir_socket_name_ssh,
1539                                      &socket_nonce_ssh);
1540
1541       /* If we are going to exec a program in the parent, we record
1542          the PID, so that the child may check whether the program is
1543          still alive. */
1544       if (argc)
1545         parent_pid = getpid ();
1546
1547       fflush (NULL);
1548
1549 #ifdef HAVE_W32_SYSTEM
1550
1551       (void)csh_style;
1552       (void)nodetach;
1553       initialize_modules ();
1554
1555 #else /*!HAVE_W32_SYSTEM*/
1556
1557       pid = fork ();
1558       if (pid == (pid_t)-1)
1559         {
1560           log_fatal ("fork failed: %s\n", strerror (errno) );
1561           exit (1);
1562         }
1563       else if (pid)
1564         { /* We are the parent */
1565           char *infostr_ssh_sock, *infostr_ssh_valid;
1566
1567           /* Close the socket FD. */
1568           close (fd);
1569
1570           /* The signal mask might not be correct right now and thus
1571              we restore it.  That is not strictly necessary but some
1572              programs falsely assume a cleared signal mask.  */
1573
1574 #ifdef HAVE_SIGPROCMASK
1575           if (startup_signal_mask_valid)
1576             {
1577               if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1578                 log_error ("error restoring signal mask: %s\n",
1579                            strerror (errno));
1580             }
1581           else
1582             log_info ("no saved signal mask\n");
1583 #endif /*HAVE_SIGPROCMASK*/
1584
1585           /* Create the SSH info string if enabled. */
1586           if (ssh_support)
1587             {
1588               if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1589                             socket_name_ssh) < 0)
1590                 {
1591                   log_error ("out of core\n");
1592                   kill (pid, SIGTERM);
1593                   exit (1);
1594                 }
1595               if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1596                             (unsigned long)getpid()) < 0)
1597                 {
1598                   log_error ("out of core\n");
1599                   kill (pid, SIGTERM);
1600                   exit (1);
1601                 }
1602             }
1603
1604           *socket_name = 0; /* Don't let cleanup() remove the socket -
1605                                the child should do this from now on */
1606           if (opt.extra_socket)
1607             *socket_name_extra = 0;
1608           if (opt.browser_socket)
1609             *socket_name_browser = 0;
1610           *socket_name_ssh = 0;
1611
1612           if (argc)
1613             { /* Run the program given on the commandline.  */
1614               if (ssh_support && (putenv (infostr_ssh_sock)
1615                                   || putenv (infostr_ssh_valid)))
1616                 {
1617                   log_error ("failed to set environment: %s\n",
1618                              strerror (errno) );
1619                   kill (pid, SIGTERM );
1620                   exit (1);
1621                 }
1622
1623               /* Close all the file descriptors except the standard
1624                  ones and those open at startup.  We explicitly don't
1625                  close 0,1,2 in case something went wrong collecting
1626                  them at startup.  */
1627               close_all_fds (3, startup_fd_list);
1628
1629               /* Run the command.  */
1630               execvp (argv[0], argv);
1631               log_error ("failed to run the command: %s\n", strerror (errno));
1632               kill (pid, SIGTERM);
1633               exit (1);
1634             }
1635           else
1636             {
1637               /* Print the environment string, so that the caller can use
1638                  shell's eval to set it */
1639               if (csh_style)
1640                 {
1641                   if (ssh_support)
1642                     {
1643                       *strchr (infostr_ssh_sock, '=') = ' ';
1644                       es_printf ("setenv %s;\n", infostr_ssh_sock);
1645                     }
1646                 }
1647               else
1648                 {
1649                   if (ssh_support)
1650                     {
1651                       es_printf ("%s; export SSH_AUTH_SOCK;\n",
1652                                  infostr_ssh_sock);
1653                     }
1654                 }
1655               if (ssh_support)
1656                 {
1657                   xfree (infostr_ssh_sock);
1658                   xfree (infostr_ssh_valid);
1659                 }
1660               exit (0);
1661             }
1662           /*NOTREACHED*/
1663         } /* End parent */
1664
1665       /*
1666          This is the child
1667        */
1668
1669       initialize_modules ();
1670
1671       /* Detach from tty and put process into a new session */
1672       if (!nodetach )
1673         {
1674           int i;
1675           unsigned int oldflags;
1676
1677           /* Close stdin, stdout and stderr unless it is the log stream */
1678           for (i=0; i <= 2; i++)
1679             {
1680               if (!log_test_fd (i) && i != fd )
1681                 {
1682                   if ( ! close (i)
1683                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1684                     {
1685                       log_error ("failed to open '%s': %s\n",
1686                                  "/dev/null", strerror (errno));
1687                       cleanup ();
1688                       exit (1);
1689                     }
1690                 }
1691             }
1692           if (setsid() == -1)
1693             {
1694               log_error ("setsid() failed: %s\n", strerror(errno) );
1695               cleanup ();
1696               exit (1);
1697             }
1698
1699           log_get_prefix (&oldflags);
1700           log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1701           opt.running_detached = 1;
1702         }
1703
1704       if (chdir("/"))
1705         {
1706           log_error ("chdir to / failed: %s\n", strerror (errno));
1707           exit (1);
1708         }
1709
1710       {
1711         struct sigaction sa;
1712
1713         sa.sa_handler = SIG_IGN;
1714         sigemptyset (&sa.sa_mask);
1715         sa.sa_flags = 0;
1716         sigaction (SIGPIPE, &sa, NULL);
1717       }
1718 #endif /*!HAVE_W32_SYSTEM*/
1719
1720       log_info ("%s %s started\n", strusage(11), strusage(13) );
1721       handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1722       assuan_sock_close (fd);
1723     }
1724
1725   return 0;
1726 }
1727
1728
1729 /* Exit entry point.  This function should be called instead of a
1730    plain exit.  */
1731 void
1732 agent_exit (int rc)
1733 {
1734   /*FIXME: update_random_seed_file();*/
1735
1736   /* We run our cleanup handler because that may close cipher contexts
1737      stored in secure memory and thus this needs to be done before we
1738      explicitly terminate secure memory.  */
1739   cleanup ();
1740
1741 #if 1
1742   /* at this time a bit annoying */
1743   if (opt.debug & DBG_MEMSTAT_VALUE)
1744     {
1745       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1746       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1747     }
1748   if (opt.debug)
1749     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1750 #endif
1751   gcry_control (GCRYCTL_TERM_SECMEM );
1752   rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1753   exit (rc);
1754 }
1755
1756
1757 /* This is our callback function for gcrypt progress messages.  It is
1758    set once at startup and dispatches progress messages to the
1759    corresponding threads of the agent.  */
1760 static void
1761 agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1762                              int current, int total)
1763 {
1764   struct progress_dispatch_s *dispatch;
1765   npth_t mytid = npth_self ();
1766
1767   (void)data;
1768
1769   for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1770     if (dispatch->ctrl && dispatch->tid == mytid)
1771       break;
1772   if (dispatch && dispatch->cb)
1773     dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1774
1775   /* Libgcrypt < 1.8 does not know about nPth and thus when it reads
1776    * from /dev/random this will block the process.  To mitigate this
1777    * problem we yield the thread when Libgcrypt tells us that it needs
1778    * more entropy.  This way other threads have chance to run.  */
1779 #if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */
1780   if (what && !strcmp (what, "need_entropy"))
1781     {
1782 #if GPGRT_VERSION_NUMBER < 0x011900 /* 1.25 */
1783       /* In older gpg-error versions gpgrt_yield is buggy for use with
1784        * nPth and thus we need to resort to a sleep call.  */
1785       npth_usleep (1000); /* 1ms */
1786 #else
1787       gpgrt_yield ();
1788 #endif
1789     }
1790 #endif
1791 }
1792
1793
1794 /* If a progress dispatcher callback has been associated with the
1795  * current connection unregister it.  */
1796 static void
1797 unregister_progress_cb (void)
1798 {
1799   struct progress_dispatch_s *dispatch;
1800   npth_t mytid = npth_self ();
1801
1802   for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1803     if (dispatch->ctrl && dispatch->tid == mytid)
1804       break;
1805   if (dispatch)
1806     {
1807       dispatch->ctrl = NULL;
1808       dispatch->cb = NULL;
1809     }
1810 }
1811
1812
1813 /* Setup a progress callback CB for the current connection.  Using a
1814  * CB of NULL disables the callback.  */
1815 void
1816 agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1817                                   int printchar, int current, int total),
1818                        ctrl_t ctrl)
1819 {
1820   struct progress_dispatch_s *dispatch, *firstfree;
1821   npth_t mytid = npth_self ();
1822
1823   firstfree = NULL;
1824   for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1825     {
1826       if (dispatch->ctrl && dispatch->tid == mytid)
1827         break;
1828       if (!dispatch->ctrl && !firstfree)
1829         firstfree = dispatch;
1830     }
1831   if (!dispatch) /* None allocated: Reuse or allocate a new one.  */
1832     {
1833       if (firstfree)
1834         {
1835           dispatch = firstfree;
1836         }
1837       else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1838         {
1839           dispatch->next = progress_dispatch_list;
1840           progress_dispatch_list = dispatch;
1841         }
1842       else
1843         {
1844           log_error ("error allocating new progress dispatcher slot: %s\n",
1845                      gpg_strerror (gpg_error_from_syserror ()));
1846           return;
1847         }
1848       dispatch->ctrl = ctrl;
1849       dispatch->tid = mytid;
1850     }
1851
1852   dispatch->cb = cb;
1853 }
1854
1855
1856 /* Each thread has its own local variables conveyed by a control
1857    structure usually identified by an argument named CTRL.  This
1858    function is called immediately after allocating the control
1859    structure.  Its purpose is to setup the default values for that
1860    structure.  Note that some values may have already been set.  */
1861 static void
1862 agent_init_default_ctrl (ctrl_t ctrl)
1863 {
1864   assert (ctrl->session_env);
1865
1866   /* Note we ignore malloc errors because we can't do much about it
1867      and the request will fail anyway shortly after this
1868      initialization. */
1869   session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1870   session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1871   session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1872   session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1873   session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1874
1875   if (ctrl->lc_ctype)
1876     xfree (ctrl->lc_ctype);
1877   ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1878
1879   if (ctrl->lc_messages)
1880     xfree (ctrl->lc_messages);
1881   ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1882                                     /**/ : NULL;
1883   ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1884 }
1885
1886
1887 /* Release all resources allocated by default in the control
1888    structure.  This is the counterpart to agent_init_default_ctrl.  */
1889 static void
1890 agent_deinit_default_ctrl (ctrl_t ctrl)
1891 {
1892   unregister_progress_cb ();
1893   session_env_release (ctrl->session_env);
1894
1895   if (ctrl->lc_ctype)
1896     xfree (ctrl->lc_ctype);
1897   if (ctrl->lc_messages)
1898     xfree (ctrl->lc_messages);
1899 }
1900
1901
1902 /* Because the ssh protocol does not send us information about the
1903    current TTY setting, we use this function to use those from startup
1904    or those explicitly set.  This is also used for the restricted mode
1905    where we ignore requests to change the environment.  */
1906 gpg_error_t
1907 agent_copy_startup_env (ctrl_t ctrl)
1908 {
1909   static const char *names[] =
1910     {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1911   gpg_error_t err = 0;
1912   int idx;
1913   const char *value;
1914
1915   for (idx=0; !err && names[idx]; idx++)
1916       if ((value = session_env_getenv (opt.startup_env, names[idx])))
1917       err = session_env_setenv (ctrl->session_env, names[idx], value);
1918
1919   if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1920     if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1921       err = gpg_error_from_syserror ();
1922
1923   if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1924     if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1925       err = gpg_error_from_syserror ();
1926
1927   if (err)
1928     log_error ("error setting default session environment: %s\n",
1929                gpg_strerror (err));
1930
1931   return err;
1932 }
1933
1934
1935 /* Reread parts of the configuration.  Note, that this function is
1936    obviously not thread-safe and should only be called from the PTH
1937    signal handler.
1938
1939    Fixme: Due to the way the argument parsing works, we create a
1940    memory leak here for all string type arguments.  There is currently
1941    no clean way to tell whether the memory for the argument has been
1942    allocated or points into the process' original arguments.  Unless
1943    we have a mechanism to tell this, we need to live on with this. */
1944 static void
1945 reread_configuration (void)
1946 {
1947   ARGPARSE_ARGS pargs;
1948   FILE *fp;
1949   unsigned int configlineno = 0;
1950   int dummy;
1951
1952   if (!config_filename)
1953     return; /* No config file. */
1954
1955   fp = fopen (config_filename, "r");
1956   if (!fp)
1957     {
1958       log_info (_("option file '%s': %s\n"),
1959                 config_filename, strerror(errno) );
1960       return;
1961     }
1962
1963   parse_rereadable_options (NULL, 1); /* Start from the default values. */
1964
1965   memset (&pargs, 0, sizeof pargs);
1966   dummy = 0;
1967   pargs.argc = &dummy;
1968   pargs.flags = 1;  /* do not remove the args */
1969   while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1970     {
1971       if (pargs.r_opt < -1)
1972         pargs.err = 1; /* Print a warning. */
1973       else /* Try to parse this option - ignore unchangeable ones. */
1974         parse_rereadable_options (&pargs, 1);
1975     }
1976   fclose (fp);
1977   finalize_rereadable_options ();
1978   set_debug ();
1979 }
1980
1981
1982 /* Return the file name of the socket we are using for native
1983    requests.  */
1984 const char *
1985 get_agent_socket_name (void)
1986 {
1987   const char *s = socket_name;
1988
1989   return (s && *s)? s : NULL;
1990 }
1991
1992 /* Return the file name of the socket we are using for SSH
1993    requests.  */
1994 const char *
1995 get_agent_ssh_socket_name (void)
1996 {
1997   const char *s = socket_name_ssh;
1998
1999   return (s && *s)? s : NULL;
2000 }
2001
2002
2003 /* Return the number of active connections. */
2004 int
2005 get_agent_active_connection_count (void)
2006 {
2007   return active_connections;
2008 }
2009
2010
2011 /* Under W32, this function returns the handle of the scdaemon
2012    notification event.  Calling it the first time creates that
2013    event.  */
2014 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
2015 void *
2016 get_agent_scd_notify_event (void)
2017 {
2018   static HANDLE the_event = INVALID_HANDLE_VALUE;
2019
2020   if (the_event == INVALID_HANDLE_VALUE)
2021     {
2022       HANDLE h, h2;
2023       SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
2024
2025       /* We need to use a manual reset event object due to the way our
2026          w32-pth wait function works: If we would use an automatic
2027          reset event we are not able to figure out which handle has
2028          been signaled because at the time we single out the signaled
2029          handles using WFSO the event has already been reset due to
2030          the WFMO.  */
2031       h = CreateEvent (&sa, TRUE, FALSE, NULL);
2032       if (!h)
2033         log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
2034       else if (!DuplicateHandle (GetCurrentProcess(), h,
2035                                  GetCurrentProcess(), &h2,
2036                                  EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
2037         {
2038           log_error ("setting synchronize for scd notify event failed: %s\n",
2039                      w32_strerror (-1) );
2040           CloseHandle (h);
2041         }
2042       else
2043         {
2044           CloseHandle (h);
2045           the_event = h2;
2046         }
2047     }
2048
2049   return the_event;
2050 }
2051 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
2052
2053
2054
2055 /* Create a name for the socket in the home directory as using
2056    STANDARD_NAME.  We also check for valid characters as well as
2057    against a maximum allowed length for a unix domain socket is done.
2058    The function terminates the process in case of an error.  Returns:
2059    Pointer to an allocated string with the absolute name of the socket
2060    used.  */
2061 static char *
2062 create_socket_name (char *standard_name, int with_homedir)
2063 {
2064   char *name;
2065
2066   if (with_homedir)
2067     name = make_filename (gnupg_socketdir (), standard_name, NULL);
2068   else
2069     name = make_filename (standard_name, NULL);
2070   if (strchr (name, PATHSEP_C))
2071     {
2072       log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
2073       agent_exit (2);
2074     }
2075   return name;
2076 }
2077
2078
2079
2080 /* Create a Unix domain socket with NAME.  Returns the file descriptor
2081    or terminates the process in case of an error.  Note that this
2082    function needs to be used for the regular socket first (indicated
2083    by PRIMARY) and only then for the extra and the ssh sockets.  If
2084    the socket has been redirected the name of the real socket is
2085    stored as a malloced string at R_REDIR_NAME.  If CYGWIN is set a
2086    Cygwin compatible socket is created (Windows only). */
2087 static gnupg_fd_t
2088 create_server_socket (char *name, int primary, int cygwin,
2089                       char **r_redir_name, assuan_sock_nonce_t *nonce)
2090 {
2091   struct sockaddr *addr;
2092   struct sockaddr_un *unaddr;
2093   socklen_t len;
2094   gnupg_fd_t fd;
2095   int rc;
2096
2097   xfree (*r_redir_name);
2098   *r_redir_name = NULL;
2099
2100   fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
2101   if (fd == ASSUAN_INVALID_FD)
2102     {
2103       log_error (_("can't create socket: %s\n"), strerror (errno));
2104       *name = 0; /* Inhibit removal of the socket by cleanup(). */
2105       agent_exit (2);
2106     }
2107
2108   if (cygwin)
2109     assuan_sock_set_flag (fd, "cygwin", 1);
2110
2111   unaddr = xmalloc (sizeof *unaddr);
2112   addr = (struct sockaddr*)unaddr;
2113
2114   {
2115     int redirected;
2116
2117     if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
2118       {
2119         if (errno == ENAMETOOLONG)
2120           log_error (_("socket name '%s' is too long\n"), name);
2121         else
2122           log_error ("error preparing socket '%s': %s\n",
2123                      name, gpg_strerror (gpg_error_from_syserror ()));
2124         *name = 0; /* Inhibit removal of the socket by cleanup(). */
2125         agent_exit (2);
2126       }
2127     if (redirected)
2128       {
2129         *r_redir_name = xstrdup (unaddr->sun_path);
2130         if (opt.verbose)
2131           log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
2132       }
2133   }
2134
2135   len = SUN_LEN (unaddr);
2136   rc = assuan_sock_bind (fd, addr, len);
2137
2138   /* Our error code mapping on W32CE returns EEXIST thus we also test
2139      for this. */
2140   if (rc == -1
2141       && (errno == EADDRINUSE
2142 #ifdef HAVE_W32_SYSTEM
2143           || errno == EEXIST
2144 #endif
2145           ))
2146     {
2147       /* Check whether a gpg-agent is already running.  We do this
2148          test only if this is the primary socket.  For secondary
2149          sockets we assume that a test for gpg-agent has already been
2150          done and reuse the requested socket.  Testing the ssh-socket
2151          is not possible because at this point, though we know the new
2152          Assuan socket, the Assuan server and thus the ssh-agent
2153          server is not yet operational; this would lead to a hang.  */
2154       if (primary && !check_for_running_agent (1))
2155         {
2156           log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
2157           log_set_file (NULL);
2158           log_error (_("a gpg-agent is already running - "
2159                        "not starting a new one\n"));
2160           *name = 0; /* Inhibit removal of the socket by cleanup(). */
2161           assuan_sock_close (fd);
2162           agent_exit (2);
2163         }
2164       gnupg_remove (unaddr->sun_path);
2165       rc = assuan_sock_bind (fd, addr, len);
2166     }
2167   if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
2168     log_error (_("error getting nonce for the socket\n"));
2169   if (rc == -1)
2170     {
2171       /* We use gpg_strerror here because it allows us to get strings
2172          for some W32 socket error codes.  */
2173       log_error (_("error binding socket to '%s': %s\n"),
2174                  unaddr->sun_path,
2175                  gpg_strerror (gpg_error_from_syserror ()));
2176
2177       assuan_sock_close (fd);
2178       *name = 0; /* Inhibit removal of the socket by cleanup(). */
2179       agent_exit (2);
2180     }
2181
2182   if (gnupg_chmod (unaddr->sun_path, "-rwx"))
2183     log_error (_("can't set permissions of '%s': %s\n"),
2184                unaddr->sun_path, strerror (errno));
2185
2186   if (listen (FD2INT(fd), 5 ) == -1)
2187     {
2188       log_error (_("listen() failed: %s\n"), strerror (errno));
2189       *name = 0; /* Inhibit removal of the socket by cleanup(). */
2190       assuan_sock_close (fd);
2191       agent_exit (2);
2192     }
2193
2194   if (opt.verbose)
2195     log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
2196
2197   return fd;
2198 }
2199
2200
2201 /* Check that the directory for storing the private keys exists and
2202    create it if not.  This function won't fail as it is only a
2203    convenience function and not strictly necessary.  */
2204 static void
2205 create_private_keys_directory (const char *home)
2206 {
2207   char *fname;
2208   struct stat statbuf;
2209
2210   fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
2211   if (stat (fname, &statbuf) && errno == ENOENT)
2212     {
2213       if (gnupg_mkdir (fname, "-rwx"))
2214         log_error (_("can't create directory '%s': %s\n"),
2215                    fname, strerror (errno) );
2216       else if (!opt.quiet)
2217         log_info (_("directory '%s' created\n"), fname);
2218     }
2219   if (gnupg_chmod (fname, "-rwx"))
2220     log_error (_("can't set permissions of '%s': %s\n"),
2221                fname, strerror (errno));
2222   xfree (fname);
2223 }
2224
2225
2226 /* Create the directory only if the supplied directory name is the
2227    same as the default one.  This way we avoid to create arbitrary
2228    directories when a non-default home directory is used.  To cope
2229    with HOME, we compare only the suffix if we see that the default
2230    homedir does start with a tilde.  We don't stop here in case of
2231    problems because other functions will throw an error anyway.*/
2232 static void
2233 create_directories (void)
2234 {
2235   struct stat statbuf;
2236   const char *defhome = standard_homedir ();
2237   char *home;
2238
2239   home = make_filename (gnupg_homedir (), NULL);
2240   if ( stat (home, &statbuf) )
2241     {
2242       if (errno == ENOENT)
2243         {
2244           if (
2245 #ifdef HAVE_W32_SYSTEM
2246               ( !compare_filenames (home, defhome) )
2247 #else
2248               (*defhome == '~'
2249                 && (strlen (home) >= strlen (defhome+1)
2250                     && !strcmp (home + strlen(home)
2251                                 - strlen (defhome+1), defhome+1)))
2252                || (*defhome != '~' && !strcmp (home, defhome) )
2253 #endif
2254                )
2255             {
2256               if (gnupg_mkdir (home, "-rwx"))
2257                 log_error (_("can't create directory '%s': %s\n"),
2258                            home, strerror (errno) );
2259               else
2260                 {
2261                   if (!opt.quiet)
2262                     log_info (_("directory '%s' created\n"), home);
2263                   create_private_keys_directory (home);
2264                 }
2265             }
2266         }
2267       else
2268         log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
2269     }
2270   else if ( !S_ISDIR(statbuf.st_mode))
2271     {
2272       log_error (_("can't use '%s' as home directory\n"), home);
2273     }
2274   else /* exists and is a directory. */
2275     {
2276       create_private_keys_directory (home);
2277     }
2278   xfree (home);
2279 }
2280
2281
2282
2283 /* This is the worker for the ticker.  It is called every few seconds
2284    and may only do fast operations. */
2285 static void
2286 handle_tick (void)
2287 {
2288   /* Check whether the scdaemon has died and cleanup in this case. */
2289   agent_scd_check_aliveness ();
2290
2291   /* If we are running as a child of another process, check whether
2292      the parent is still alive and shutdown if not. */
2293 #ifndef HAVE_W32_SYSTEM
2294   if (parent_pid != (pid_t)(-1))
2295     {
2296       if (kill (parent_pid, 0))
2297         {
2298           shutdown_pending = 2;
2299           log_info ("parent process died - shutting down\n");
2300           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2301           cleanup ();
2302           agent_exit (0);
2303         }
2304     }
2305 #endif /*HAVE_W32_SYSTEM*/
2306 }
2307
2308
2309 /* A global function which allows us to call the reload stuff from
2310    other places too.  This is only used when build for W32.  */
2311 void
2312 agent_sighup_action (void)
2313 {
2314   log_info ("SIGHUP received - "
2315             "re-reading configuration and flushing cache\n");
2316
2317   agent_flush_cache ();
2318   reread_configuration ();
2319   agent_reload_trustlist ();
2320   /* We flush the module name cache so that after installing a
2321      "pinentry" binary that one can be used in case the
2322      "pinentry-basic" fallback was in use.  */
2323   gnupg_module_name_flush_some ();
2324 }
2325
2326
2327 /* A helper function to handle SIGUSR2.  */
2328 static void
2329 agent_sigusr2_action (void)
2330 {
2331   if (opt.verbose)
2332     log_info ("SIGUSR2 received - updating card event counter\n");
2333   /* Nothing to check right now.  We only increment a counter.  */
2334   bump_card_eventcounter ();
2335 }
2336
2337
2338 #ifndef HAVE_W32_SYSTEM
2339 /* The signal handler for this program.  It is expected to be run in
2340    its own trhead and not in the context of a signal handler.  */
2341 static void
2342 handle_signal (int signo)
2343 {
2344   switch (signo)
2345     {
2346 #ifndef HAVE_W32_SYSTEM
2347     case SIGHUP:
2348       agent_sighup_action ();
2349       break;
2350
2351     case SIGUSR1:
2352       log_info ("SIGUSR1 received - printing internal information:\n");
2353       /* Fixme: We need to see how to integrate pth dumping into our
2354          logging system.  */
2355       /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2356       agent_query_dump_state ();
2357       agent_scd_dump_state ();
2358       break;
2359
2360     case SIGUSR2:
2361       agent_sigusr2_action ();
2362       break;
2363
2364       /* nothing to do here, just take an extra cycle on the select loop */
2365     case SIGCONT:
2366       break;
2367
2368     case SIGTERM:
2369       if (!shutdown_pending)
2370         log_info ("SIGTERM received - shutting down ...\n");
2371       else
2372         log_info ("SIGTERM received - still %i open connections\n",
2373                   active_connections);
2374       shutdown_pending++;
2375       if (shutdown_pending > 2)
2376         {
2377           log_info ("shutdown forced\n");
2378           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2379           cleanup ();
2380           agent_exit (0);
2381         }
2382       break;
2383
2384     case SIGINT:
2385       log_info ("SIGINT received - immediate shutdown\n");
2386       log_info( "%s %s stopped\n", strusage(11), strusage(13));
2387       cleanup ();
2388       agent_exit (0);
2389       break;
2390 #endif
2391     default:
2392       log_info ("signal %d received - no action defined\n", signo);
2393     }
2394 }
2395 #endif
2396
2397 /* Check the nonce on a new connection.  This is a NOP unless we we
2398    are using our Unix domain socket emulation under Windows.  */
2399 static int
2400 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2401 {
2402   if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2403     {
2404       log_info (_("error reading nonce on fd %d: %s\n"),
2405                 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2406       assuan_sock_close (ctrl->thread_startup.fd);
2407       xfree (ctrl);
2408       return -1;
2409     }
2410   else
2411     return 0;
2412 }
2413
2414
2415 #ifdef HAVE_W32_SYSTEM
2416 /* The window message processing function for Putty.  Warning: This
2417    code runs as a native Windows thread.  Use of our own functions
2418    needs to be bracket with pth_leave/pth_enter. */
2419 static LRESULT CALLBACK
2420 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2421 {
2422   int ret = 0;
2423   int w32rc;
2424   COPYDATASTRUCT *cds;
2425   const char *mapfile;
2426   HANDLE maphd;
2427   PSID mysid = NULL;
2428   PSID mapsid = NULL;
2429   void *data = NULL;
2430   PSECURITY_DESCRIPTOR psd = NULL;
2431   ctrl_t ctrl = NULL;
2432
2433   if (msg != WM_COPYDATA)
2434     {
2435       return DefWindowProc (hwnd, msg, wparam, lparam);
2436     }
2437
2438   cds = (COPYDATASTRUCT*)lparam;
2439   if (cds->dwData != PUTTY_IPC_MAGIC)
2440     return 0;  /* Ignore data with the wrong magic.  */
2441   mapfile = cds->lpData;
2442   if (!cds->cbData || mapfile[cds->cbData - 1])
2443     return 0;  /* Ignore empty and non-properly terminated strings.  */
2444
2445   if (DBG_IPC)
2446     {
2447       npth_protect ();
2448       log_debug ("ssh map file '%s'", mapfile);
2449       npth_unprotect ();
2450     }
2451
2452   maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2453   if (DBG_IPC)
2454     {
2455       npth_protect ();
2456       log_debug ("ssh map handle %p\n", maphd);
2457       npth_unprotect ();
2458     }
2459
2460   if (!maphd || maphd == INVALID_HANDLE_VALUE)
2461     return 0;
2462
2463   npth_protect ();
2464
2465   mysid = w32_get_user_sid ();
2466   if (!mysid)
2467     {
2468       log_error ("error getting my sid\n");
2469       goto leave;
2470     }
2471
2472   w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2473                            OWNER_SECURITY_INFORMATION,
2474                            &mapsid, NULL, NULL, NULL,
2475                            &psd);
2476   if (w32rc)
2477     {
2478       log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2479       goto leave;
2480     }
2481
2482   if (DBG_IPC)
2483     {
2484       char *sidstr;
2485
2486       if (!ConvertSidToStringSid (mysid, &sidstr))
2487         sidstr = NULL;
2488       log_debug ("          my sid: '%s'", sidstr? sidstr: "[error]");
2489       LocalFree (sidstr);
2490       if (!ConvertSidToStringSid (mapsid, &sidstr))
2491         sidstr = NULL;
2492       log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2493       LocalFree (sidstr);
2494     }
2495
2496   if (!EqualSid (mysid, mapsid))
2497     {
2498       log_error ("ssh map file has a non-matching sid\n");
2499       goto leave;
2500     }
2501
2502   data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2503   if (DBG_IPC)
2504     log_debug ("ssh IPC buffer at %p\n", data);
2505   if (!data)
2506     goto leave;
2507
2508   /* log_printhex ("request:", data, 20); */
2509
2510   ctrl = xtrycalloc (1, sizeof *ctrl);
2511   if (!ctrl)
2512     {
2513       log_error ("error allocating connection control data: %s\n",
2514                  strerror (errno) );
2515       goto leave;
2516     }
2517   ctrl->session_env = session_env_new ();
2518   if (!ctrl->session_env)
2519     {
2520       log_error ("error allocating session environment block: %s\n",
2521                  strerror (errno) );
2522       goto leave;
2523     }
2524
2525   agent_init_default_ctrl (ctrl);
2526   if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2527     ret = 1; /* Valid ssh message has been constructed.  */
2528   agent_deinit_default_ctrl (ctrl);
2529   /* log_printhex ("  reply:", data, 20); */
2530
2531  leave:
2532   xfree (ctrl);
2533   if (data)
2534     UnmapViewOfFile (data);
2535   xfree (mapsid);
2536   if (psd)
2537     LocalFree (psd);
2538   xfree (mysid);
2539   CloseHandle (maphd);
2540
2541   npth_unprotect ();
2542
2543   return ret;
2544 }
2545 #endif /*HAVE_W32_SYSTEM*/
2546
2547
2548 #ifdef HAVE_W32_SYSTEM
2549 /* The thread handling Putty's IPC requests.  */
2550 static void *
2551 putty_message_thread (void *arg)
2552 {
2553   WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2554                         NULL, NULL, NULL, NULL, NULL, "Pageant"};
2555   HWND hwnd;
2556   MSG msg;
2557
2558   (void)arg;
2559
2560   if (opt.verbose)
2561     log_info ("putty message loop thread started\n");
2562
2563   /* The message loop runs as thread independent from our nPth system.
2564      This also means that we need to make sure that we switch back to
2565      our system before calling any no-windows function.  */
2566   npth_unprotect ();
2567
2568   /* First create a window to make sure that a message queue exists
2569      for this thread.  */
2570   if (!RegisterClass (&wndwclass))
2571     {
2572       npth_protect ();
2573       log_error ("error registering Pageant window class");
2574       return NULL;
2575     }
2576   hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2577                          0, 0, 0, 0,
2578                          HWND_MESSAGE,  /* hWndParent */
2579                          NULL,          /* hWndMenu   */
2580                          NULL,          /* hInstance  */
2581                          NULL);         /* lpParm     */
2582   if (!hwnd)
2583     {
2584       npth_protect ();
2585       log_error ("error creating Pageant window");
2586       return NULL;
2587     }
2588
2589   while (GetMessage(&msg, NULL, 0, 0))
2590     {
2591       TranslateMessage(&msg);
2592       DispatchMessage(&msg);
2593     }
2594
2595   /* Back to nPth.  */
2596   npth_protect ();
2597
2598   if (opt.verbose)
2599     log_info ("putty message loop thread stopped\n");
2600   return NULL;
2601 }
2602 #endif /*HAVE_W32_SYSTEM*/
2603
2604
2605 static void *
2606 do_start_connection_thread (ctrl_t ctrl)
2607 {
2608   active_connections++;
2609   agent_init_default_ctrl (ctrl);
2610   if (opt.verbose && !DBG_IPC)
2611     log_info (_("handler 0x%lx for fd %d started\n"),
2612               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2613
2614   start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2615   if (opt.verbose && !DBG_IPC)
2616     log_info (_("handler 0x%lx for fd %d terminated\n"),
2617               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2618
2619   agent_deinit_default_ctrl (ctrl);
2620   xfree (ctrl);
2621   active_connections--;
2622   return NULL;
2623 }
2624
2625
2626 /* This is the standard connection thread's main function.  */
2627 static void *
2628 start_connection_thread_std (void *arg)
2629 {
2630   ctrl_t ctrl = arg;
2631
2632   if (check_nonce (ctrl, &socket_nonce))
2633     {
2634       log_error ("handler 0x%lx nonce check FAILED\n",
2635                  (unsigned long) npth_self());
2636       return NULL;
2637     }
2638
2639   return do_start_connection_thread (ctrl);
2640 }
2641
2642
2643 /* This is the extra socket connection thread's main function.  */
2644 static void *
2645 start_connection_thread_extra (void *arg)
2646 {
2647   ctrl_t ctrl = arg;
2648
2649   if (check_nonce (ctrl, &socket_nonce_extra))
2650     {
2651       log_error ("handler 0x%lx nonce check FAILED\n",
2652                  (unsigned long) npth_self());
2653       return NULL;
2654     }
2655
2656   ctrl->restricted = 1;
2657   return do_start_connection_thread (ctrl);
2658 }
2659
2660
2661 /* This is the browser socket connection thread's main function.  */
2662 static void *
2663 start_connection_thread_browser (void *arg)
2664 {
2665   ctrl_t ctrl = arg;
2666
2667   if (check_nonce (ctrl, &socket_nonce_browser))
2668     {
2669       log_error ("handler 0x%lx nonce check FAILED\n",
2670                  (unsigned long) npth_self());
2671       return NULL;
2672     }
2673
2674   ctrl->restricted = 2;
2675   return do_start_connection_thread (ctrl);
2676 }
2677
2678
2679 /* This is the ssh connection thread's main function.  */
2680 static void *
2681 start_connection_thread_ssh (void *arg)
2682 {
2683   ctrl_t ctrl = arg;
2684
2685   if (check_nonce (ctrl, &socket_nonce_ssh))
2686     return NULL;
2687
2688   active_connections++;
2689   agent_init_default_ctrl (ctrl);
2690   if (opt.verbose)
2691     log_info (_("ssh handler 0x%lx for fd %d started\n"),
2692               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2693
2694   start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2695   if (opt.verbose)
2696     log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2697               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2698
2699   agent_deinit_default_ctrl (ctrl);
2700   xfree (ctrl);
2701   active_connections--;
2702   return NULL;
2703 }
2704
2705
2706 void interrupt_main_thread_loop (void)
2707 {
2708 #ifndef HAVE_W32_SYSTEM
2709   kill (main_thread_pid, SIGCONT);
2710 #endif
2711 }
2712
2713 /* helper function for readability: test whether a given struct
2714    timespec is set to all-zeros */
2715 static inline int
2716 tv_is_set (struct timespec tv)
2717 {
2718   return tv.tv_sec || tv.tv_nsec;
2719 }
2720
2721
2722 /* Connection handler loop.  Wait for connection requests and spawn a
2723    thread after accepting a connection.  */
2724 static void
2725 handle_connections (gnupg_fd_t listen_fd,
2726                     gnupg_fd_t listen_fd_extra,
2727                     gnupg_fd_t listen_fd_browser,
2728                     gnupg_fd_t listen_fd_ssh)
2729 {
2730   gpg_error_t err;
2731   npth_attr_t tattr;
2732   struct sockaddr_un paddr;
2733   socklen_t plen;
2734   fd_set fdset, read_fdset;
2735   int ret;
2736   gnupg_fd_t fd;
2737   int nfd;
2738   int saved_errno;
2739   int idx;
2740   struct timespec abstime;
2741   struct timespec curtime;
2742   struct timespec timeout;
2743   struct timespec *select_timeout;
2744 #ifdef HAVE_W32_SYSTEM
2745   HANDLE events[2];
2746   unsigned int events_set;
2747 #endif
2748   int my_inotify_fd = -1;
2749   struct {
2750     const char *name;
2751     void *(*func) (void *arg);
2752     gnupg_fd_t l_fd;
2753   } listentbl[] = {
2754     { "std",     start_connection_thread_std   },
2755     { "extra",   start_connection_thread_extra },
2756     { "browser", start_connection_thread_browser },
2757     { "ssh",    start_connection_thread_ssh   }
2758   };
2759   struct {
2760     struct timespec interval;
2761     void (*func) (void);
2762     struct timespec next;
2763   } timertbl[] = {
2764     { { TIMERTICK_INTERVAL, 0 }, handle_tick },
2765     { { CHECK_OWN_SOCKET_INTERVAL, 0 }, check_own_socket }
2766   };
2767
2768
2769   ret = npth_attr_init(&tattr);
2770   if (ret)
2771     log_fatal ("error allocating thread attributes: %s\n",
2772                strerror (ret));
2773   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2774
2775 #ifndef HAVE_W32_SYSTEM
2776   npth_sigev_init ();
2777   npth_sigev_add (SIGHUP);
2778   npth_sigev_add (SIGUSR1);
2779   npth_sigev_add (SIGUSR2);
2780   npth_sigev_add (SIGINT);
2781   npth_sigev_add (SIGCONT);
2782   npth_sigev_add (SIGTERM);
2783   npth_sigev_fini ();
2784   main_thread_pid = getpid ();
2785 #else
2786 # ifdef HAVE_W32CE_SYSTEM
2787   /* Use a dummy event. */
2788   sigs = 0;
2789   ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2790 # else
2791   events[0] = get_agent_scd_notify_event ();
2792   events[1] = INVALID_HANDLE_VALUE;
2793 # endif
2794 #endif
2795
2796   if (disable_check_own_socket)
2797     my_inotify_fd = -1;
2798   else if ((err = gnupg_inotify_watch_socket (&my_inotify_fd, socket_name)))
2799     {
2800       if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2801         log_info ("error enabling fast daemon termination: %s\n",
2802                   gpg_strerror (err));
2803     }
2804
2805   /* On Windows we need to fire up a separate thread to listen for
2806      requests from Putty (an SSH client), so we can replace Putty's
2807      Pageant (its ssh-agent implementation). */
2808 #ifdef HAVE_W32_SYSTEM
2809   if (putty_support)
2810     {
2811       npth_t thread;
2812
2813       ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2814       if (ret)
2815         {
2816           log_error ("error spawning putty message loop: %s\n", strerror (ret));
2817         }
2818     }
2819 #endif /*HAVE_W32_SYSTEM*/
2820
2821   /* Set a flag to tell call-scd.c that it may enable event
2822      notifications.  */
2823   opt.sigusr2_enabled = 1;
2824
2825   FD_ZERO (&fdset);
2826   FD_SET (FD2INT (listen_fd), &fdset);
2827   nfd = FD2INT (listen_fd);
2828   if (listen_fd_extra != GNUPG_INVALID_FD)
2829     {
2830       FD_SET ( FD2INT(listen_fd_extra), &fdset);
2831       if (FD2INT (listen_fd_extra) > nfd)
2832         nfd = FD2INT (listen_fd_extra);
2833     }
2834   if (listen_fd_browser != GNUPG_INVALID_FD)
2835     {
2836       FD_SET ( FD2INT(listen_fd_browser), &fdset);
2837       if (FD2INT (listen_fd_browser) > nfd)
2838         nfd = FD2INT (listen_fd_browser);
2839     }
2840   if (listen_fd_ssh != GNUPG_INVALID_FD)
2841     {
2842       FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2843       if (FD2INT (listen_fd_ssh) > nfd)
2844         nfd = FD2INT (listen_fd_ssh);
2845     }
2846   if (my_inotify_fd != -1)
2847     {
2848       FD_SET (my_inotify_fd, &fdset);
2849       if (my_inotify_fd > nfd)
2850         nfd = my_inotify_fd;
2851     }
2852
2853   listentbl[0].l_fd = listen_fd;
2854   listentbl[1].l_fd = listen_fd_extra;
2855   listentbl[2].l_fd = listen_fd_browser;
2856   listentbl[3].l_fd = listen_fd_ssh;
2857
2858   for (;;)
2859     {
2860       /* Shutdown test.  */
2861       if (shutdown_pending)
2862         {
2863           if (active_connections == 0)
2864             break; /* ready */
2865
2866           /* Do not accept new connections but keep on running the
2867            * loop to cope with the timer events.
2868            *
2869            * Note that we do not close the listening socket because a
2870            * client trying to connect to that socket would instead
2871            * restart a new dirmngr instance - which is unlikely the
2872            * intention of a shutdown. */
2873           FD_ZERO (&fdset);
2874           nfd = -1;
2875           if (my_inotify_fd != -1)
2876             {
2877               FD_SET (my_inotify_fd, &fdset);
2878               nfd = my_inotify_fd;
2879             }
2880         }
2881
2882       /* POSIX says that fd_set should be implemented as a structure,
2883          thus a simple assignment is fine to copy the entire set.  */
2884       read_fdset = fdset;
2885
2886       /* loop through all timers, fire any registered functions, and
2887          plan next timer to trigger */
2888       npth_clock_gettime (&curtime);
2889       abstime.tv_sec = abstime.tv_nsec = 0;
2890       for (idx=0; idx < DIM(timertbl); idx++)
2891         {
2892           /* schedule any unscheduled timers */
2893           if ((!tv_is_set (timertbl[idx].next)) && tv_is_set (timertbl[idx].interval))
2894             npth_timeradd (&timertbl[idx].interval, &curtime, &timertbl[idx].next);
2895           /* if a timer is due, fire it ... */
2896           if (tv_is_set (timertbl[idx].next))
2897             {
2898               if (!(npth_timercmp (&curtime, &timertbl[idx].next, <)))
2899                 {
2900                   timertbl[idx].func ();
2901                   npth_clock_gettime (&curtime);
2902                   /* ...and reschedule it, if desired: */
2903                   if (tv_is_set (timertbl[idx].interval))
2904                     npth_timeradd (&timertbl[idx].interval, &curtime, &timertbl[idx].next);
2905                   else
2906                     timertbl[idx].next.tv_sec = timertbl[idx].next.tv_nsec = 0;
2907                 }
2908             }
2909           /* accumulate next timer to come due in abstime: */
2910           if (tv_is_set (timertbl[idx].next) &&
2911               ((!tv_is_set (abstime)) ||
2912                (npth_timercmp (&abstime, &timertbl[idx].next, >))))
2913             abstime = timertbl[idx].next;
2914         }
2915       /* choose a timeout for the select loop: */
2916       if (tv_is_set (abstime))
2917         {
2918           npth_timersub (&abstime, &curtime, &timeout);
2919           select_timeout = &timeout;
2920         }
2921       else
2922           select_timeout = NULL;
2923       
2924
2925 #ifndef HAVE_W32_SYSTEM
2926       ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, select_timeout,
2927                           npth_sigev_sigmask ());
2928       saved_errno = errno;
2929
2930       {
2931         int signo;
2932         while (npth_sigev_get_pending (&signo))
2933           handle_signal (signo);
2934       }
2935 #else
2936       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, select_timeout,
2937                           events, &events_set);
2938       saved_errno = errno;
2939
2940       /* This is valid even if npth_eselect returns an error.  */
2941       if (events_set & 1)
2942         agent_sigusr2_action ();
2943 #endif
2944
2945       if (ret == -1 && saved_errno != EINTR)
2946         {
2947           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2948                      strerror (saved_errno));
2949           npth_sleep (1);
2950           continue;
2951         }
2952       if (ret <= 0)
2953         /* Interrupt or timeout.  Will be handled when calculating the
2954            next timeout.  */
2955         continue;
2956
2957       if (!shutdown_pending)
2958         {
2959           ctrl_t ctrl;
2960           npth_t thread;
2961
2962           if (my_inotify_fd != -1
2963               && FD_ISSET (my_inotify_fd, &read_fdset)
2964               && gnupg_inotify_has_name (my_inotify_fd, GPG_AGENT_SOCK_NAME))
2965             {
2966               shutdown_pending = 1;
2967               log_info ("socket file has been removed - shutting down\n");
2968             }
2969
2970           for (idx=0; idx < DIM(listentbl); idx++)
2971             {
2972               if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2973                 continue;
2974               if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2975                 continue;
2976
2977               plen = sizeof paddr;
2978               fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2979                                         (struct sockaddr *)&paddr, &plen));
2980               if (fd == GNUPG_INVALID_FD)
2981                 {
2982                   log_error ("accept failed for %s: %s\n",
2983                              listentbl[idx].name, strerror (errno));
2984                 }
2985               else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2986                 {
2987                   log_error ("error allocating connection data for %s: %s\n",
2988                              listentbl[idx].name, strerror (errno) );
2989                   assuan_sock_close (fd);
2990                 }
2991               else if ( !(ctrl->session_env = session_env_new ()))
2992                 {
2993                   log_error ("error allocating session env block for %s: %s\n",
2994                              listentbl[idx].name, strerror (errno) );
2995                   xfree (ctrl);
2996                   assuan_sock_close (fd);
2997                 }
2998               else
2999                 {
3000                   ctrl->thread_startup.fd = fd;
3001                   ret = npth_create (&thread, &tattr,
3002                                      listentbl[idx].func, ctrl);
3003                   if (ret)
3004                     {
3005                       log_error ("error spawning connection handler for %s:"
3006                                  " %s\n", listentbl[idx].name, strerror (ret));
3007                       assuan_sock_close (fd);
3008                       xfree (ctrl);
3009                     }
3010                 }
3011               fd = GNUPG_INVALID_FD;
3012             }
3013         }
3014     }
3015
3016   if (my_inotify_fd != -1)
3017     close (my_inotify_fd);
3018   cleanup ();
3019   log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
3020   npth_attr_destroy (&tattr);
3021 }
3022
3023
3024
3025 /* Helper for check_own_socket.  */
3026 static gpg_error_t
3027 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
3028 {
3029   membuf_t *mb = opaque;
3030   put_membuf (mb, buffer, length);
3031   return 0;
3032 }
3033
3034
3035 /* The thread running the actual check.  We need to run this in a
3036    separate thread so that check_own_thread can be called from the
3037    timer tick.  */
3038 static void *
3039 check_own_socket_thread (void *arg)
3040 {
3041   int rc;
3042   char *sockname = arg;
3043   assuan_context_t ctx = NULL;
3044   membuf_t mb;
3045   char *buffer;
3046
3047   check_own_socket_running++;
3048
3049   rc = assuan_new (&ctx);
3050   if (rc)
3051     {
3052       log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
3053       goto leave;
3054     }
3055   assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
3056
3057   rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3058   if (rc)
3059     {
3060       log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
3061       goto leave;
3062     }
3063
3064   init_membuf (&mb, 100);
3065   rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
3066                         NULL, NULL, NULL, NULL);
3067   put_membuf (&mb, "", 1);
3068   buffer = get_membuf (&mb, NULL);
3069   if (rc || !buffer)
3070     {
3071       log_error ("sending command \"%s\" to my own socket failed: %s\n",
3072                  "GETINFO pid", gpg_strerror (rc));
3073       rc = 1;
3074     }
3075   else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
3076     {
3077       log_error ("socket is now serviced by another server\n");
3078       rc = 1;
3079     }
3080   else if (opt.verbose > 1)
3081     log_error ("socket is still served by this server\n");
3082
3083   xfree (buffer);
3084
3085  leave:
3086   xfree (sockname);
3087   if (ctx)
3088     assuan_release (ctx);
3089   if (rc)
3090     {
3091       /* We may not remove the socket as it is now in use by another
3092          server. */
3093       inhibit_socket_removal = 1;
3094       shutdown_pending = 2;
3095       log_info ("this process is useless - shutting down\n");
3096     }
3097   check_own_socket_running--;
3098   return NULL;
3099 }
3100
3101
3102 /* Check whether we are still listening on our own socket.  In case
3103    another gpg-agent process started after us has taken ownership of
3104    our socket, we would linger around without any real task.  Thus we
3105    better check once in a while whether we are really needed.  */
3106 static void
3107 check_own_socket (void)
3108 {
3109   char *sockname;
3110   npth_t thread;
3111   npth_attr_t tattr;
3112   int err;
3113
3114   if (disable_check_own_socket)
3115     return;
3116
3117   if (check_own_socket_running || shutdown_pending)
3118     return;  /* Still running or already shutting down.  */
3119
3120   sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3121   if (!sockname)
3122     return; /* Out of memory.  */
3123
3124   err = npth_attr_init (&tattr);
3125   if (err)
3126     return;
3127   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3128   err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
3129   if (err)
3130     log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
3131   npth_attr_destroy (&tattr);
3132 }
3133
3134
3135
3136 /* Figure out whether an agent is available and running. Prints an
3137    error if not.  If SILENT is true, no messages are printed.
3138    Returns 0 if the agent is running. */
3139 static int
3140 check_for_running_agent (int silent)
3141 {
3142   gpg_error_t err;
3143   char *sockname;
3144   assuan_context_t ctx = NULL;
3145
3146   sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3147   if (!sockname)
3148     return gpg_error_from_syserror ();
3149
3150   err = assuan_new (&ctx);
3151   if (!err)
3152     err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3153   xfree (sockname);
3154   if (err)
3155     {
3156       if (!silent)
3157         log_error (_("no gpg-agent running in this session\n"));
3158
3159       if (ctx)
3160         assuan_release (ctx);
3161       return -1;
3162     }
3163
3164   if (!opt.quiet && !silent)
3165     log_info ("gpg-agent running and available\n");
3166
3167   assuan_release (ctx);
3168   return 0;
3169 }