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