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