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