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