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