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