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