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