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