Imported Upstream version 2.0.19
[platform/upstream/gpg2.git] / agent / gpg-agent.c
1 /* gpg-agent.c  -  The GnuPG Agent
2  * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005,
3  *               2006, 2007, 2009, 2010 Free Software Foundation, Inc.
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 #ifndef HAVE_W32_SYSTEM
34 # include <sys/socket.h>
35 # include <sys/un.h>
36 #endif /*!HAVE_W32_SYSTEM*/
37 #include <unistd.h>
38 #include <signal.h>
39 #include <pth.h>
40
41 #define JNLIB_NEED_LOG_LOGV
42 #define JNLIB_NEED_AFLOCAL
43 #include "agent.h"
44 #include <assuan.h> /* Malloc hooks  and socket wrappers. */
45
46 #include "i18n.h"
47 #include "mkdtemp.h" /* Gnulib replacement. */
48 #include "sysutils.h"
49 #include "setenv.h"
50 #include "gc-opt-flags.h"
51 #include "exechelp.h"
52 #include "../common/estream.h"
53
54 enum cmd_and_opt_values
55 { aNull = 0,
56   oCsh            = 'c',
57   oQuiet          = 'q',
58   oSh             = 's',
59   oVerbose        = 'v',
60
61   oNoVerbose = 500,
62   aGPGConfList,
63   aGPGConfTest,
64   aUseStandardSocketP,
65   oOptions,
66   oDebug,
67   oDebugAll,
68   oDebugLevel,
69   oDebugWait,
70   oNoGreeting,
71   oNoOptions,
72   oHomedir,
73   oNoDetach,
74   oNoGrab,
75   oLogFile,
76   oServer,
77   oDaemon,
78   oBatch,
79
80   oPinentryProgram,
81   oPinentryTouchFile,
82   oDisplay,
83   oTTYname,
84   oTTYtype,
85   oLCctype,
86   oLCmessages,
87   oXauthority,
88   oScdaemonProgram,
89   oDefCacheTTL,
90   oDefCacheTTLSSH,
91   oMaxCacheTTL,
92   oMaxCacheTTLSSH,
93   oEnforcePassphraseConstraints,
94   oMinPassphraseLen,
95   oMinPassphraseNonalpha,
96   oCheckPassphrasePattern,
97   oMaxPassphraseDays,
98   oEnablePassphraseHistory,
99   oUseStandardSocket,
100   oNoUseStandardSocket,
101   oFakedSystemTime,
102
103   oIgnoreCacheForSigning,
104   oAllowMarkTrusted,
105   oAllowPresetPassphrase,
106   oKeepTTY,
107   oKeepDISPLAY,
108   oSSHSupport,
109   oDisableScdaemon,
110   oWriteEnvFile
111 };
112
113
114
115 static ARGPARSE_OPTS opts[] = {
116
117   { aGPGConfList, "gpgconf-list", 256, "@" },
118   { aGPGConfTest, "gpgconf-test", 256, "@" },
119   { aUseStandardSocketP, "use-standard-socket-p", 256, "@" },
120
121   { 301, NULL, 0, N_("@Options:\n ") },
122
123   { oServer,   "server",     0, N_("run in server mode (foreground)") },
124   { oDaemon,   "daemon",     0, N_("run in daemon mode (background)") },
125   { oVerbose, "verbose",     0, N_("verbose") },
126   { oQuiet,     "quiet",     0, N_("be somewhat more quiet") },
127   { oSh,        "sh",        0, N_("sh-style command output") },
128   { oCsh,       "csh",       0, N_("csh-style command output") },
129   { oOptions, "options"  , 2, N_("|FILE|read options from FILE")},
130   { oDebug,     "debug"     ,4|16, "@"},
131   { oDebugAll, "debug-all"     ,0, "@"},
132   { oDebugLevel, "debug-level" ,2, "@"},
133   { oDebugWait,"debug-wait",1, "@"},
134   { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
135   { oNoGrab, "no-grab"     ,0, N_("do not grab keyboard and mouse")},
136   { oLogFile, "log-file"   ,2, N_("use a log file for the server")},
137   { oUseStandardSocket, "use-standard-socket", 0,
138                       N_("use a standard location for the socket")},
139   { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
140   { oPinentryProgram, "pinentry-program", 2 ,
141                                N_("|PGM|use PGM as the PIN-Entry program") },
142   { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
143   { oScdaemonProgram, "scdaemon-program", 2 ,
144                                N_("|PGM|use PGM as the SCdaemon program") },
145   { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
146   { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
147
148   { oBatch,      "batch",       0, "@" },
149   { oHomedir,    "homedir",     2, "@"},
150
151   { oDisplay,    "display",     2, "@" },
152   { oTTYname,    "ttyname",     2, "@" },
153   { oTTYtype,    "ttytype",     2, "@" },
154   { oLCctype,    "lc-ctype",    2, "@" },
155   { oLCmessages, "lc-messages", 2, "@" },
156   { oXauthority, "xauthority",  2, "@" },
157   { oKeepTTY,    "keep-tty",    0,  N_("ignore requests to change the TTY")},
158   { oKeepDISPLAY, "keep-display",
159                           0, N_("ignore requests to change the X display")},
160
161   { oDefCacheTTL, "default-cache-ttl", 4,
162                                N_("|N|expire cached PINs after N seconds")},
163   { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
164   { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
165   { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
166
167   { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
168   { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
169   { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
170   { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
171   { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
172   { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
173
174   { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
175                                N_("do not use the PIN cache when signing")},
176   { oAllowMarkTrusted, "allow-mark-trusted", 0,
177                              N_("allow clients to mark keys as \"trusted\"")},
178   { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
179                              N_("allow presetting passphrase")},
180   { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
181   { oWriteEnvFile, "write-env-file", 2|8,
182             N_("|FILE|write environment settings also to FILE")},
183   {0}
184 };
185
186
187 #define DEFAULT_CACHE_TTL     (10*60)  /* 10 minutes */
188 #define DEFAULT_CACHE_TTL_SSH (30*60)  /* 30 minutes */
189 #define MAX_CACHE_TTL         (120*60) /* 2 hours */
190 #define MAX_CACHE_TTL_SSH     (120*60) /* 2 hours */
191 #define MIN_PASSPHRASE_LEN    (8)
192 #define MIN_PASSPHRASE_NONALPHA (1)
193 #define MAX_PASSPHRASE_DAYS   (0)
194
195 /* The timer tick used for housekeeping stuff.  For Windows we use a
196    longer period as the SetWaitableTimer seems to signal earlier than
197    the 2 seconds.  */
198 #ifdef HAVE_W32_SYSTEM
199 #define TIMERTICK_INTERVAL    (4)
200 #else
201 #define TIMERTICK_INTERVAL    (2)    /* Seconds.  */
202 #endif
203
204
205 /* The list of open file descriptors at startup.  Note that this list
206    has been allocated using the standard malloc.  */
207 static int *startup_fd_list;
208
209 /* The signal mask at startup and a flag telling whether it is valid.  */
210 #ifdef HAVE_SIGPROCMASK
211 static sigset_t startup_signal_mask;
212 static int startup_signal_mask_valid;
213 #endif
214
215 /* Flag to indicate that a shutdown was requested.  */
216 static int shutdown_pending;
217
218 /* Counter for the currently running own socket checks.  */
219 static int check_own_socket_running;
220
221 /* It is possible that we are currently running under setuid permissions */
222 static int maybe_setuid = 1;
223
224 /* Name of the communication socket used for native gpg-agent requests.  */
225 static char *socket_name;
226
227 /* Name of the communication socket used for ssh-agent-emulation.  */
228 static char *socket_name_ssh;
229
230 /* We need to keep track of the server's nonces (these are dummies for
231    POSIX systems). */
232 static assuan_sock_nonce_t socket_nonce;
233 static assuan_sock_nonce_t socket_nonce_ssh;
234
235
236 /* Default values for options passed to the pinentry. */
237 static char *default_display;
238 static char *default_ttyname;
239 static char *default_ttytype;
240 static char *default_lc_ctype;
241 static char *default_lc_messages;
242 static char *default_xauthority;
243
244 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
245 static char *config_filename;
246
247 /* Helper to implement --debug-level */
248 static const char *debug_level;
249
250 /* Keep track of the current log file so that we can avoid updating
251    the log file after a SIGHUP if it didn't changed. Malloced. */
252 static char *current_logfile;
253
254 /* The handle_tick() function may test whether a parent is still
255    running.  We record the PID of the parent here or -1 if it should be
256    watched. */
257 static pid_t parent_pid = (pid_t)(-1);
258
259 \f
260 /*
261    Local prototypes.
262  */
263
264 static char *create_socket_name (char *standard_name, char *template);
265 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
266                                         assuan_sock_nonce_t *nonce);
267 static void create_directories (void);
268
269 static void agent_init_default_ctrl (ctrl_t ctrl);
270 static void agent_deinit_default_ctrl (ctrl_t ctrl);
271
272 static void handle_connections (gnupg_fd_t listen_fd,
273                                 gnupg_fd_t listen_fd_ssh);
274 static void check_own_socket (void);
275 static int check_for_running_agent (int silent, int mode);
276
277 /* Pth wrapper function definitions. */
278 ASSUAN_SYSTEM_PTH_IMPL;
279
280 GCRY_THREAD_OPTION_PTH_IMPL;
281 static int fixed_gcry_pth_init (void)
282 {
283   return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
284 }
285
286
287 #ifndef PTH_HAVE_PTH_THREAD_ID
288 static unsigned long pth_thread_id (void)
289 {
290   return (unsigned long)pth_self ();
291 }
292 #endif
293
294
295 \f
296 /*
297    Functions.
298  */
299
300 static char *
301 make_libversion (const char *libname, const char *(*getfnc)(const char*))
302 {
303   const char *s;
304   char *result;
305
306   if (maybe_setuid)
307     {
308       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
309       maybe_setuid = 0;
310     }
311   s = getfnc (NULL);
312   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
313   strcpy (stpcpy (stpcpy (result, libname), " "), s);
314   return result;
315 }
316
317
318 static const char *
319 my_strusage (int level)
320 {
321   static char *ver_gcry;
322   const char *p;
323
324   switch (level)
325     {
326     case 11: p = "gpg-agent (GnuPG)";
327       break;
328     case 13: p = VERSION; break;
329     case 17: p = PRINTABLE_OS_NAME; break;
330       /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
331          reporting address.  This is so that we can change the
332          reporting address without breaking the translations.  */
333     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
334
335     case 20:
336       if (!ver_gcry)
337         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
338       p = ver_gcry;
339       break;
340
341     case 1:
342     case 40: p =  _("Usage: gpg-agent [options] (-h for help)");
343       break;
344     case 41: p =  _("Syntax: gpg-agent [options] [command [args]]\n"
345                     "Secret key management for GnuPG\n");
346     break;
347
348     default: p = NULL;
349     }
350   return p;
351 }
352
353
354
355 /* Setup the debugging.  With the global variable DEBUG_LEVEL set to NULL
356    only the active debug flags are propagated to the subsystems.  With
357    DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
358    all flags already set. Note that we don't fail here, because it is
359    important to keep gpg-agent running even after re-reading the
360    options due to a SIGHUP. */
361 static void
362 set_debug (void)
363 {
364   int numok = (debug_level && digitp (debug_level));
365   int numlvl = numok? atoi (debug_level) : 0;
366
367   if (!debug_level)
368     ;
369   else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
370     opt.debug = 0;
371   else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
372     opt.debug = DBG_ASSUAN_VALUE;
373   else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
374     opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
375   else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
376     opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
377                  |DBG_CACHE_VALUE);
378   else if (!strcmp (debug_level, "guru") || numok)
379     {
380       opt.debug = ~0;
381       /* Unless the "guru" string has been used we don't want to allow
382          hashing debugging.  The rationale is that people tend to
383          select the highest debug value and would then clutter their
384          disk with debug files which may reveal confidential data.  */
385       if (numok)
386         opt.debug &= ~(DBG_HASHING_VALUE);
387     }
388   else
389     {
390       log_error (_("invalid debug-level `%s' given\n"), debug_level);
391       opt.debug = 0; /* Reset debugging, so that prior debug
392                         statements won't have an undesired effect. */
393     }
394
395   if (opt.debug && !opt.verbose)
396     opt.verbose = 1;
397   if (opt.debug && opt.quiet)
398     opt.quiet = 0;
399
400   if (opt.debug & DBG_MPI_VALUE)
401     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
402   if (opt.debug & DBG_CRYPTO_VALUE )
403     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
404   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
405
406   if (opt.debug)
407     log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
408               (opt.debug & DBG_COMMAND_VALUE)? " command":"",
409               (opt.debug & DBG_MPI_VALUE    )? " mpi":"",
410               (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
411               (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
412               (opt.debug & DBG_CACHE_VALUE  )? " cache":"",
413               (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
414               (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
415               (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
416 }
417
418
419 /* Helper for cleanup to remove one socket with NAME.  */
420 static void
421 remove_socket (char *name)
422 {
423   if (name && *name)
424     {
425       char *p;
426
427       remove (name);
428       p = strrchr (name, '/');
429       if (p)
430         {
431           *p = 0;
432           rmdir (name);
433           *p = '/';
434         }
435       *name = 0;
436     }
437 }
438
439 static void
440 cleanup (void)
441 {
442   remove_socket (socket_name);
443   remove_socket (socket_name_ssh);
444 }
445
446
447
448 /* Handle options which are allowed to be reset after program start.
449    Return true when the current option in PARGS could be handled and
450    false if not.  As a special feature, passing a value of NULL for
451    PARGS, resets the options to the default.  REREAD should be set
452    true if it is not the initial option parsing. */
453 static int
454 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
455 {
456   if (!pargs)
457     { /* reset mode */
458       opt.quiet = 0;
459       opt.verbose = 0;
460       opt.debug = 0;
461       opt.no_grab = 0;
462       opt.pinentry_program = NULL;
463       opt.pinentry_touch_file = NULL;
464       opt.scdaemon_program = NULL;
465       opt.def_cache_ttl = DEFAULT_CACHE_TTL;
466       opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
467       opt.max_cache_ttl = MAX_CACHE_TTL;
468       opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
469       opt.enforce_passphrase_constraints = 0;
470       opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
471       opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
472       opt.check_passphrase_pattern = NULL;
473       opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
474       opt.enable_passhrase_history = 0;
475       opt.ignore_cache_for_signing = 0;
476       opt.allow_mark_trusted = 0;
477       opt.disable_scdaemon = 0;
478       return 1;
479     }
480
481   switch (pargs->r_opt)
482     {
483     case oQuiet: opt.quiet = 1; break;
484     case oVerbose: opt.verbose++; break;
485
486     case oDebug: opt.debug |= pargs->r.ret_ulong; break;
487     case oDebugAll: opt.debug = ~0; break;
488     case oDebugLevel: debug_level = pargs->r.ret_str; break;
489
490     case oLogFile:
491       if (!reread)
492         return 0; /* not handeld */
493       if (!current_logfile || !pargs->r.ret_str
494           || strcmp (current_logfile, pargs->r.ret_str))
495         {
496           log_set_file (pargs->r.ret_str);
497           if (DBG_ASSUAN)
498             assuan_set_assuan_log_stream (log_get_stream ());
499           xfree (current_logfile);
500           current_logfile = xtrystrdup (pargs->r.ret_str);
501         }
502       break;
503
504     case oNoGrab: opt.no_grab = 1; break;
505
506     case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
507     case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
508     case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
509     case oDisableScdaemon: opt.disable_scdaemon = 1; break;
510
511     case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
512     case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
513     case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
514     case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
515
516     case oEnforcePassphraseConstraints:
517       opt.enforce_passphrase_constraints=1;
518       break;
519     case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
520     case oMinPassphraseNonalpha:
521       opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
522       break;
523     case oCheckPassphrasePattern:
524       opt.check_passphrase_pattern = pargs->r.ret_str;
525       break;
526     case oMaxPassphraseDays:
527       opt.max_passphrase_days = pargs->r.ret_ulong;
528       break;
529     case oEnablePassphraseHistory:
530       opt.enable_passhrase_history = 1;
531       break;
532
533     case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
534
535     case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
536
537     case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
538
539     default:
540       return 0; /* not handled */
541     }
542
543   return 1; /* handled */
544 }
545
546
547 /* The main entry point.  */
548 int
549 main (int argc, char **argv )
550 {
551   ARGPARSE_ARGS pargs;
552   int orig_argc;
553   char **orig_argv;
554   FILE *configfp = NULL;
555   char *configname = NULL;
556   const char *shell;
557   unsigned configlineno;
558   int parse_debug = 0;
559   int default_config =1;
560   int greeting = 0;
561   int nogreeting = 0;
562   int pipe_server = 0;
563   int is_daemon = 0;
564   int nodetach = 0;
565   int csh_style = 0;
566   char *logfile = NULL;
567   int debug_wait = 0;
568   int gpgconf_list = 0;
569   gpg_error_t err;
570   const char *env_file_name = NULL;
571   struct assuan_malloc_hooks malloc_hooks;
572
573   /* Before we do anything else we save the list of currently open
574      file descriptors and the signal mask.  This info is required to
575      do the exec call properly. */
576   startup_fd_list = get_all_open_fds ();
577 #ifdef HAVE_SIGPROCMASK
578   if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
579     startup_signal_mask_valid = 1;
580 #endif /*HAVE_SIGPROCMASK*/
581
582   /* Set program name etc.  */
583   set_strusage (my_strusage);
584   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
585   /* Please note that we may running SUID(ROOT), so be very CAREFUL
586      when adding any stuff between here and the call to INIT_SECMEM()
587      somewhere after the option parsing */
588   log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
589
590   /* Make sure that our subsystems are ready.  */
591   i18n_init ();
592   init_common_subsystems ();
593
594
595   /* Libgcrypt requires us to register the threading model first.
596      Note that this will also do the pth_init. */
597   gcry_threads_pth.init = fixed_gcry_pth_init;
598   err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
599   if (err)
600     {
601       log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
602                  gpg_strerror (err));
603     }
604
605
606   /* Check that the libraries are suitable.  Do it here because
607      the option parsing may need services of the library. */
608   if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
609     {
610       log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
611                  NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
612     }
613
614   malloc_hooks.malloc = gcry_malloc;
615   malloc_hooks.realloc = gcry_realloc;
616   malloc_hooks.free = gcry_free;
617   assuan_set_malloc_hooks (&malloc_hooks);
618   assuan_set_assuan_log_prefix (log_get_prefix (NULL));
619   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
620   assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
621   assuan_sock_init ();
622
623   setup_libgcrypt_logging ();
624   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
625
626   disable_core_dumps ();
627
628   /* Set default options.  */
629   parse_rereadable_options (NULL, 0); /* Reset them to default values. */
630 #ifdef USE_STANDARD_SOCKET
631   opt.use_standard_socket = 1;  /* Under Windows we always use a standard
632                                    socket.  */
633 #endif
634
635   shell = getenv ("SHELL");
636   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
637     csh_style = 1;
638
639   opt.homedir = default_homedir ();
640
641   /* Record some of the original environment strings. */
642   {
643     const char *s;
644     int idx;
645     static const char *names[] =
646       { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
647
648     err = 0;
649     opt.startup_env = session_env_new ();
650     if (!opt.startup_env)
651       err = gpg_error_from_syserror ();
652     for (idx=0; !err && names[idx]; idx++)
653       {
654         s = getenv (names[idx]);
655         if (s)
656           err = session_env_setenv (opt.startup_env, names[idx], s);
657       }
658     if (!err)
659       {
660         s = ttyname (0);
661         if (s)
662           err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
663       }
664     if (err)
665       log_fatal ("error recording startup environment: %s\n",
666                  gpg_strerror (err));
667
668     /* Fixme: Better use the locale function here.  */
669     opt.startup_lc_ctype = getenv ("LC_CTYPE");
670     if (opt.startup_lc_ctype)
671       opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
672     opt.startup_lc_messages = getenv ("LC_MESSAGES");
673     if (opt.startup_lc_messages)
674       opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
675   }
676
677   /* Check whether we have a config file on the commandline */
678   orig_argc = argc;
679   orig_argv = argv;
680   pargs.argc = &argc;
681   pargs.argv = &argv;
682   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
683   while (arg_parse( &pargs, opts))
684     {
685       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
686         parse_debug++;
687       else if (pargs.r_opt == oOptions)
688         { /* yes there is one, so we do not try the default one, but
689              read the option file when it is encountered at the
690              commandline */
691           default_config = 0;
692         }
693         else if (pargs.r_opt == oNoOptions)
694           default_config = 0; /* --no-options */
695         else if (pargs.r_opt == oHomedir)
696           opt.homedir = pargs.r.ret_str;
697     }
698
699   /* Initialize the secure memory. */
700   gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
701   maybe_setuid = 0;
702
703   /*
704      Now we are now working under our real uid
705   */
706
707   if (default_config)
708     configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
709
710   argc = orig_argc;
711   argv = orig_argv;
712   pargs.argc = &argc;
713   pargs.argv = &argv;
714   pargs.flags=  1;  /* do not remove the args */
715  next_pass:
716   if (configname)
717     {
718       configlineno = 0;
719       configfp = fopen (configname, "r");
720       if (!configfp)
721         {
722           if (default_config)
723             {
724               if( parse_debug )
725                 log_info (_("NOTE: no default option file `%s'\n"),
726                           configname );
727               /* Save the default conf file name so that
728                  reread_configuration is able to test whether the
729                  config file has been created in the meantime.  */
730               xfree (config_filename);
731               config_filename = configname;
732               configname = NULL;
733             }
734           else
735             {
736               log_error (_("option file `%s': %s\n"),
737                          configname, strerror(errno) );
738               exit(2);
739             }
740           xfree (configname);
741           configname = NULL;
742         }
743       if (parse_debug && configname )
744         log_info (_("reading options from `%s'\n"), configname );
745       default_config = 0;
746     }
747
748   while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
749     {
750       if (parse_rereadable_options (&pargs, 0))
751         continue; /* Already handled */
752       switch (pargs.r_opt)
753         {
754         case aGPGConfList: gpgconf_list = 1; break;
755         case aGPGConfTest: gpgconf_list = 2; break;
756         case aUseStandardSocketP: gpgconf_list = 3; break;
757         case oBatch: opt.batch=1; break;
758
759         case oDebugWait: debug_wait = pargs.r.ret_int; break;
760
761         case oOptions:
762           /* config files may not be nested (silently ignore them) */
763           if (!configfp)
764             {
765                 xfree(configname);
766                 configname = xstrdup(pargs.r.ret_str);
767                 goto next_pass;
768             }
769           break;
770         case oNoGreeting: nogreeting = 1; break;
771         case oNoVerbose: opt.verbose = 0; break;
772         case oNoOptions: break; /* no-options */
773         case oHomedir: opt.homedir = pargs.r.ret_str; break;
774         case oNoDetach: nodetach = 1; break;
775         case oLogFile: logfile = pargs.r.ret_str; break;
776         case oCsh: csh_style = 1; break;
777         case oSh: csh_style = 0; break;
778         case oServer: pipe_server = 1; break;
779         case oDaemon: is_daemon = 1; break;
780
781         case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
782         case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
783         case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
784         case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
785         case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
786         case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
787           break;
788
789         case oUseStandardSocket:   opt.use_standard_socket = 1; break;
790         case oNoUseStandardSocket: opt.use_standard_socket = 0; break;
791
792         case oFakedSystemTime:
793           {
794             time_t faked_time = isotime2epoch (pargs.r.ret_str);
795             if (faked_time == (time_t)(-1))
796               faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
797             gnupg_set_time (faked_time, 0);
798           }
799           break;
800
801         case oKeepTTY: opt.keep_tty = 1; break;
802         case oKeepDISPLAY: opt.keep_display = 1; break;
803
804         case oSSHSupport:  opt.ssh_support = 1; break;
805         case oWriteEnvFile:
806           if (pargs.r_type)
807             env_file_name = pargs.r.ret_str;
808           else
809             env_file_name = make_filename ("~/.gpg-agent-info", NULL);
810           break;
811
812         default : pargs.err = configfp? 1:2; break;
813         }
814     }
815   if (configfp)
816     {
817       fclose( configfp );
818       configfp = NULL;
819       /* Keep a copy of the name so that it can be read on SIGHUP. */
820       if (config_filename != configname)
821         {
822           xfree (config_filename);
823           config_filename = configname;
824         }
825       configname = NULL;
826       goto next_pass;
827     }
828
829   xfree (configname);
830   configname = NULL;
831   if (log_get_errorcount(0))
832     exit(2);
833   if (nogreeting )
834     greeting = 0;
835
836   if (greeting)
837     {
838       fprintf (stderr, "%s %s; %s\n",
839                  strusage(11), strusage(13), strusage(14) );
840       fprintf (stderr, "%s\n", strusage(15) );
841     }
842 #ifdef IS_DEVELOPMENT_VERSION
843   /* We don't want to print it here because gpg-agent is useful of its
844      own and quite matured.  */
845   /*log_info ("NOTE: this is a development version!\n");*/
846 #endif
847
848   set_debug ();
849
850   if (atexit (cleanup))
851     {
852       log_error ("atexit failed\n");
853       cleanup ();
854       exit (1);
855     }
856
857   initialize_module_call_pinentry ();
858   initialize_module_call_scd ();
859   initialize_module_trustlist ();
860
861   /* Try to create missing directories. */
862   create_directories ();
863
864   if (debug_wait && pipe_server)
865     {
866       log_debug ("waiting for debugger - my pid is %u .....\n",
867                  (unsigned int)getpid());
868       gnupg_sleep (debug_wait);
869       log_debug ("... okay\n");
870     }
871
872   if (gpgconf_list == 3)
873     agent_exit (!opt.use_standard_socket);
874   if (gpgconf_list == 2)
875     agent_exit (0);
876   if (gpgconf_list)
877     {
878       char *filename;
879       char *filename_esc;
880
881       /* List options and default values in the GPG Conf format.  */
882       filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
883       filename_esc = percent_escape (filename, NULL);
884
885       printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
886               GC_OPT_FLAG_DEFAULT, filename_esc);
887       xfree (filename);
888       xfree (filename_esc);
889
890       printf ("verbose:%lu:\n"
891               "quiet:%lu:\n"
892               "debug-level:%lu:\"none:\n"
893               "log-file:%lu:\n",
894               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
895               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
896               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
897               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
898       printf ("default-cache-ttl:%lu:%d:\n",
899               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
900       printf ("default-cache-ttl-ssh:%lu:%d:\n",
901               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
902       printf ("max-cache-ttl:%lu:%d:\n",
903               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
904       printf ("max-cache-ttl-ssh:%lu:%d:\n",
905               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
906       printf ("enforce-passphrase-constraints:%lu:\n",
907               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
908       printf ("min-passphrase-len:%lu:%d:\n",
909               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
910       printf ("min-passphrase-nonalpha:%lu:%d:\n",
911               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
912               MIN_PASSPHRASE_NONALPHA);
913       printf ("check-passphrase-pattern:%lu:\n",
914               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
915       printf ("max-passphrase-days:%lu:%d:\n",
916               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
917               MAX_PASSPHRASE_DAYS);
918       printf ("enable-passphrase-history:%lu:\n",
919               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
920       printf ("no-grab:%lu:\n",
921               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
922       printf ("ignore-cache-for-signing:%lu:\n",
923               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
924       printf ("allow-mark-trusted:%lu:\n",
925               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
926       printf ("disable-scdaemon:%lu:\n",
927               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
928
929       agent_exit (0);
930     }
931
932   /* If this has been called without any options, we merely check
933      whether an agent is already running.  We do this here so that we
934      don't clobber a logfile but print it directly to stderr. */
935   if (!pipe_server && !is_daemon)
936     {
937       log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
938       check_for_running_agent (0, 0);
939       agent_exit (0);
940     }
941
942 #ifdef ENABLE_NLS
943   /* gpg-agent usually does not output any messages because it runs in
944      the background.  For log files it is acceptable to have messages
945      always encoded in utf-8.  We switch here to utf-8, so that
946      commands like --help still give native messages.  It is far
947      easier to switch only once instead of for every message and it
948      actually helps when more then one thread is active (avoids an
949      extra copy step). */
950     bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
951 #endif
952
953   /* Now start with logging to a file if this is desired. */
954   if (logfile)
955     {
956       log_set_file (logfile);
957       log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
958                              |JNLIB_LOG_WITH_TIME
959                              |JNLIB_LOG_WITH_PID));
960       current_logfile = xstrdup (logfile);
961     }
962   if (DBG_ASSUAN)
963     assuan_set_assuan_log_stream (log_get_stream ());
964
965   /* Make sure that we have a default ttyname. */
966   if (!default_ttyname && ttyname (1))
967     default_ttyname = xstrdup (ttyname (1));
968   if (!default_ttytype && getenv ("TERM"))
969     default_ttytype = xstrdup (getenv ("TERM"));
970
971
972   if (pipe_server)
973     {
974       /* This is the simple pipe based server */
975       ctrl_t ctrl;
976
977       ctrl = xtrycalloc (1, sizeof *ctrl);
978       if (!ctrl)
979         {
980           log_error ("error allocating connection control data: %s\n",
981                      strerror (errno) );
982           agent_exit (1);
983         }
984       ctrl->session_env = session_env_new ();
985       if (!ctrl->session_env)
986         {
987           log_error ("error allocating session environment block: %s\n",
988                      strerror (errno) );
989           xfree (ctrl);
990           agent_exit (1);
991         }
992       agent_init_default_ctrl (ctrl);
993       start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
994       agent_deinit_default_ctrl (ctrl);
995       xfree (ctrl);
996     }
997   else if (!is_daemon)
998     ; /* NOTREACHED */
999   else
1000     { /* Regular server mode */
1001       gnupg_fd_t fd;
1002       gnupg_fd_t fd_ssh;
1003       pid_t pid;
1004
1005       /* Remove the DISPLAY variable so that a pinentry does not
1006          default to a specific display.  There is still a default
1007          display when gpg-agent was started using --display or a
1008          client requested this using an OPTION command.  Note, that we
1009          don't do this when running in reverse daemon mode (i.e. when
1010          exec the program given as arguments). */
1011 #ifndef HAVE_W32_SYSTEM
1012       if (!opt.keep_display && !argc)
1013         unsetenv ("DISPLAY");
1014 #endif
1015
1016
1017       /* Create the sockets.  */
1018       socket_name = create_socket_name
1019         ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
1020       if (opt.ssh_support)
1021         socket_name_ssh = create_socket_name
1022           ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
1023
1024       fd = create_server_socket (socket_name, 0, &socket_nonce);
1025       if (opt.ssh_support)
1026         fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
1027       else
1028         fd_ssh = GNUPG_INVALID_FD;
1029
1030       /* If we are going to exec a program in the parent, we record
1031          the PID, so that the child may check whether the program is
1032          still alive. */
1033       if (argc)
1034         parent_pid = getpid ();
1035
1036       fflush (NULL);
1037 #ifdef HAVE_W32_SYSTEM
1038       pid = getpid ();
1039       printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
1040 #else /*!HAVE_W32_SYSTEM*/
1041       pid = fork ();
1042       if (pid == (pid_t)-1)
1043         {
1044           log_fatal ("fork failed: %s\n", strerror (errno) );
1045           exit (1);
1046         }
1047       else if (pid)
1048         { /* We are the parent */
1049           char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
1050
1051           /* Close the socket FD. */
1052           close (fd);
1053
1054           /* Note that we used a standard fork so that Pth runs in
1055              both the parent and the child.  The pth_fork would
1056              terminate Pth in the child but that is not the way we
1057              want it.  Thus we use a plain fork and terminate Pth here
1058              in the parent.  The pth_kill may or may not work reliable
1059              but it should not harm to call it.  Because Pth fiddles
1060              with the signal mask the signal mask might not be correct
1061              right now and thus we restore it.  That is not strictly
1062              necessary but some programs falsely assume a cleared
1063              signal mask.  es_pth_kill is a wrapper around pth_kill to
1064              take care not to use any Pth functions in the estream
1065              code after Pth has been killed.  */
1066           if ( !es_pth_kill () )
1067             log_error ("pth_kill failed in forked process\n");
1068
1069 #ifdef HAVE_SIGPROCMASK
1070           if (startup_signal_mask_valid)
1071             {
1072               if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1073                 log_error ("error restoring signal mask: %s\n",
1074                            strerror (errno));
1075             }
1076           else
1077             log_info ("no saved signal mask\n");
1078 #endif /*HAVE_SIGPROCMASK*/
1079
1080           /* Create the info string: <name>:<pid>:<protocol_version> */
1081           if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1082                         socket_name, (ulong)pid ) < 0)
1083             {
1084               log_error ("out of core\n");
1085               kill (pid, SIGTERM);
1086               exit (1);
1087             }
1088           if (opt.ssh_support)
1089             {
1090               if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1091                             socket_name_ssh) < 0)
1092                 {
1093                   log_error ("out of core\n");
1094                   kill (pid, SIGTERM);
1095                   exit (1);
1096                 }
1097               if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1098                             pid) < 0)
1099                 {
1100                   log_error ("out of core\n");
1101                   kill (pid, SIGTERM);
1102                   exit (1);
1103                 }
1104             }
1105
1106           *socket_name = 0; /* Don't let cleanup() remove the socket -
1107                                the child should do this from now on */
1108           if (opt.ssh_support)
1109             *socket_name_ssh = 0;
1110
1111           if (env_file_name)
1112             {
1113               FILE *fp;
1114
1115               fp = fopen (env_file_name, "w");
1116               if (!fp)
1117                 log_error (_("error creating `%s': %s\n"),
1118                              env_file_name, strerror (errno));
1119               else
1120                 {
1121                   fputs (infostr, fp);
1122                   putc ('\n', fp);
1123                   if (opt.ssh_support)
1124                     {
1125                       fputs (infostr_ssh_sock, fp);
1126                       putc ('\n', fp);
1127                       fputs (infostr_ssh_pid, fp);
1128                       putc ('\n', fp);
1129                     }
1130                   fclose (fp);
1131                 }
1132             }
1133
1134
1135           if (argc)
1136             { /* Run the program given on the commandline.  */
1137               if (putenv (infostr))
1138                 {
1139                   log_error ("failed to set environment: %s\n",
1140                              strerror (errno) );
1141                   kill (pid, SIGTERM );
1142                   exit (1);
1143                 }
1144               if (opt.ssh_support && putenv (infostr_ssh_sock))
1145                 {
1146                   log_error ("failed to set environment: %s\n",
1147                              strerror (errno) );
1148                   kill (pid, SIGTERM );
1149                   exit (1);
1150                 }
1151               if (opt.ssh_support && putenv (infostr_ssh_pid))
1152                 {
1153                   log_error ("failed to set environment: %s\n",
1154                              strerror (errno) );
1155                   kill (pid, SIGTERM );
1156                   exit (1);
1157                 }
1158
1159               /* Close all the file descriptors except the standard
1160                  ones and those open at startup.  We explicitly don't
1161                  close 0,1,2 in case something went wrong collecting
1162                  them at startup.  */
1163               close_all_fds (3, startup_fd_list);
1164
1165               /* Run the command.  */
1166               execvp (argv[0], argv);
1167               log_error ("failed to run the command: %s\n", strerror (errno));
1168               kill (pid, SIGTERM);
1169               exit (1);
1170             }
1171           else
1172             {
1173               /* Print the environment string, so that the caller can use
1174                  shell's eval to set it */
1175               if (csh_style)
1176                 {
1177                   *strchr (infostr, '=') = ' ';
1178                   printf ("setenv %s;\n", infostr);
1179                   if (opt.ssh_support)
1180                     {
1181                       *strchr (infostr_ssh_sock, '=') = ' ';
1182                       printf ("setenv %s;\n", infostr_ssh_sock);
1183                       *strchr (infostr_ssh_pid, '=') = ' ';
1184                       printf ("setenv %s;\n", infostr_ssh_pid);
1185                     }
1186                 }
1187               else
1188                 {
1189                   printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1190                   if (opt.ssh_support)
1191                     {
1192                       printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1193                       printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1194                     }
1195                 }
1196               xfree (infostr);
1197               if (opt.ssh_support)
1198                 {
1199                   xfree (infostr_ssh_sock);
1200                   xfree (infostr_ssh_pid);
1201                 }
1202               exit (0);
1203             }
1204           /*NOTREACHED*/
1205         } /* End parent */
1206
1207       /*
1208          This is the child
1209        */
1210
1211       /* Detach from tty and put process into a new session */
1212       if (!nodetach )
1213         {
1214           int i;
1215           unsigned int oldflags;
1216
1217           /* Close stdin, stdout and stderr unless it is the log stream */
1218           for (i=0; i <= 2; i++)
1219             {
1220               if (!log_test_fd (i) && i != fd )
1221                 {
1222                   if ( ! close (i)
1223                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1224                     {
1225                       log_error ("failed to open `%s': %s\n",
1226                                  "/dev/null", strerror (errno));
1227                       cleanup ();
1228                       exit (1);
1229                     }
1230                 }
1231             }
1232           if (setsid() == -1)
1233             {
1234               log_error ("setsid() failed: %s\n", strerror(errno) );
1235               cleanup ();
1236               exit (1);
1237             }
1238
1239           log_get_prefix (&oldflags);
1240           log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1241           opt.running_detached = 1;
1242         }
1243
1244       if (chdir("/"))
1245         {
1246           log_error ("chdir to / failed: %s\n", strerror (errno));
1247           exit (1);
1248         }
1249
1250       {
1251         struct sigaction sa;
1252
1253         sa.sa_handler = SIG_IGN;
1254         sigemptyset (&sa.sa_mask);
1255         sa.sa_flags = 0;
1256         sigaction (SIGPIPE, &sa, NULL);
1257       }
1258 #endif /*!HAVE_W32_SYSTEM*/
1259
1260       log_info ("%s %s started\n", strusage(11), strusage(13) );
1261       handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1262       assuan_sock_close (fd);
1263     }
1264
1265   return 0;
1266 }
1267
1268
1269 void
1270 agent_exit (int rc)
1271 {
1272   /*FIXME: update_random_seed_file();*/
1273 #if 1
1274   /* at this time a bit annoying */
1275   if (opt.debug & DBG_MEMSTAT_VALUE)
1276     {
1277       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1278       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1279     }
1280   if (opt.debug)
1281     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1282 #endif
1283   gcry_control (GCRYCTL_TERM_SECMEM );
1284   rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1285   exit (rc);
1286 }
1287
1288
1289 static void
1290 agent_init_default_ctrl (ctrl_t ctrl)
1291 {
1292   /* Note we ignore malloc errors because we can't do much about it
1293      and the request will fail anyway shortly after this
1294      initialization. */
1295   session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1296   session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1297   session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1298   session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1299   session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1300
1301   if (ctrl->lc_ctype)
1302     xfree (ctrl->lc_ctype);
1303   ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1304
1305   if (ctrl->lc_messages)
1306     xfree (ctrl->lc_messages);
1307   ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1308                                     /**/ : NULL;
1309
1310 }
1311
1312
1313 static void
1314 agent_deinit_default_ctrl (ctrl_t ctrl)
1315 {
1316   session_env_release (ctrl->session_env);
1317
1318   if (ctrl->lc_ctype)
1319     xfree (ctrl->lc_ctype);
1320   if (ctrl->lc_messages)
1321     xfree (ctrl->lc_messages);
1322 }
1323
1324
1325 /* Reread parts of the configuration.  Note, that this function is
1326    obviously not thread-safe and should only be called from the PTH
1327    signal handler.
1328
1329    Fixme: Due to the way the argument parsing works, we create a
1330    memory leak here for all string type arguments.  There is currently
1331    no clean way to tell whether the memory for the argument has been
1332    allocated or points into the process' original arguments.  Unless
1333    we have a mechanism to tell this, we need to live on with this. */
1334 static void
1335 reread_configuration (void)
1336 {
1337   ARGPARSE_ARGS pargs;
1338   FILE *fp;
1339   unsigned int configlineno = 0;
1340   int dummy;
1341
1342   if (!config_filename)
1343     return; /* No config file. */
1344
1345   fp = fopen (config_filename, "r");
1346   if (!fp)
1347     {
1348       log_info (_("option file `%s': %s\n"),
1349                 config_filename, strerror(errno) );
1350       return;
1351     }
1352
1353   parse_rereadable_options (NULL, 1); /* Start from the default values. */
1354
1355   memset (&pargs, 0, sizeof pargs);
1356   dummy = 0;
1357   pargs.argc = &dummy;
1358   pargs.flags = 1;  /* do not remove the args */
1359   while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1360     {
1361       if (pargs.r_opt < -1)
1362         pargs.err = 1; /* Print a warning. */
1363       else /* Try to parse this option - ignore unchangeable ones. */
1364         parse_rereadable_options (&pargs, 1);
1365     }
1366   fclose (fp);
1367   set_debug ();
1368 }
1369
1370
1371 /* Return the file name of the socket we are using for native
1372    requests.  */
1373 const char *
1374 get_agent_socket_name (void)
1375 {
1376   const char *s = socket_name;
1377
1378   return (s && *s)? s : NULL;
1379 }
1380
1381 /* Return the file name of the socket we are using for SSH
1382    requests.  */
1383 const char *
1384 get_agent_ssh_socket_name (void)
1385 {
1386   const char *s = socket_name_ssh;
1387
1388   return (s && *s)? s : NULL;
1389 }
1390
1391
1392 /* Under W32, this function returns the handle of the scdaemon
1393    notification event.  Calling it the first time creates that
1394    event.  */
1395 #ifdef HAVE_W32_SYSTEM
1396 void *
1397 get_agent_scd_notify_event (void)
1398 {
1399   static HANDLE the_event;
1400
1401   if (!the_event)
1402     {
1403       HANDLE h, h2;
1404       SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1405
1406       /* We need to use manual reset evet object due to the way our
1407          w32-pth wait function works: If we would use an automatic
1408          reset event we are not able to figure out which handle has
1409          been signaled because at the time we single out the signaled
1410          handles using WFSO the event has already been reset due to
1411          the WFMO.  */
1412       h = CreateEvent (&sa, TRUE, FALSE, NULL);
1413       if (!h)
1414         log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1415       else if (!DuplicateHandle (GetCurrentProcess(), h,
1416                                  GetCurrentProcess(), &h2,
1417                                  EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1418         {
1419           log_error ("setting syncronize for scd notify event failed: %s\n",
1420                      w32_strerror (-1) );
1421           CloseHandle (h);
1422         }
1423       else
1424         {
1425           CloseHandle (h);
1426           the_event = h2;
1427         }
1428     }
1429
1430   log_debug  ("returning notify handle %p\n", the_event);
1431   return the_event;
1432 }
1433 #endif /*HAVE_W32_SYSTEM*/
1434
1435
1436
1437 /* Create a name for the socket.  With USE_STANDARD_SOCKET given as
1438    true using STANDARD_NAME in the home directory or if given as
1439    false from the mkdir type name TEMPLATE.  In the latter case a
1440    unique name in a unique new directory will be created.  In both
1441    cases check for valid characters as well as against a maximum
1442    allowed length for a unix domain socket is done.  The function
1443    terminates the process in case of an error.  Returns: Pointer to an
1444    allocated string with the absolute name of the socket used.  */
1445 static char *
1446 create_socket_name (char *standard_name, char *template)
1447 {
1448   char *name, *p;
1449
1450   if (opt.use_standard_socket)
1451     name = make_filename (opt.homedir, standard_name, NULL);
1452   else
1453     {
1454       name = xstrdup (template);
1455       p = strrchr (name, '/');
1456       if (!p)
1457         BUG ();
1458       *p = 0;
1459       if (!mkdtemp (name))
1460         {
1461           log_error (_("can't create directory `%s': %s\n"),
1462                      name, strerror (errno));
1463           agent_exit (2);
1464         }
1465       *p = '/';
1466     }
1467
1468   if (strchr (name, PATHSEP_C))
1469     {
1470       log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1471       agent_exit (2);
1472     }
1473   if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1474     {
1475       log_error (_("name of socket too long\n"));
1476       agent_exit (2);
1477     }
1478   return name;
1479 }
1480
1481
1482
1483 /* Create a Unix domain socket with NAME.  Returns the file descriptor
1484    or terminates the process in case of an error.  Not that this
1485    function needs to be used for the regular socket first and only
1486    then for the ssh socket.  */
1487 static gnupg_fd_t
1488 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1489 {
1490   struct sockaddr_un *serv_addr;
1491   socklen_t len;
1492   gnupg_fd_t fd;
1493   int rc;
1494
1495   fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1496   if (fd == ASSUAN_INVALID_FD)
1497     {
1498       log_error (_("can't create socket: %s\n"), strerror (errno));
1499       agent_exit (2);
1500     }
1501
1502   serv_addr = xmalloc (sizeof (*serv_addr));
1503   memset (serv_addr, 0, sizeof *serv_addr);
1504   serv_addr->sun_family = AF_UNIX;
1505   if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1506     {
1507       log_error (_("socket name `%s' is too long\n"), name);
1508       agent_exit (2);
1509     }
1510   strcpy (serv_addr->sun_path, name);
1511   len = SUN_LEN (serv_addr);
1512   rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1513   if (opt.use_standard_socket && rc == -1 && errno == EADDRINUSE)
1514     {
1515       /* Check whether a gpg-agent is already running on the standard
1516          socket.  We do this test only if this is not the ssh socket.
1517          For ssh we assume that a test for gpg-agent has already been
1518          done and reuse the requested ssh socket.  Testing the
1519          ssh-socket is not possible because at this point, though we
1520          know the new Assuan socket, the Assuan server and thus the
1521          ssh-agent server is not yet operational.  This would lead to
1522          a hang.  */
1523       if (!is_ssh && !check_for_running_agent (1, 1))
1524         {
1525           log_error (_("a gpg-agent is already running - "
1526                        "not starting a new one\n"));
1527           *name = 0; /* Inhibit removal of the socket by cleanup(). */
1528           assuan_sock_close (fd);
1529           agent_exit (2);
1530         }
1531       remove (name);
1532       rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1533     }
1534   if (rc != -1
1535       && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1536     log_error (_("error getting nonce for the socket\n"));
1537   if (rc == -1)
1538     {
1539       /* We use gpg_strerror here because it allows us to get strings
1540          for some W32 socket error codes.  */
1541       log_error (_("error binding socket to `%s': %s\n"),
1542                  serv_addr->sun_path,
1543                  gpg_strerror (gpg_error_from_errno (errno)));
1544
1545       assuan_sock_close (fd);
1546       if (opt.use_standard_socket)
1547         *name = 0; /* Inhibit removal of the socket by cleanup(). */
1548       agent_exit (2);
1549     }
1550
1551   if (listen (FD2INT(fd), 5 ) == -1)
1552     {
1553       log_error (_("listen() failed: %s\n"), strerror (errno));
1554       assuan_sock_close (fd);
1555       agent_exit (2);
1556     }
1557
1558   if (opt.verbose)
1559     log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1560
1561   return fd;
1562 }
1563
1564
1565 /* Check that the directory for storing the private keys exists and
1566    create it if not.  This function won't fail as it is only a
1567    convenience function and not strictly necessary.  */
1568 static void
1569 create_private_keys_directory (const char *home)
1570 {
1571   char *fname;
1572   struct stat statbuf;
1573
1574   fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1575   if (stat (fname, &statbuf) && errno == ENOENT)
1576     {
1577 #ifdef HAVE_W32_SYSTEM  /*FIXME: Setup proper permissions.  */
1578       if (!CreateDirectory (fname, NULL))
1579         log_error (_("can't create directory `%s': %s\n"),
1580                    fname, w32_strerror (-1) );
1581 #else
1582       if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1583         log_error (_("can't create directory `%s': %s\n"),
1584                    fname, strerror (errno) );
1585 #endif
1586       else if (!opt.quiet)
1587         log_info (_("directory `%s' created\n"), fname);
1588     }
1589   xfree (fname);
1590 }
1591
1592 /* Create the directory only if the supplied directory name is the
1593    same as the default one.  This way we avoid to create arbitrary
1594    directories when a non-default home directory is used.  To cope
1595    with HOME, we compare only the suffix if we see that the default
1596    homedir does start with a tilde.  We don't stop here in case of
1597    problems because other functions will throw an error anyway.*/
1598 static void
1599 create_directories (void)
1600 {
1601   struct stat statbuf;
1602   const char *defhome = standard_homedir ();
1603   char *home;
1604
1605   home = make_filename (opt.homedir, NULL);
1606   if ( stat (home, &statbuf) )
1607     {
1608       if (errno == ENOENT)
1609         {
1610           if (
1611 #ifdef HAVE_W32_SYSTEM
1612               ( !compare_filenames (home, defhome) )
1613 #else
1614               (*defhome == '~'
1615                 && (strlen (home) >= strlen (defhome+1)
1616                     && !strcmp (home + strlen(home)
1617                                 - strlen (defhome+1), defhome+1)))
1618                || (*defhome != '~' && !strcmp (home, defhome) )
1619 #endif
1620                )
1621             {
1622 #ifdef HAVE_W32_SYSTEM
1623               if (!CreateDirectory (home, NULL))
1624                 log_error (_("can't create directory `%s': %s\n"),
1625                            home, w32_strerror (-1) );
1626 #else
1627               if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1628                 log_error (_("can't create directory `%s': %s\n"),
1629                            home, strerror (errno) );
1630 #endif
1631               else
1632                 {
1633                   if (!opt.quiet)
1634                     log_info (_("directory `%s' created\n"), home);
1635                   create_private_keys_directory (home);
1636                 }
1637             }
1638         }
1639       else
1640         log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1641     }
1642   else if ( !S_ISDIR(statbuf.st_mode))
1643     {
1644       log_error (_("can't use `%s' as home directory\n"), home);
1645     }
1646   else /* exists and is a directory. */
1647     {
1648       create_private_keys_directory (home);
1649     }
1650   xfree (home);
1651 }
1652
1653
1654
1655 /* This is the worker for the ticker.  It is called every few seconds
1656    and may only do fast operations. */
1657 static void
1658 handle_tick (void)
1659 {
1660   static time_t last_minute;
1661
1662   if (!last_minute)
1663     last_minute = time (NULL);
1664
1665   /* Check whether the scdaemon has died and cleanup in this case. */
1666   agent_scd_check_aliveness ();
1667
1668   /* If we are running as a child of another process, check whether
1669      the parent is still alive and shutdown if not. */
1670 #ifndef HAVE_W32_SYSTEM
1671   if (parent_pid != (pid_t)(-1))
1672     {
1673       if (kill (parent_pid, 0))
1674         {
1675           shutdown_pending = 2;
1676           if (!opt.quiet)
1677             {
1678               log_info ("parent process died - shutting down\n");
1679               log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1680             }
1681           cleanup ();
1682           agent_exit (0);
1683         }
1684     }
1685 #endif /*HAVE_W32_SYSTEM*/
1686
1687   /* Code to be run every minute.  */
1688   if (last_minute + 60 <= time (NULL))
1689     {
1690       check_own_socket ();
1691       last_minute = time (NULL);
1692     }
1693
1694 }
1695
1696
1697 /* A global function which allows us to call the reload stuff from
1698    other places too.  This is only used when build for W32.  */
1699 void
1700 agent_sighup_action (void)
1701 {
1702   log_info ("SIGHUP received - "
1703             "re-reading configuration and flushing cache\n");
1704   agent_flush_cache ();
1705   reread_configuration ();
1706   agent_reload_trustlist ();
1707 }
1708
1709
1710 static void
1711 agent_sigusr2_action (void)
1712 {
1713   if (opt.verbose)
1714     log_info ("SIGUSR2 received - updating card event counter\n");
1715   /* Nothing to check right now.  We only increment a counter.  */
1716   bump_card_eventcounter ();
1717 }
1718
1719
1720 static void
1721 handle_signal (int signo)
1722 {
1723   switch (signo)
1724     {
1725 #ifndef HAVE_W32_SYSTEM
1726     case SIGHUP:
1727       agent_sighup_action ();
1728       break;
1729
1730     case SIGUSR1:
1731       log_info ("SIGUSR1 received - printing internal information:\n");
1732       pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1733       agent_query_dump_state ();
1734       agent_scd_dump_state ();
1735       break;
1736
1737     case SIGUSR2:
1738       agent_sigusr2_action ();
1739       break;
1740
1741     case SIGTERM:
1742       if (!shutdown_pending)
1743         log_info ("SIGTERM received - shutting down ...\n");
1744       else
1745         log_info ("SIGTERM received - still %ld running threads\n",
1746                   pth_ctrl( PTH_CTRL_GETTHREADS ));
1747       shutdown_pending++;
1748       if (shutdown_pending > 2)
1749         {
1750           log_info ("shutdown forced\n");
1751           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1752           cleanup ();
1753           agent_exit (0);
1754         }
1755       break;
1756
1757     case SIGINT:
1758       log_info ("SIGINT received - immediate shutdown\n");
1759       log_info( "%s %s stopped\n", strusage(11), strusage(13));
1760       cleanup ();
1761       agent_exit (0);
1762       break;
1763 #endif
1764     default:
1765       log_info ("signal %d received - no action defined\n", signo);
1766     }
1767 }
1768
1769
1770 /* Check the nonce on a new connection.  This is a NOP unless we we
1771    are using our Unix domain socket emulation under Windows.  */
1772 static int
1773 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1774 {
1775   if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1776     {
1777       log_info (_("error reading nonce on fd %d: %s\n"),
1778                 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1779       assuan_sock_close (ctrl->thread_startup.fd);
1780       xfree (ctrl);
1781       return -1;
1782     }
1783   else
1784     return 0;
1785 }
1786
1787
1788 /* This is the standard connection thread's main function.  */
1789 static void *
1790 start_connection_thread (void *arg)
1791 {
1792   ctrl_t ctrl = arg;
1793
1794   if (check_nonce (ctrl, &socket_nonce))
1795     return NULL;
1796
1797   agent_init_default_ctrl (ctrl);
1798   if (opt.verbose)
1799     log_info (_("handler 0x%lx for fd %d started\n"),
1800               pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1801
1802   start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1803   if (opt.verbose)
1804     log_info (_("handler 0x%lx for fd %d terminated\n"),
1805               pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1806
1807   agent_deinit_default_ctrl (ctrl);
1808   xfree (ctrl);
1809   return NULL;
1810 }
1811
1812
1813 /* This is the ssh connection thread's main function.  */
1814 static void *
1815 start_connection_thread_ssh (void *arg)
1816 {
1817   ctrl_t ctrl = arg;
1818
1819   if (check_nonce (ctrl, &socket_nonce_ssh))
1820     return NULL;
1821
1822   agent_init_default_ctrl (ctrl);
1823   if (opt.verbose)
1824     log_info (_("ssh handler 0x%lx for fd %d started\n"),
1825               pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1826
1827   start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1828   if (opt.verbose)
1829     log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1830               pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1831
1832   agent_deinit_default_ctrl (ctrl);
1833   xfree (ctrl);
1834   return NULL;
1835 }
1836
1837
1838 /* Connection handler loop.  Wait for connection requests and spawn a
1839    thread after accepting a connection.  */
1840 static void
1841 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1842 {
1843   pth_attr_t tattr;
1844   pth_event_t ev, time_ev;
1845   sigset_t sigs;
1846   int signo;
1847   struct sockaddr_un paddr;
1848   socklen_t plen;
1849   fd_set fdset, read_fdset;
1850   int ret;
1851   gnupg_fd_t fd;
1852   int nfd;
1853
1854   tattr = pth_attr_new();
1855   pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1856   pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1857
1858 #ifndef HAVE_W32_SYSTEM /* fixme */
1859   /* Make sure that the signals we are going to handle are not blocked
1860      and create an event object for them.  We also set the default
1861      action to ignore because we use an Pth event to get notified
1862      about signals.  This avoids that the default action is taken in
1863      case soemthing goes wrong within Pth.  The problem might also be
1864      a Pth bug.  */
1865   sigemptyset (&sigs );
1866   {
1867     static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1868     struct sigaction sa;
1869     int i;
1870
1871     for (i=0; i < DIM (mysigs); i++)
1872       {
1873         sigemptyset (&sa.sa_mask);
1874         sa.sa_handler = SIG_IGN;
1875         sa.sa_flags = 0;
1876         sigaction (mysigs[i], &sa, NULL);
1877
1878         sigaddset (&sigs, mysigs[i]);
1879       }
1880   }
1881
1882   pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1883   ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1884 #else
1885 # ifdef PTH_EVENT_HANDLE
1886   sigs = 0;
1887   ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1888   signo = 0;
1889 # else
1890   /* Use a dummy event. */
1891   sigs = 0;
1892   ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1893 # endif
1894 #endif
1895   time_ev = NULL;
1896
1897   /* Set a flag to tell call-scd.c that it may enable event
1898      notifications.  */
1899   opt.sigusr2_enabled = 1;
1900
1901   FD_ZERO (&fdset);
1902   FD_SET (FD2INT (listen_fd), &fdset);
1903   nfd = FD2INT (listen_fd);
1904   if (listen_fd_ssh != GNUPG_INVALID_FD)
1905     {
1906       FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1907       if (FD2INT (listen_fd_ssh) > nfd)
1908         nfd = FD2INT (listen_fd_ssh);
1909     }
1910
1911   for (;;)
1912     {
1913       /* Make sure that our signals are not blocked.  */
1914       pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1915
1916       /* Shutdown test.  */
1917       if (shutdown_pending)
1918         {
1919           if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1920             break; /* ready */
1921
1922           /* Do not accept new connections but keep on running the
1923              loop to cope with the timer events.  */
1924           FD_ZERO (&fdset);
1925         }
1926
1927       /* Create a timeout event if needed.  To help with power saving
1928          we syncronize the ticks to the next full second.  */
1929       if (!time_ev)
1930         {
1931           pth_time_t nexttick;
1932
1933           nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1934           if (nexttick.tv_usec > 10)  /* Use a 10 usec threshhold.  */
1935             {
1936               nexttick.tv_sec++;
1937               nexttick.tv_usec = 0;
1938             }
1939           time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1940         }
1941
1942       /* POSIX says that fd_set should be implemented as a structure,
1943          thus a simple assignment is fine to copy the entire set.  */
1944       read_fdset = fdset;
1945
1946       if (time_ev)
1947         pth_event_concat (ev, time_ev, NULL);
1948       ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1949       if (time_ev)
1950         pth_event_isolate (time_ev);
1951
1952       if (ret == -1)
1953         {
1954           if (pth_event_occurred (ev)
1955               || (time_ev && pth_event_occurred (time_ev)))
1956             {
1957               if (pth_event_occurred (ev))
1958                 {
1959 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1960                   agent_sigusr2_action ();
1961 #else
1962                   handle_signal (signo);
1963 #endif
1964                 }
1965               if (time_ev && pth_event_occurred (time_ev))
1966                 {
1967                   pth_event_free (time_ev, PTH_FREE_ALL);
1968                   time_ev = NULL;
1969                   handle_tick ();
1970                 }
1971               continue;
1972             }
1973           log_error (_("pth_select failed: %s - waiting 1s\n"),
1974                      strerror (errno));
1975           pth_sleep (1);
1976           continue;
1977         }
1978
1979       if (pth_event_occurred (ev))
1980         {
1981 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1982           agent_sigusr2_action ();
1983 #else
1984           handle_signal (signo);
1985 #endif
1986         }
1987
1988       if (time_ev && pth_event_occurred (time_ev))
1989         {
1990           pth_event_free (time_ev, PTH_FREE_ALL);
1991           time_ev = NULL;
1992           handle_tick ();
1993         }
1994
1995
1996       /* We now might create new threads and because we don't want any
1997          signals (as we are handling them here) to be delivered to a
1998          new thread.  Thus we need to block those signals. */
1999       pth_sigmask (SIG_BLOCK, &sigs, NULL);
2000
2001       if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
2002         {
2003           ctrl_t ctrl;
2004
2005           plen = sizeof paddr;
2006           fd = INT2FD (pth_accept (FD2INT(listen_fd),
2007                                    (struct sockaddr *)&paddr, &plen));
2008           if (fd == GNUPG_INVALID_FD)
2009             {
2010               log_error ("accept failed: %s\n", strerror (errno));
2011             }
2012           else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2013             {
2014               log_error ("error allocating connection control data: %s\n",
2015                          strerror (errno) );
2016               assuan_sock_close (fd);
2017             }
2018           else if ( !(ctrl->session_env = session_env_new ()) )
2019             {
2020               log_error ("error allocating session environment block: %s\n",
2021                          strerror (errno) );
2022               xfree (ctrl);
2023               assuan_sock_close (fd);
2024             }
2025           else
2026             {
2027               char threadname[50];
2028
2029               snprintf (threadname, sizeof threadname-1,
2030                         "conn fd=%d (gpg)", FD2INT(fd));
2031               threadname[sizeof threadname -1] = 0;
2032               pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2033               ctrl->thread_startup.fd = fd;
2034               if (!pth_spawn (tattr, start_connection_thread, ctrl))
2035                 {
2036                   log_error ("error spawning connection handler: %s\n",
2037                              strerror (errno) );
2038                   assuan_sock_close (fd);
2039                   xfree (ctrl);
2040                 }
2041             }
2042           fd = GNUPG_INVALID_FD;
2043         }
2044
2045       if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
2046           && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
2047         {
2048           ctrl_t ctrl;
2049
2050           plen = sizeof paddr;
2051           fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
2052                                   (struct sockaddr *)&paddr, &plen));
2053           if (fd == GNUPG_INVALID_FD)
2054             {
2055               log_error ("accept failed for ssh: %s\n", strerror (errno));
2056             }
2057           else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2058             {
2059               log_error ("error allocating connection control data: %s\n",
2060                          strerror (errno) );
2061               assuan_sock_close (fd);
2062             }
2063           else if ( !(ctrl->session_env = session_env_new ()) )
2064             {
2065               log_error ("error allocating session environment block: %s\n",
2066                          strerror (errno) );
2067               xfree (ctrl);
2068               assuan_sock_close (fd);
2069             }
2070           else
2071             {
2072               char threadname[50];
2073
2074               agent_init_default_ctrl (ctrl);
2075               snprintf (threadname, sizeof threadname-1,
2076                         "conn fd=%d (ssh)", FD2INT(fd));
2077               threadname[sizeof threadname -1] = 0;
2078               pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2079               ctrl->thread_startup.fd = fd;
2080               if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2081                 {
2082                   log_error ("error spawning ssh connection handler: %s\n",
2083                              strerror (errno) );
2084                   assuan_sock_close (fd);
2085                   xfree (ctrl);
2086                 }
2087             }
2088           fd = GNUPG_INVALID_FD;
2089         }
2090     }
2091
2092   pth_event_free (ev, PTH_FREE_ALL);
2093   if (time_ev)
2094     pth_event_free (time_ev, PTH_FREE_ALL);
2095   cleanup ();
2096   log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2097 }
2098
2099
2100
2101 /* Helper for check_own_socket.  */
2102 static gpg_error_t
2103 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2104 {
2105   membuf_t *mb = opaque;
2106   put_membuf (mb, buffer, length);
2107   return 0;
2108 }
2109
2110
2111 /* The thread running the actual check.  We need to run this in a
2112    separate thread so that check_own_thread can be called from the
2113    timer tick.  */
2114 static void *
2115 check_own_socket_thread (void *arg)
2116 {
2117   int rc;
2118   char *sockname = arg;
2119   assuan_context_t ctx = NULL;
2120   membuf_t mb;
2121   char *buffer;
2122
2123   check_own_socket_running++;
2124
2125   rc = assuan_new (&ctx);
2126   if (rc)
2127     {
2128       log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2129       goto leave;
2130     }
2131
2132   rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2133   if (rc)
2134     {
2135       log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2136       goto leave;
2137     }
2138
2139   init_membuf (&mb, 100);
2140   rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2141                         NULL, NULL, NULL, NULL);
2142   put_membuf (&mb, "", 1);
2143   buffer = get_membuf (&mb, NULL);
2144   if (rc || !buffer)
2145     {
2146       log_error ("sending command \"%s\" to my own socket failed: %s\n",
2147                  "GETINFO pid", gpg_strerror (rc));
2148       rc = 1;
2149     }
2150   else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2151     {
2152       log_error ("socket is now serviced by another server\n");
2153       rc = 1;
2154     }
2155   else if (opt.verbose > 1)
2156     log_error ("socket is still served by this server\n");
2157
2158   xfree (buffer);
2159
2160  leave:
2161   xfree (sockname);
2162   if (ctx)
2163     assuan_release (ctx);
2164   if (rc)
2165     {
2166       /* We may not remove the socket as it is now in use by another
2167          server.  Setting the name to empty does this.  */
2168       if (socket_name)
2169         *socket_name = 0;
2170       if (socket_name_ssh)
2171         *socket_name_ssh = 0;
2172       shutdown_pending = 2;
2173       log_info ("this process is useless - shutting down\n");
2174     }
2175   check_own_socket_running--;
2176   return NULL;
2177 }
2178
2179
2180 /* Check whether we are still listening on our own socket.  In case
2181    another gpg-agent process started after us has taken ownership of
2182    our socket, we woul linger around without any real taks.  Thus we
2183    better check once in a while whether we are really needed.  */
2184 static void
2185 check_own_socket (void)
2186 {
2187   char *sockname;
2188   pth_attr_t tattr;
2189
2190   if (!opt.use_standard_socket)
2191     return; /* This check makes only sense in standard socket mode.  */
2192
2193   if (check_own_socket_running || shutdown_pending)
2194     return;  /* Still running or already shutting down.  */
2195
2196   sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2197   if (!sockname)
2198     return; /* Out of memory.  */
2199
2200   tattr = pth_attr_new();
2201   pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2202   pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2203   pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2204
2205   if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2206       log_error ("error spawning check_own_socket_thread: %s\n",
2207                  strerror (errno) );
2208   pth_attr_destroy (tattr);
2209 }
2210
2211
2212
2213 /* Figure out whether an agent is available and running. Prints an
2214    error if not.  If SILENT is true, no messages are printed.  Usually
2215    started with MODE 0.  Returns 0 if the agent is running. */
2216 static int
2217 check_for_running_agent (int silent, int mode)
2218 {
2219   int rc;
2220   char *infostr, *p;
2221   assuan_context_t ctx = NULL;
2222   int prot, pid;
2223
2224   if (!mode)
2225     {
2226       infostr = getenv ("GPG_AGENT_INFO");
2227       if (!infostr || !*infostr)
2228         {
2229           if (!check_for_running_agent (silent, 1))
2230             return 0; /* Okay, its running on the standard socket. */
2231           if (!silent)
2232             log_error (_("no gpg-agent running in this session\n"));
2233           return -1;
2234         }
2235
2236       infostr = xstrdup (infostr);
2237       if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2238         {
2239           xfree (infostr);
2240           if (!check_for_running_agent (silent, 1))
2241             return 0; /* Okay, its running on the standard socket. */
2242           if (!silent)
2243             log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2244           return -1;
2245         }
2246
2247       *p++ = 0;
2248       pid = atoi (p);
2249       while (*p && *p != PATHSEP_C)
2250         p++;
2251       prot = *p? atoi (p+1) : 0;
2252       if (prot != 1)
2253         {
2254           xfree (infostr);
2255           if (!silent)
2256             log_error (_("gpg-agent protocol version %d is not supported\n"),
2257                        prot);
2258           if (!check_for_running_agent (silent, 1))
2259             return 0; /* Okay, its running on the standard socket. */
2260           return -1;
2261         }
2262     }
2263   else /* MODE != 0 */
2264     {
2265       infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2266       pid = (pid_t)(-1);
2267     }
2268
2269   rc = assuan_new (&ctx);
2270   if (! rc)
2271     rc = assuan_socket_connect (ctx, infostr, pid, 0);
2272   xfree (infostr);
2273   if (rc)
2274     {
2275       if (!mode && !check_for_running_agent (silent, 1))
2276         return 0; /* Okay, its running on the standard socket. */
2277
2278       if (!mode && !silent)
2279         log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2280
2281       if (ctx)
2282         assuan_release (ctx);
2283       return -1;
2284     }
2285
2286   if (!opt.quiet && !silent)
2287     log_info ("gpg-agent running and available\n");
2288
2289   assuan_release (ctx);
2290   return 0;
2291 }