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