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