Imported Upstream version 2.1.2
[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 caller to override the pinentry")),
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 /* Fixup some options after all have been processed.  */
632 static void
633 finalize_rereadable_options (void)
634 {
635   /* It would be too surprising if the max-cache-ttl is lower than the
636      default-cache-ttl - thus we silently correct that.  */
637   if (opt.def_cache_ttl > opt.max_cache_ttl)
638     opt.max_cache_ttl = opt.def_cache_ttl;
639   if (opt.def_cache_ttl_ssh > opt.max_cache_ttl_ssh)
640     opt.max_cache_ttl_ssh = opt.def_cache_ttl_ssh;
641 }
642
643
644
645 /* The main entry point.  */
646 int
647 main (int argc, char **argv )
648 {
649   ARGPARSE_ARGS pargs;
650   int orig_argc;
651   char **orig_argv;
652   FILE *configfp = NULL;
653   char *configname = NULL;
654   const char *shell;
655   unsigned configlineno;
656   int parse_debug = 0;
657   int default_config =1;
658   int pipe_server = 0;
659   int is_daemon = 0;
660   int nodetach = 0;
661   int csh_style = 0;
662   char *logfile = NULL;
663   int debug_wait = 0;
664   int gpgconf_list = 0;
665   gpg_error_t err;
666   struct assuan_malloc_hooks malloc_hooks;
667
668   early_system_init ();
669
670   /* Before we do anything else we save the list of currently open
671      file descriptors and the signal mask.  This info is required to
672      do the exec call properly. */
673   startup_fd_list = get_all_open_fds ();
674 #ifdef HAVE_SIGPROCMASK
675   if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
676     startup_signal_mask_valid = 1;
677 #endif /*HAVE_SIGPROCMASK*/
678
679   /* Set program name etc.  */
680   set_strusage (my_strusage);
681   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
682   /* Please note that we may running SUID(ROOT), so be very CAREFUL
683      when adding any stuff between here and the call to INIT_SECMEM()
684      somewhere after the option parsing */
685   log_set_prefix (GPG_AGENT_NAME, JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
686
687   /* Make sure that our subsystems are ready.  */
688   i18n_init ();
689   init_common_subsystems (&argc, &argv);
690
691   npth_init ();
692
693   /* Check that the libraries are suitable.  Do it here because
694      the option parsing may need services of the library. */
695   if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
696     {
697       log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
698                  NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
699     }
700
701   malloc_hooks.malloc = gcry_malloc;
702   malloc_hooks.realloc = gcry_realloc;
703   malloc_hooks.free = gcry_free;
704   assuan_set_malloc_hooks (&malloc_hooks);
705   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
706   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
707   assuan_sock_init ();
708   setup_libassuan_logging (&opt.debug);
709
710   setup_libgcrypt_logging ();
711   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
712
713   disable_core_dumps ();
714
715   /* Set default options.  */
716   parse_rereadable_options (NULL, 0); /* Reset them to default values. */
717
718   shell = getenv ("SHELL");
719   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
720     csh_style = 1;
721
722   opt.homedir = default_homedir ();
723
724   /* Record some of the original environment strings. */
725   {
726     const char *s;
727     int idx;
728     static const char *names[] =
729       { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
730
731     err = 0;
732     opt.startup_env = session_env_new ();
733     if (!opt.startup_env)
734       err = gpg_error_from_syserror ();
735     for (idx=0; !err && names[idx]; idx++)
736       {
737         s = getenv (names[idx]);
738         if (s)
739           err = session_env_setenv (opt.startup_env, names[idx], s);
740       }
741     if (!err)
742       {
743         s = gnupg_ttyname (0);
744         if (s)
745           err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
746       }
747     if (err)
748       log_fatal ("error recording startup environment: %s\n",
749                  gpg_strerror (err));
750
751     /* Fixme: Better use the locale function here.  */
752     opt.startup_lc_ctype = getenv ("LC_CTYPE");
753     if (opt.startup_lc_ctype)
754       opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
755     opt.startup_lc_messages = getenv ("LC_MESSAGES");
756     if (opt.startup_lc_messages)
757       opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
758   }
759
760   /* Check whether we have a config file on the commandline */
761   orig_argc = argc;
762   orig_argv = argv;
763   pargs.argc = &argc;
764   pargs.argv = &argv;
765   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
766   while (arg_parse( &pargs, opts))
767     {
768       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
769         parse_debug++;
770       else if (pargs.r_opt == oOptions)
771         { /* yes there is one, so we do not try the default one, but
772              read the option file when it is encountered at the
773              commandline */
774           default_config = 0;
775         }
776         else if (pargs.r_opt == oNoOptions)
777           default_config = 0; /* --no-options */
778         else if (pargs.r_opt == oHomedir)
779           opt.homedir = pargs.r.ret_str;
780         else if (pargs.r_opt == oDebugQuickRandom)
781           {
782             gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
783           }
784
785     }
786
787   /* Initialize the secure memory. */
788   gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
789   maybe_setuid = 0;
790
791   /*
792      Now we are now working under our real uid
793   */
794
795   if (default_config)
796     configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
797                                 NULL );
798
799   argc = orig_argc;
800   argv = orig_argv;
801   pargs.argc = &argc;
802   pargs.argv = &argv;
803   pargs.flags=  1;  /* do not remove the args */
804  next_pass:
805   if (configname)
806     {
807       configlineno = 0;
808       configfp = fopen (configname, "r");
809       if (!configfp)
810         {
811           if (default_config)
812             {
813               if( parse_debug )
814                 log_info (_("Note: no default option file '%s'\n"),
815                           configname );
816               /* Save the default conf file name so that
817                  reread_configuration is able to test whether the
818                  config file has been created in the meantime.  */
819               xfree (config_filename);
820               config_filename = configname;
821               configname = NULL;
822             }
823           else
824             {
825               log_error (_("option file '%s': %s\n"),
826                          configname, strerror(errno) );
827               exit(2);
828             }
829           xfree (configname);
830           configname = NULL;
831         }
832       if (parse_debug && configname )
833         log_info (_("reading options from '%s'\n"), configname );
834       default_config = 0;
835     }
836
837   while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
838     {
839       if (parse_rereadable_options (&pargs, 0))
840         continue; /* Already handled */
841       switch (pargs.r_opt)
842         {
843         case aGPGConfList: gpgconf_list = 1; break;
844         case aGPGConfTest: gpgconf_list = 2; break;
845         case aUseStandardSocketP: gpgconf_list = 3; break;
846         case oBatch: opt.batch=1; break;
847
848         case oDebugWait: debug_wait = pargs.r.ret_int; break;
849
850         case oOptions:
851           /* config files may not be nested (silently ignore them) */
852           if (!configfp)
853             {
854                 xfree(configname);
855                 configname = xstrdup(pargs.r.ret_str);
856                 goto next_pass;
857             }
858           break;
859         case oNoGreeting: /* Dummy option.  */ break;
860         case oNoVerbose: opt.verbose = 0; break;
861         case oNoOptions: break; /* no-options */
862         case oHomedir: opt.homedir = pargs.r.ret_str; break;
863         case oNoDetach: nodetach = 1; break;
864         case oLogFile: logfile = pargs.r.ret_str; break;
865         case oCsh: csh_style = 1; break;
866         case oSh: csh_style = 0; break;
867         case oServer: pipe_server = 1; break;
868         case oDaemon: is_daemon = 1; break;
869
870         case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
871         case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
872         case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
873         case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
874         case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
875           break;
876         case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
877           break;
878
879         case oUseStandardSocket:   /* dummy */ break;
880         case oNoUseStandardSocket: /* dummy */ break;
881
882         case oFakedSystemTime:
883           {
884             time_t faked_time = isotime2epoch (pargs.r.ret_str);
885             if (faked_time == (time_t)(-1))
886               faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
887             gnupg_set_time (faked_time, 0);
888           }
889           break;
890
891         case oKeepTTY: opt.keep_tty = 1; break;
892         case oKeepDISPLAY: opt.keep_display = 1; break;
893
894         case oSSHSupport:  opt.ssh_support = 1; break;
895         case oPuttySupport:
896 #        ifdef HAVE_W32_SYSTEM
897           putty_support = 1;
898           opt.ssh_support = 1;
899 #        endif
900           break;
901
902         case oExtraSocket:
903           opt.extra_socket = 1;  /* (1 = points into argv)  */
904           socket_name_extra = pargs.r.ret_str;
905           break;
906
907         case oDebugQuickRandom:
908           /* Only used by the first stage command line parser.  */
909           break;
910
911         case oWriteEnvFile: /* dummy */ break;
912
913         default : pargs.err = configfp? 1:2; break;
914         }
915     }
916   if (configfp)
917     {
918       fclose( configfp );
919       configfp = NULL;
920       /* Keep a copy of the name so that it can be read on SIGHUP. */
921       if (config_filename != configname)
922         {
923           xfree (config_filename);
924           config_filename = configname;
925         }
926       configname = NULL;
927       goto next_pass;
928     }
929
930   xfree (configname);
931   configname = NULL;
932   if (log_get_errorcount(0))
933     exit(2);
934
935   finalize_rereadable_options ();
936
937   /* Turn the homedir into an absolute one. */
938   opt.homedir = make_absfilename (opt.homedir, NULL);
939
940   /* Print a warning if an argument looks like an option.  */
941   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
942     {
943       int i;
944
945       for (i=0; i < argc; i++)
946         if (argv[i][0] == '-' && argv[i][1] == '-')
947           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
948     }
949
950 #ifdef ENABLE_NLS
951   /* gpg-agent usually does not output any messages because it runs in
952      the background.  For log files it is acceptable to have messages
953      always encoded in utf-8.  We switch here to utf-8, so that
954      commands like --help still give native messages.  It is far
955      easier to switch only once instead of for every message and it
956      actually helps when more then one thread is active (avoids an
957      extra copy step). */
958     bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
959 #endif
960
961   if (!pipe_server && !is_daemon && !gpgconf_list)
962     {
963      /* We have been called without any options and thus we merely
964         check whether an agent is already running.  We do this right
965         here so that we don't clobber a logfile with this check but
966         print the status directly to stderr. */
967       opt.debug = 0;
968       set_debug ();
969       check_for_running_agent (0);
970       agent_exit (0);
971     }
972
973   set_debug ();
974
975   if (atexit (cleanup))
976     {
977       log_error ("atexit failed\n");
978       cleanup ();
979       exit (1);
980     }
981
982   initialize_module_cache ();
983   initialize_module_call_pinentry ();
984   initialize_module_call_scd ();
985   initialize_module_trustlist ();
986
987   /* Try to create missing directories. */
988   create_directories ();
989
990   if (debug_wait && pipe_server)
991     {
992       log_debug ("waiting for debugger - my pid is %u .....\n",
993                  (unsigned int)getpid());
994       gnupg_sleep (debug_wait);
995       log_debug ("... okay\n");
996     }
997
998   if (gpgconf_list == 3)
999     {
1000       /* We now use the standard socket always - return true for
1001          backward compatibility.  */
1002       agent_exit (0);
1003     }
1004   else if (gpgconf_list == 2)
1005     agent_exit (0);
1006   else if (gpgconf_list)
1007     {
1008       char *filename;
1009       char *filename_esc;
1010
1011       /* List options and default values in the GPG Conf format.  */
1012       filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
1013                                 NULL );
1014       filename_esc = percent_escape (filename, NULL);
1015
1016       es_printf ("%s-%s.conf:%lu:\"%s\n",
1017                  GPGCONF_NAME, GPG_AGENT_NAME,
1018                  GC_OPT_FLAG_DEFAULT, filename_esc);
1019       xfree (filename);
1020       xfree (filename_esc);
1021
1022       es_printf ("verbose:%lu:\n"
1023               "quiet:%lu:\n"
1024               "debug-level:%lu:\"none:\n"
1025               "log-file:%lu:\n",
1026               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1027               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1028               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1029               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1030       es_printf ("default-cache-ttl:%lu:%d:\n",
1031               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1032       es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1033               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1034       es_printf ("max-cache-ttl:%lu:%d:\n",
1035               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1036       es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1037               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1038       es_printf ("enforce-passphrase-constraints:%lu:\n",
1039               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1040       es_printf ("min-passphrase-len:%lu:%d:\n",
1041               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1042       es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1043               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1044               MIN_PASSPHRASE_NONALPHA);
1045       es_printf ("check-passphrase-pattern:%lu:\n",
1046               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1047       es_printf ("max-passphrase-days:%lu:%d:\n",
1048               GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1049               MAX_PASSPHRASE_DAYS);
1050       es_printf ("enable-passphrase-history:%lu:\n",
1051               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1052       es_printf ("no-grab:%lu:\n",
1053               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1054       es_printf ("ignore-cache-for-signing:%lu:\n",
1055               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1056       es_printf ("no-allow-mark-trusted:%lu:\n",
1057               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1058       es_printf ("disable-scdaemon:%lu:\n",
1059               GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1060 #ifdef HAVE_W32_SYSTEM
1061       es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1062 #else
1063       es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1064 #endif
1065       es_printf ("allow-loopback-pinentry:%lu:\n",
1066                  GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1067
1068       agent_exit (0);
1069     }
1070
1071   /* Now start with logging to a file if this is desired. */
1072   if (logfile)
1073     {
1074       log_set_file (logfile);
1075       log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
1076                              |JNLIB_LOG_WITH_TIME
1077                              |JNLIB_LOG_WITH_PID));
1078       current_logfile = xstrdup (logfile);
1079     }
1080
1081   /* Make sure that we have a default ttyname. */
1082   if (!default_ttyname && gnupg_ttyname (1))
1083     default_ttyname = xstrdup (gnupg_ttyname (1));
1084   if (!default_ttytype && getenv ("TERM"))
1085     default_ttytype = xstrdup (getenv ("TERM"));
1086
1087
1088   if (pipe_server)
1089     {
1090       /* This is the simple pipe based server */
1091       ctrl_t ctrl;
1092
1093       ctrl = xtrycalloc (1, sizeof *ctrl);
1094       if (!ctrl)
1095         {
1096           log_error ("error allocating connection control data: %s\n",
1097                      strerror (errno) );
1098           agent_exit (1);
1099         }
1100       ctrl->session_env = session_env_new ();
1101       if (!ctrl->session_env)
1102         {
1103           log_error ("error allocating session environment block: %s\n",
1104                      strerror (errno) );
1105           xfree (ctrl);
1106           agent_exit (1);
1107         }
1108       agent_init_default_ctrl (ctrl);
1109       start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1110       agent_deinit_default_ctrl (ctrl);
1111       xfree (ctrl);
1112     }
1113   else if (!is_daemon)
1114     ; /* NOTREACHED */
1115   else
1116     { /* Regular server mode */
1117       gnupg_fd_t fd;
1118       gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1119       gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1120       pid_t pid;
1121
1122       /* Remove the DISPLAY variable so that a pinentry does not
1123          default to a specific display.  There is still a default
1124          display when gpg-agent was started using --display or a
1125          client requested this using an OPTION command.  Note, that we
1126          don't do this when running in reverse daemon mode (i.e. when
1127          exec the program given as arguments). */
1128 #ifndef HAVE_W32_SYSTEM
1129       if (!opt.keep_display && !argc)
1130         gnupg_unsetenv ("DISPLAY");
1131 #endif
1132
1133       /* Create the sockets.  */
1134       socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1135       fd = create_server_socket (socket_name, 1,
1136                                  &redir_socket_name, &socket_nonce);
1137
1138       if (opt.extra_socket)
1139         {
1140           socket_name_extra = create_socket_name (socket_name_extra, 0);
1141           opt.extra_socket = 2; /* Indicate that it has been malloced.  */
1142           fd_extra = create_server_socket (socket_name_extra, 0,
1143                                            &redir_socket_name_extra,
1144                                            &socket_nonce_extra);
1145         }
1146
1147       if (opt.ssh_support)
1148         {
1149           socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1150           fd_ssh = create_server_socket (socket_name_ssh, 0,
1151                                          &redir_socket_name_ssh,
1152                                          &socket_nonce_ssh);
1153         }
1154
1155       /* If we are going to exec a program in the parent, we record
1156          the PID, so that the child may check whether the program is
1157          still alive. */
1158       if (argc)
1159         parent_pid = getpid ();
1160
1161       fflush (NULL);
1162 #ifdef HAVE_W32_SYSTEM
1163       (void)csh_style;
1164       (void)nodetach;
1165       pid = getpid ();
1166 #else /*!HAVE_W32_SYSTEM*/
1167       pid = fork ();
1168       if (pid == (pid_t)-1)
1169         {
1170           log_fatal ("fork failed: %s\n", strerror (errno) );
1171           exit (1);
1172         }
1173       else if (pid)
1174         { /* We are the parent */
1175           char *infostr_ssh_sock, *infostr_ssh_valid;
1176
1177           /* Close the socket FD. */
1178           close (fd);
1179
1180           /* The signal mask might not be correct right now and thus
1181              we restore it.  That is not strictly necessary but some
1182              programs falsely assume a cleared signal mask.  */
1183
1184 #ifdef HAVE_SIGPROCMASK
1185           if (startup_signal_mask_valid)
1186             {
1187               if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1188                 log_error ("error restoring signal mask: %s\n",
1189                            strerror (errno));
1190             }
1191           else
1192             log_info ("no saved signal mask\n");
1193 #endif /*HAVE_SIGPROCMASK*/
1194
1195           /* Create the SSH info string if enabled. */
1196           if (opt.ssh_support)
1197             {
1198               if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1199                             socket_name_ssh) < 0)
1200                 {
1201                   log_error ("out of core\n");
1202                   kill (pid, SIGTERM);
1203                   exit (1);
1204                 }
1205               if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1206                             (unsigned long)getpid()) < 0)
1207                 {
1208                   log_error ("out of core\n");
1209                   kill (pid, SIGTERM);
1210                   exit (1);
1211                 }
1212             }
1213
1214           *socket_name = 0; /* Don't let cleanup() remove the socket -
1215                                the child should do this from now on */
1216           if (opt.extra_socket)
1217             *socket_name_extra = 0;
1218           if (opt.ssh_support)
1219             *socket_name_ssh = 0;
1220
1221           if (argc)
1222             { /* Run the program given on the commandline.  */
1223               if (opt.ssh_support && (putenv (infostr_ssh_sock)
1224                                       || putenv (infostr_ssh_valid)))
1225                 {
1226                   log_error ("failed to set environment: %s\n",
1227                              strerror (errno) );
1228                   kill (pid, SIGTERM );
1229                   exit (1);
1230                 }
1231
1232               /* Close all the file descriptors except the standard
1233                  ones and those open at startup.  We explicitly don't
1234                  close 0,1,2 in case something went wrong collecting
1235                  them at startup.  */
1236               close_all_fds (3, startup_fd_list);
1237
1238               /* Run the command.  */
1239               execvp (argv[0], argv);
1240               log_error ("failed to run the command: %s\n", strerror (errno));
1241               kill (pid, SIGTERM);
1242               exit (1);
1243             }
1244           else
1245             {
1246               /* Print the environment string, so that the caller can use
1247                  shell's eval to set it */
1248               if (csh_style)
1249                 {
1250                   if (opt.ssh_support)
1251                     {
1252                       *strchr (infostr_ssh_sock, '=') = ' ';
1253                       es_printf ("setenv %s;\n", infostr_ssh_sock);
1254                     }
1255                 }
1256               else
1257                 {
1258                   if (opt.ssh_support)
1259                     {
1260                       es_printf ("%s; export SSH_AUTH_SOCK;\n",
1261                                  infostr_ssh_sock);
1262                     }
1263                 }
1264               if (opt.ssh_support)
1265                 {
1266                   xfree (infostr_ssh_sock);
1267                   xfree (infostr_ssh_valid);
1268                 }
1269               exit (0);
1270             }
1271           /*NOTREACHED*/
1272         } /* End parent */
1273
1274       /*
1275          This is the child
1276        */
1277
1278       /* Detach from tty and put process into a new session */
1279       if (!nodetach )
1280         {
1281           int i;
1282           unsigned int oldflags;
1283
1284           /* Close stdin, stdout and stderr unless it is the log stream */
1285           for (i=0; i <= 2; i++)
1286             {
1287               if (!log_test_fd (i) && i != fd )
1288                 {
1289                   if ( ! close (i)
1290                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1291                     {
1292                       log_error ("failed to open '%s': %s\n",
1293                                  "/dev/null", strerror (errno));
1294                       cleanup ();
1295                       exit (1);
1296                     }
1297                 }
1298             }
1299           if (setsid() == -1)
1300             {
1301               log_error ("setsid() failed: %s\n", strerror(errno) );
1302               cleanup ();
1303               exit (1);
1304             }
1305
1306           log_get_prefix (&oldflags);
1307           log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1308           opt.running_detached = 1;
1309         }
1310
1311       if (chdir("/"))
1312         {
1313           log_error ("chdir to / failed: %s\n", strerror (errno));
1314           exit (1);
1315         }
1316
1317       {
1318         struct sigaction sa;
1319
1320         sa.sa_handler = SIG_IGN;
1321         sigemptyset (&sa.sa_mask);
1322         sa.sa_flags = 0;
1323         sigaction (SIGPIPE, &sa, NULL);
1324       }
1325 #endif /*!HAVE_W32_SYSTEM*/
1326
1327       log_info ("%s %s started\n", strusage(11), strusage(13) );
1328       handle_connections (fd, fd_extra, fd_ssh);
1329       assuan_sock_close (fd);
1330     }
1331
1332   return 0;
1333 }
1334
1335
1336 /* Exit entry point.  This function should be called instead of a
1337    plain exit.  */
1338 void
1339 agent_exit (int rc)
1340 {
1341   /*FIXME: update_random_seed_file();*/
1342
1343   /* We run our cleanup handler because that may close cipher contexts
1344      stored in secure memory and thus this needs to be done before we
1345      explicitly terminate secure memory.  */
1346   cleanup ();
1347
1348 #if 1
1349   /* at this time a bit annoying */
1350   if (opt.debug & DBG_MEMSTAT_VALUE)
1351     {
1352       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1353       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1354     }
1355   if (opt.debug)
1356     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1357 #endif
1358   gcry_control (GCRYCTL_TERM_SECMEM );
1359   rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1360   exit (rc);
1361 }
1362
1363
1364 /* Each thread has its own local variables conveyed by a control
1365    structure usually identified by an argument named CTRL.  This
1366    function is called immediately after allocating the control
1367    structure.  Its purpose is to setup the default values for that
1368    structure.  Note that some values may have already been set.  */
1369 static void
1370 agent_init_default_ctrl (ctrl_t ctrl)
1371 {
1372   assert (ctrl->session_env);
1373
1374   /* Note we ignore malloc errors because we can't do much about it
1375      and the request will fail anyway shortly after this
1376      initialization. */
1377   session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1378   session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1379   session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1380   session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1381   session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1382
1383   if (ctrl->lc_ctype)
1384     xfree (ctrl->lc_ctype);
1385   ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1386
1387   if (ctrl->lc_messages)
1388     xfree (ctrl->lc_messages);
1389   ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1390                                     /**/ : NULL;
1391   ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1392 }
1393
1394
1395 /* Release all resources allocated by default in the control
1396    structure.  This is the counterpart to agent_init_default_ctrl.  */
1397 static void
1398 agent_deinit_default_ctrl (ctrl_t ctrl)
1399 {
1400   session_env_release (ctrl->session_env);
1401
1402   if (ctrl->lc_ctype)
1403     xfree (ctrl->lc_ctype);
1404   if (ctrl->lc_messages)
1405     xfree (ctrl->lc_messages);
1406 }
1407
1408
1409 /* Because the ssh protocol does not send us information about the
1410    current TTY setting, we use this function to use those from startup
1411    or those explictly set.  This is also used for the restricted mode
1412    where we ignore requests to change the environment.  */
1413 gpg_error_t
1414 agent_copy_startup_env (ctrl_t ctrl)
1415 {
1416   static const char *names[] =
1417     {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1418   gpg_error_t err = 0;
1419   int idx;
1420   const char *value;
1421
1422   for (idx=0; !err && names[idx]; idx++)
1423       if ((value = session_env_getenv (opt.startup_env, names[idx])))
1424       err = session_env_setenv (ctrl->session_env, names[idx], value);
1425
1426   if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1427     if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1428       err = gpg_error_from_syserror ();
1429
1430   if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1431     if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1432       err = gpg_error_from_syserror ();
1433
1434   if (err)
1435     log_error ("error setting default session environment: %s\n",
1436                gpg_strerror (err));
1437
1438   return err;
1439 }
1440
1441
1442 /* Reread parts of the configuration.  Note, that this function is
1443    obviously not thread-safe and should only be called from the PTH
1444    signal handler.
1445
1446    Fixme: Due to the way the argument parsing works, we create a
1447    memory leak here for all string type arguments.  There is currently
1448    no clean way to tell whether the memory for the argument has been
1449    allocated or points into the process' original arguments.  Unless
1450    we have a mechanism to tell this, we need to live on with this. */
1451 static void
1452 reread_configuration (void)
1453 {
1454   ARGPARSE_ARGS pargs;
1455   FILE *fp;
1456   unsigned int configlineno = 0;
1457   int dummy;
1458
1459   if (!config_filename)
1460     return; /* No config file. */
1461
1462   fp = fopen (config_filename, "r");
1463   if (!fp)
1464     {
1465       log_info (_("option file '%s': %s\n"),
1466                 config_filename, strerror(errno) );
1467       return;
1468     }
1469
1470   parse_rereadable_options (NULL, 1); /* Start from the default values. */
1471
1472   memset (&pargs, 0, sizeof pargs);
1473   dummy = 0;
1474   pargs.argc = &dummy;
1475   pargs.flags = 1;  /* do not remove the args */
1476   while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1477     {
1478       if (pargs.r_opt < -1)
1479         pargs.err = 1; /* Print a warning. */
1480       else /* Try to parse this option - ignore unchangeable ones. */
1481         parse_rereadable_options (&pargs, 1);
1482     }
1483   fclose (fp);
1484   finalize_rereadable_options ();
1485   set_debug ();
1486 }
1487
1488
1489 /* Return the file name of the socket we are using for native
1490    requests.  */
1491 const char *
1492 get_agent_socket_name (void)
1493 {
1494   const char *s = socket_name;
1495
1496   return (s && *s)? s : NULL;
1497 }
1498
1499 /* Return the file name of the socket we are using for SSH
1500    requests.  */
1501 const char *
1502 get_agent_ssh_socket_name (void)
1503 {
1504   const char *s = socket_name_ssh;
1505
1506   return (s && *s)? s : NULL;
1507 }
1508
1509
1510 /* Under W32, this function returns the handle of the scdaemon
1511    notification event.  Calling it the first time creates that
1512    event.  */
1513 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1514 void *
1515 get_agent_scd_notify_event (void)
1516 {
1517   static HANDLE the_event = INVALID_HANDLE_VALUE;
1518
1519   if (the_event == INVALID_HANDLE_VALUE)
1520     {
1521       HANDLE h, h2;
1522       SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1523
1524       /* We need to use a manual reset event object due to the way our
1525          w32-pth wait function works: If we would use an automatic
1526          reset event we are not able to figure out which handle has
1527          been signaled because at the time we single out the signaled
1528          handles using WFSO the event has already been reset due to
1529          the WFMO.  */
1530       h = CreateEvent (&sa, TRUE, FALSE, NULL);
1531       if (!h)
1532         log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1533       else if (!DuplicateHandle (GetCurrentProcess(), h,
1534                                  GetCurrentProcess(), &h2,
1535                                  EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1536         {
1537           log_error ("setting syncronize for scd notify event failed: %s\n",
1538                      w32_strerror (-1) );
1539           CloseHandle (h);
1540         }
1541       else
1542         {
1543           CloseHandle (h);
1544           the_event = h2;
1545         }
1546     }
1547
1548   return the_event;
1549 }
1550 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1551
1552
1553
1554 /* Create a name for the socket in the home directory as using
1555    STANDARD_NAME.  We also check for valid characters as well as
1556    against a maximum allowed length for a unix domain socket is done.
1557    The function terminates the process in case of an error.  Returns:
1558    Pointer to an allocated string with the absolute name of the socket
1559    used.  */
1560 static char *
1561 create_socket_name (char *standard_name, int with_homedir)
1562 {
1563   char *name;
1564
1565   if (with_homedir)
1566     name = make_filename (opt.homedir, standard_name, NULL);
1567   else
1568     name = make_filename (standard_name, NULL);
1569   if (strchr (name, PATHSEP_C))
1570     {
1571       log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1572       agent_exit (2);
1573     }
1574   return name;
1575 }
1576
1577
1578
1579 /* Create a Unix domain socket with NAME.  Returns the file descriptor
1580    or terminates the process in case of an error.  Note that this
1581    function needs to be used for the regular socket first (indicated
1582    by PRIMARY) and only then for the extra and the ssh sockets.  If
1583    the socket has been redirected the name of the real socket is
1584    stored as a malloced string at R_REDIR_NAME.  */
1585 static gnupg_fd_t
1586 create_server_socket (char *name, int primary,
1587                       char **r_redir_name, assuan_sock_nonce_t *nonce)
1588 {
1589   struct sockaddr *addr;
1590   struct sockaddr_un *unaddr;
1591   socklen_t len;
1592   gnupg_fd_t fd;
1593   int rc;
1594
1595   xfree (*r_redir_name);
1596   *r_redir_name = NULL;
1597
1598   fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1599   if (fd == ASSUAN_INVALID_FD)
1600     {
1601       log_error (_("can't create socket: %s\n"), strerror (errno));
1602       *name = 0; /* Inhibit removal of the socket by cleanup(). */
1603       agent_exit (2);
1604     }
1605
1606   unaddr = xmalloc (sizeof *unaddr);
1607   addr = (struct sockaddr*)unaddr;
1608
1609 #if ASSUAN_VERSION_NUMBER >= 0x020104 /* >= 2.1.4 */
1610   {
1611     int redirected;
1612
1613     if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1614       {
1615         if (errno == ENAMETOOLONG)
1616           log_error (_("socket name '%s' is too long\n"), name);
1617         else
1618           log_error ("error preparing socket '%s': %s\n",
1619                      name, gpg_strerror (gpg_error_from_syserror ()));
1620         *name = 0; /* Inhibit removal of the socket by cleanup(). */
1621         agent_exit (2);
1622       }
1623     if (redirected)
1624       {
1625         *r_redir_name = xstrdup (unaddr->sun_path);
1626         if (opt.verbose)
1627           log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1628       }
1629   }
1630 #else /* Assuan < 2.1.4 */
1631   memset (unaddr, 0, sizeof *unaddr);
1632   unaddr->sun_family = AF_UNIX;
1633   if (strlen (name) + 1 >= sizeof (unaddr->sun_path))
1634     {
1635       log_error (_("socket name '%s' is too long\n"), name);
1636       *name = 0; /* Inhibit removal of the socket by cleanup(). */
1637       agent_exit (2);
1638     }
1639   strcpy (unaddr->sun_path, name);
1640 #endif /* Assuan < 2.1.4 */
1641
1642   len = SUN_LEN (unaddr);
1643   rc = assuan_sock_bind (fd, addr, len);
1644
1645   /* Our error code mapping on W32CE returns EEXIST thus we also test
1646      for this. */
1647   if (rc == -1
1648       && (errno == EADDRINUSE
1649 #ifdef HAVE_W32_SYSTEM
1650           || errno == EEXIST
1651 #endif
1652           ))
1653     {
1654       /* Check whether a gpg-agent is already running.  We do this
1655          test only if this is the primary socket.  For secondary
1656          sockets we assume that a test for gpg-agent has already been
1657          done and reuse the requested socket.  Testing the ssh-socket
1658          is not possible because at this point, though we know the new
1659          Assuan socket, the Assuan server and thus the ssh-agent
1660          server is not yet operational; this would lead to a hang.  */
1661       if (primary && !check_for_running_agent (1))
1662         {
1663           log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
1664           log_set_file (NULL);
1665           log_error (_("a gpg-agent is already running - "
1666                        "not starting a new one\n"));
1667           *name = 0; /* Inhibit removal of the socket by cleanup(). */
1668           assuan_sock_close (fd);
1669           agent_exit (2);
1670         }
1671       gnupg_remove (unaddr->sun_path);
1672       rc = assuan_sock_bind (fd, addr, len);
1673     }
1674   if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1675     log_error (_("error getting nonce for the socket\n"));
1676   if (rc == -1)
1677     {
1678       /* We use gpg_strerror here because it allows us to get strings
1679          for some W32 socket error codes.  */
1680       log_error (_("error binding socket to '%s': %s\n"),
1681                  unaddr->sun_path,
1682                  gpg_strerror (gpg_error_from_syserror ()));
1683
1684       assuan_sock_close (fd);
1685       *name = 0; /* Inhibit removal of the socket by cleanup(). */
1686       agent_exit (2);
1687     }
1688
1689   if (listen (FD2INT(fd), 5 ) == -1)
1690     {
1691       log_error (_("listen() failed: %s\n"), strerror (errno));
1692       *name = 0; /* Inhibit removal of the socket by cleanup(). */
1693       assuan_sock_close (fd);
1694       agent_exit (2);
1695     }
1696
1697   if (opt.verbose)
1698     log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1699
1700   return fd;
1701 }
1702
1703
1704 /* Check that the directory for storing the private keys exists and
1705    create it if not.  This function won't fail as it is only a
1706    convenience function and not strictly necessary.  */
1707 static void
1708 create_private_keys_directory (const char *home)
1709 {
1710   char *fname;
1711   struct stat statbuf;
1712
1713   fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1714   if (stat (fname, &statbuf) && errno == ENOENT)
1715     {
1716       if (gnupg_mkdir (fname, "-rwx"))
1717         log_error (_("can't create directory '%s': %s\n"),
1718                    fname, strerror (errno) );
1719       else if (!opt.quiet)
1720         log_info (_("directory '%s' created\n"), fname);
1721     }
1722   xfree (fname);
1723 }
1724
1725 /* Create the directory only if the supplied directory name is the
1726    same as the default one.  This way we avoid to create arbitrary
1727    directories when a non-default home directory is used.  To cope
1728    with HOME, we compare only the suffix if we see that the default
1729    homedir does start with a tilde.  We don't stop here in case of
1730    problems because other functions will throw an error anyway.*/
1731 static void
1732 create_directories (void)
1733 {
1734   struct stat statbuf;
1735   const char *defhome = standard_homedir ();
1736   char *home;
1737
1738   home = make_filename (opt.homedir, NULL);
1739   if ( stat (home, &statbuf) )
1740     {
1741       if (errno == ENOENT)
1742         {
1743           if (
1744 #ifdef HAVE_W32_SYSTEM
1745               ( !compare_filenames (home, defhome) )
1746 #else
1747               (*defhome == '~'
1748                 && (strlen (home) >= strlen (defhome+1)
1749                     && !strcmp (home + strlen(home)
1750                                 - strlen (defhome+1), defhome+1)))
1751                || (*defhome != '~' && !strcmp (home, defhome) )
1752 #endif
1753                )
1754             {
1755               if (gnupg_mkdir (home, "-rwx"))
1756                 log_error (_("can't create directory '%s': %s\n"),
1757                            home, strerror (errno) );
1758               else
1759                 {
1760                   if (!opt.quiet)
1761                     log_info (_("directory '%s' created\n"), home);
1762                   create_private_keys_directory (home);
1763                 }
1764             }
1765         }
1766       else
1767         log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1768     }
1769   else if ( !S_ISDIR(statbuf.st_mode))
1770     {
1771       log_error (_("can't use '%s' as home directory\n"), home);
1772     }
1773   else /* exists and is a directory. */
1774     {
1775       create_private_keys_directory (home);
1776     }
1777   xfree (home);
1778 }
1779
1780
1781
1782 /* This is the worker for the ticker.  It is called every few seconds
1783    and may only do fast operations. */
1784 static void
1785 handle_tick (void)
1786 {
1787   static time_t last_minute;
1788
1789   if (!last_minute)
1790     last_minute = time (NULL);
1791
1792   /* Check whether the scdaemon has died and cleanup in this case. */
1793   agent_scd_check_aliveness ();
1794
1795   /* If we are running as a child of another process, check whether
1796      the parent is still alive and shutdown if not. */
1797 #ifndef HAVE_W32_SYSTEM
1798   if (parent_pid != (pid_t)(-1))
1799     {
1800       if (kill (parent_pid, 0))
1801         {
1802           shutdown_pending = 2;
1803           log_info ("parent process died - shutting down\n");
1804           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1805           cleanup ();
1806           agent_exit (0);
1807         }
1808     }
1809 #endif /*HAVE_W32_SYSTEM*/
1810
1811   /* Code to be run from time to time.  */
1812 #if CHECK_OWN_SOCKET_INTERVAL > 0
1813   if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
1814     {
1815       check_own_socket ();
1816       last_minute = time (NULL);
1817     }
1818 #endif
1819
1820 }
1821
1822
1823 /* A global function which allows us to call the reload stuff from
1824    other places too.  This is only used when build for W32.  */
1825 void
1826 agent_sighup_action (void)
1827 {
1828   log_info ("SIGHUP received - "
1829             "re-reading configuration and flushing cache\n");
1830
1831   agent_flush_cache ();
1832   reread_configuration ();
1833   agent_reload_trustlist ();
1834   /* We flush the module name cache so that after installing a
1835      "pinentry" binary that one can be used in case the
1836      "pinentry-basic" fallback was in use.  */
1837   gnupg_module_name_flush_some ();
1838 }
1839
1840
1841 /* A helper function to handle SIGUSR2.  */
1842 static void
1843 agent_sigusr2_action (void)
1844 {
1845   if (opt.verbose)
1846     log_info ("SIGUSR2 received - updating card event counter\n");
1847   /* Nothing to check right now.  We only increment a counter.  */
1848   bump_card_eventcounter ();
1849 }
1850
1851
1852 #ifndef HAVE_W32_SYSTEM
1853 /* The signal handler for this program.  It is expected to be run in
1854    its own trhead and not in the context of a signal handler.  */
1855 static void
1856 handle_signal (int signo)
1857 {
1858   switch (signo)
1859     {
1860 #ifndef HAVE_W32_SYSTEM
1861     case SIGHUP:
1862       agent_sighup_action ();
1863       break;
1864
1865     case SIGUSR1:
1866       log_info ("SIGUSR1 received - printing internal information:\n");
1867       /* Fixme: We need to see how to integrate pth dumping into our
1868          logging system.  */
1869       /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1870       agent_query_dump_state ();
1871       agent_scd_dump_state ();
1872       break;
1873
1874     case SIGUSR2:
1875       agent_sigusr2_action ();
1876       break;
1877
1878     case SIGTERM:
1879       if (!shutdown_pending)
1880         log_info ("SIGTERM received - shutting down ...\n");
1881       else
1882         log_info ("SIGTERM received - still %i open connections\n",
1883                   active_connections);
1884       shutdown_pending++;
1885       if (shutdown_pending > 2)
1886         {
1887           log_info ("shutdown forced\n");
1888           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1889           cleanup ();
1890           agent_exit (0);
1891         }
1892       break;
1893
1894     case SIGINT:
1895       log_info ("SIGINT received - immediate shutdown\n");
1896       log_info( "%s %s stopped\n", strusage(11), strusage(13));
1897       cleanup ();
1898       agent_exit (0);
1899       break;
1900 #endif
1901     default:
1902       log_info ("signal %d received - no action defined\n", signo);
1903     }
1904 }
1905 #endif
1906
1907 /* Check the nonce on a new connection.  This is a NOP unless we we
1908    are using our Unix domain socket emulation under Windows.  */
1909 static int
1910 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1911 {
1912   if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1913     {
1914       log_info (_("error reading nonce on fd %d: %s\n"),
1915                 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1916       assuan_sock_close (ctrl->thread_startup.fd);
1917       xfree (ctrl);
1918       return -1;
1919     }
1920   else
1921     return 0;
1922 }
1923
1924
1925 #ifdef HAVE_W32_SYSTEM
1926 /* The window message processing function for Putty.  Warning: This
1927    code runs as a native Windows thread.  Use of our own functions
1928    needs to be bracket with pth_leave/pth_enter. */
1929 static LRESULT CALLBACK
1930 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1931 {
1932   int ret = 0;
1933   int w32rc;
1934   COPYDATASTRUCT *cds;
1935   const char *mapfile;
1936   HANDLE maphd;
1937   PSID mysid = NULL;
1938   PSID mapsid = NULL;
1939   void *data = NULL;
1940   PSECURITY_DESCRIPTOR psd = NULL;
1941   ctrl_t ctrl = NULL;
1942
1943   if (msg != WM_COPYDATA)
1944     {
1945       return DefWindowProc (hwnd, msg, wparam, lparam);
1946     }
1947
1948   cds = (COPYDATASTRUCT*)lparam;
1949   if (cds->dwData != PUTTY_IPC_MAGIC)
1950     return 0;  /* Ignore data with the wrong magic.  */
1951   mapfile = cds->lpData;
1952   if (!cds->cbData || mapfile[cds->cbData - 1])
1953     return 0;  /* Ignore empty and non-properly terminated strings.  */
1954
1955   if (DBG_ASSUAN)
1956     {
1957       npth_protect ();
1958       log_debug ("ssh map file '%s'", mapfile);
1959       npth_unprotect ();
1960     }
1961
1962   maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
1963   if (DBG_ASSUAN)
1964     {
1965       npth_protect ();
1966       log_debug ("ssh map handle %p\n", maphd);
1967       npth_unprotect ();
1968     }
1969
1970   if (!maphd || maphd == INVALID_HANDLE_VALUE)
1971     return 0;
1972
1973   npth_protect ();
1974
1975   mysid = w32_get_user_sid ();
1976   if (!mysid)
1977     {
1978       log_error ("error getting my sid\n");
1979       goto leave;
1980     }
1981
1982   w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
1983                            OWNER_SECURITY_INFORMATION,
1984                            &mapsid, NULL, NULL, NULL,
1985                            &psd);
1986   if (w32rc)
1987     {
1988       log_error ("error getting sid of ssh map file: rc=%d", w32rc);
1989       goto leave;
1990     }
1991
1992   if (DBG_ASSUAN)
1993     {
1994       char *sidstr;
1995
1996       if (!ConvertSidToStringSid (mysid, &sidstr))
1997         sidstr = NULL;
1998       log_debug ("          my sid: '%s'", sidstr? sidstr: "[error]");
1999       LocalFree (sidstr);
2000       if (!ConvertSidToStringSid (mapsid, &sidstr))
2001         sidstr = NULL;
2002       log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2003       LocalFree (sidstr);
2004     }
2005
2006   if (!EqualSid (mysid, mapsid))
2007     {
2008       log_error ("ssh map file has a non-matching sid\n");
2009       goto leave;
2010     }
2011
2012   data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2013   if (DBG_ASSUAN)
2014     log_debug ("ssh IPC buffer at %p\n", data);
2015   if (!data)
2016     goto leave;
2017
2018   /* log_printhex ("request:", data, 20); */
2019
2020   ctrl = xtrycalloc (1, sizeof *ctrl);
2021   if (!ctrl)
2022     {
2023       log_error ("error allocating connection control data: %s\n",
2024                  strerror (errno) );
2025       goto leave;
2026     }
2027   ctrl->session_env = session_env_new ();
2028   if (!ctrl->session_env)
2029     {
2030       log_error ("error allocating session environment block: %s\n",
2031                  strerror (errno) );
2032       goto leave;
2033     }
2034
2035   agent_init_default_ctrl (ctrl);
2036   if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2037     ret = 1; /* Valid ssh message has been constructed.  */
2038   agent_deinit_default_ctrl (ctrl);
2039   /* log_printhex ("  reply:", data, 20); */
2040
2041  leave:
2042   xfree (ctrl);
2043   if (data)
2044     UnmapViewOfFile (data);
2045   xfree (mapsid);
2046   if (psd)
2047     LocalFree (psd);
2048   xfree (mysid);
2049   CloseHandle (maphd);
2050
2051   npth_unprotect ();
2052
2053   return ret;
2054 }
2055 #endif /*HAVE_W32_SYSTEM*/
2056
2057
2058 #ifdef HAVE_W32_SYSTEM
2059 /* The thread handling Putty's IPC requests.  */
2060 static void *
2061 putty_message_thread (void *arg)
2062 {
2063   WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2064                         NULL, NULL, NULL, NULL, NULL, "Pageant"};
2065   HWND hwnd;
2066   MSG msg;
2067
2068   (void)arg;
2069
2070   if (opt.verbose)
2071     log_info ("putty message loop thread started\n");
2072
2073   /* The message loop runs as thread independent from our nPth system.
2074      This also means that we need to make sure that we switch back to
2075      our system before calling any no-windows function.  */
2076   npth_unprotect ();
2077
2078   /* First create a window to make sure that a message queue exists
2079      for this thread.  */
2080   if (!RegisterClass (&wndwclass))
2081     {
2082       npth_protect ();
2083       log_error ("error registering Pageant window class");
2084       return NULL;
2085     }
2086   hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2087                          0, 0, 0, 0,
2088                          HWND_MESSAGE,  /* hWndParent */
2089                          NULL,          /* hWndMenu   */
2090                          NULL,          /* hInstance  */
2091                          NULL);         /* lpParm     */
2092   if (!hwnd)
2093     {
2094       npth_protect ();
2095       log_error ("error creating Pageant window");
2096       return NULL;
2097     }
2098
2099   while (GetMessage(&msg, NULL, 0, 0))
2100     {
2101       TranslateMessage(&msg);
2102       DispatchMessage(&msg);
2103     }
2104
2105   /* Back to nPth.  */
2106   npth_protect ();
2107
2108   if (opt.verbose)
2109     log_info ("putty message loop thread stopped\n");
2110   return NULL;
2111 }
2112 #endif /*HAVE_W32_SYSTEM*/
2113
2114
2115 static void *
2116 start_connection_thread (ctrl_t ctrl)
2117 {
2118   if (check_nonce (ctrl, &socket_nonce))
2119     {
2120       log_error ("handler 0x%lx nonce check FAILED\n",
2121                  (unsigned long) npth_self());
2122       return NULL;
2123     }
2124
2125   agent_init_default_ctrl (ctrl);
2126   if (opt.verbose)
2127     log_info (_("handler 0x%lx for fd %d started\n"),
2128               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2129
2130   start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2131   if (opt.verbose)
2132     log_info (_("handler 0x%lx for fd %d terminated\n"),
2133               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2134
2135   agent_deinit_default_ctrl (ctrl);
2136   xfree (ctrl);
2137   return NULL;
2138 }
2139
2140
2141 /* This is the standard connection thread's main function.  */
2142 static void *
2143 start_connection_thread_std (void *arg)
2144 {
2145   ctrl_t ctrl = arg;
2146
2147   return start_connection_thread (ctrl);
2148 }
2149
2150
2151 /* This is the extra socket connection thread's main function.  */
2152 static void *
2153 start_connection_thread_extra (void *arg)
2154 {
2155   ctrl_t ctrl = arg;
2156
2157   ctrl->restricted = 1;
2158   return start_connection_thread (ctrl);
2159 }
2160
2161
2162 /* This is the ssh connection thread's main function.  */
2163 static void *
2164 start_connection_thread_ssh (void *arg)
2165 {
2166   ctrl_t ctrl = arg;
2167
2168   if (check_nonce (ctrl, &socket_nonce_ssh))
2169     return NULL;
2170
2171   agent_init_default_ctrl (ctrl);
2172   if (opt.verbose)
2173     log_info (_("ssh handler 0x%lx for fd %d started\n"),
2174               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2175
2176   start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2177   if (opt.verbose)
2178     log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2179               (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2180
2181   agent_deinit_default_ctrl (ctrl);
2182   xfree (ctrl);
2183   return NULL;
2184 }
2185
2186
2187 /* Connection handler loop.  Wait for connection requests and spawn a
2188    thread after accepting a connection.  */
2189 static void
2190 handle_connections (gnupg_fd_t listen_fd,
2191                     gnupg_fd_t listen_fd_extra,
2192                     gnupg_fd_t listen_fd_ssh)
2193 {
2194   npth_attr_t tattr;
2195   struct sockaddr_un paddr;
2196   socklen_t plen;
2197   fd_set fdset, read_fdset;
2198   int ret;
2199   gnupg_fd_t fd;
2200   int nfd;
2201   int saved_errno;
2202   struct timespec abstime;
2203   struct timespec curtime;
2204   struct timespec timeout;
2205 #ifdef HAVE_W32_SYSTEM
2206   HANDLE events[2];
2207   unsigned int events_set;
2208 #endif
2209   struct {
2210     const char *name;
2211     void *(*func) (void *arg);
2212     gnupg_fd_t l_fd;
2213   } listentbl[] = {
2214     { "std",  start_connection_thread_std   },
2215     { "extra",start_connection_thread_extra },
2216     { "ssh",  start_connection_thread_ssh   }
2217   };
2218
2219
2220   ret = npth_attr_init(&tattr);
2221   if (ret)
2222     log_fatal ("error allocating thread attributes: %s\n",
2223                strerror (ret));
2224   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2225
2226 #ifndef HAVE_W32_SYSTEM
2227   npth_sigev_init ();
2228   npth_sigev_add (SIGHUP);
2229   npth_sigev_add (SIGUSR1);
2230   npth_sigev_add (SIGUSR2);
2231   npth_sigev_add (SIGINT);
2232   npth_sigev_add (SIGTERM);
2233   npth_sigev_fini ();
2234 #else
2235 # ifdef HAVE_W32CE_SYSTEM
2236   /* Use a dummy event. */
2237   sigs = 0;
2238   ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2239 # else
2240   events[0] = get_agent_scd_notify_event ();
2241   events[1] = INVALID_HANDLE_VALUE;
2242 # endif
2243 #endif
2244
2245   /* On Windows we need to fire up a separate thread to listen for
2246      requests from Putty (an SSH client), so we can replace Putty's
2247      Pageant (its ssh-agent implementation). */
2248 #ifdef HAVE_W32_SYSTEM
2249   if (putty_support)
2250     {
2251       npth_t thread;
2252
2253       ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2254       if (ret)
2255         {
2256           log_error ("error spawning putty message loop: %s\n", strerror (ret));
2257         }
2258     }
2259 #endif /*HAVE_W32_SYSTEM*/
2260
2261   /* Set a flag to tell call-scd.c that it may enable event
2262      notifications.  */
2263   opt.sigusr2_enabled = 1;
2264
2265   FD_ZERO (&fdset);
2266   FD_SET (FD2INT (listen_fd), &fdset);
2267   nfd = FD2INT (listen_fd);
2268   if (listen_fd_extra != GNUPG_INVALID_FD)
2269     {
2270       FD_SET ( FD2INT(listen_fd_extra), &fdset);
2271       if (FD2INT (listen_fd_extra) > nfd)
2272         nfd = FD2INT (listen_fd_extra);
2273     }
2274   if (listen_fd_ssh != GNUPG_INVALID_FD)
2275     {
2276       FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2277       if (FD2INT (listen_fd_ssh) > nfd)
2278         nfd = FD2INT (listen_fd_ssh);
2279     }
2280
2281   listentbl[0].l_fd = listen_fd;
2282   listentbl[1].l_fd = listen_fd_extra;
2283   listentbl[2].l_fd = listen_fd_ssh;
2284
2285   npth_clock_gettime (&abstime);
2286   abstime.tv_sec += TIMERTICK_INTERVAL;
2287
2288   for (;;)
2289     {
2290       /* Shutdown test.  */
2291       if (shutdown_pending)
2292         {
2293           if (active_connections == 0)
2294             break; /* ready */
2295
2296           /* Do not accept new connections but keep on running the
2297              loop to cope with the timer events.  */
2298           FD_ZERO (&fdset);
2299         }
2300
2301       /* POSIX says that fd_set should be implemented as a structure,
2302          thus a simple assignment is fine to copy the entire set.  */
2303       read_fdset = fdset;
2304
2305       npth_clock_gettime (&curtime);
2306       if (!(npth_timercmp (&curtime, &abstime, <)))
2307         {
2308           /* Timeout.  */
2309           handle_tick ();
2310           npth_clock_gettime (&abstime);
2311           abstime.tv_sec += TIMERTICK_INTERVAL;
2312         }
2313       npth_timersub (&abstime, &curtime, &timeout);
2314
2315 #ifndef HAVE_W32_SYSTEM
2316       ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2317                           npth_sigev_sigmask ());
2318       saved_errno = errno;
2319
2320       {
2321         int signo;
2322         while (npth_sigev_get_pending (&signo))
2323           handle_signal (signo);
2324       }
2325 #else
2326       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2327                           events, &events_set);
2328       saved_errno = errno;
2329
2330       /* This is valid even if npth_eselect returns an error.  */
2331       if (events_set & 1)
2332         agent_sigusr2_action ();
2333 #endif
2334
2335       if (ret == -1 && saved_errno != EINTR)
2336         {
2337           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2338                      strerror (saved_errno));
2339           npth_sleep (1);
2340           continue;
2341         }
2342       if (ret <= 0)
2343         /* Interrupt or timeout.  Will be handled when calculating the
2344            next timeout.  */
2345         continue;
2346
2347       if (!shutdown_pending)
2348         {
2349           int idx;
2350           ctrl_t ctrl;
2351           npth_t thread;
2352
2353           for (idx=0; idx < DIM(listentbl); idx++)
2354             {
2355               if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2356                 continue;
2357               if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2358                 continue;
2359
2360               plen = sizeof paddr;
2361               fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2362                                         (struct sockaddr *)&paddr, &plen));
2363               if (fd == GNUPG_INVALID_FD)
2364                 {
2365                   log_error ("accept failed for %s: %s\n",
2366                              listentbl[idx].name, strerror (errno));
2367                 }
2368               else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2369                 {
2370                   log_error ("error allocating connection data for %s: %s\n",
2371                              listentbl[idx].name, strerror (errno) );
2372                   assuan_sock_close (fd);
2373                 }
2374               else if ( !(ctrl->session_env = session_env_new ()))
2375                 {
2376                   log_error ("error allocating session env block for %s: %s\n",
2377                              listentbl[idx].name, strerror (errno) );
2378                   xfree (ctrl);
2379                   assuan_sock_close (fd);
2380                 }
2381               else
2382                 {
2383                   ctrl->thread_startup.fd = fd;
2384                   ret = npth_create (&thread, &tattr,
2385                                      listentbl[idx].func, ctrl);
2386                   if (ret)
2387                     {
2388                       log_error ("error spawning connection handler for %s:"
2389                                  " %s\n", listentbl[idx].name, strerror (ret));
2390                       assuan_sock_close (fd);
2391                       xfree (ctrl);
2392                     }
2393                 }
2394               fd = GNUPG_INVALID_FD;
2395             }
2396         }
2397     }
2398
2399   cleanup ();
2400   log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2401   npth_attr_destroy (&tattr);
2402 }
2403
2404
2405
2406 /* Helper for check_own_socket.  */
2407 static gpg_error_t
2408 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2409 {
2410   membuf_t *mb = opaque;
2411   put_membuf (mb, buffer, length);
2412   return 0;
2413 }
2414
2415
2416 /* The thread running the actual check.  We need to run this in a
2417    separate thread so that check_own_thread can be called from the
2418    timer tick.  */
2419 static void *
2420 check_own_socket_thread (void *arg)
2421 {
2422   int rc;
2423   char *sockname = arg;
2424   assuan_context_t ctx = NULL;
2425   membuf_t mb;
2426   char *buffer;
2427
2428   check_own_socket_running++;
2429
2430   rc = assuan_new (&ctx);
2431   if (rc)
2432     {
2433       log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2434       goto leave;
2435     }
2436
2437   rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2438   if (rc)
2439     {
2440       log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2441       goto leave;
2442     }
2443
2444   init_membuf (&mb, 100);
2445   rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2446                         NULL, NULL, NULL, NULL);
2447   put_membuf (&mb, "", 1);
2448   buffer = get_membuf (&mb, NULL);
2449   if (rc || !buffer)
2450     {
2451       log_error ("sending command \"%s\" to my own socket failed: %s\n",
2452                  "GETINFO pid", gpg_strerror (rc));
2453       rc = 1;
2454     }
2455   else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2456     {
2457       log_error ("socket is now serviced by another server\n");
2458       rc = 1;
2459     }
2460   else if (opt.verbose > 1)
2461     log_error ("socket is still served by this server\n");
2462
2463   xfree (buffer);
2464
2465  leave:
2466   xfree (sockname);
2467   if (ctx)
2468     assuan_release (ctx);
2469   if (rc)
2470     {
2471       /* We may not remove the socket as it is now in use by another
2472          server.  Setting the name to empty does this.  */
2473       if (socket_name)
2474         *socket_name = 0;
2475       if (socket_name_ssh)
2476         *socket_name_ssh = 0;
2477       shutdown_pending = 2;
2478       log_info ("this process is useless - shutting down\n");
2479     }
2480   check_own_socket_running--;
2481   return NULL;
2482 }
2483
2484
2485 /* Check whether we are still listening on our own socket.  In case
2486    another gpg-agent process started after us has taken ownership of
2487    our socket, we would linger around without any real task.  Thus we
2488    better check once in a while whether we are really needed.  */
2489 static void
2490 check_own_socket (void)
2491 {
2492   char *sockname;
2493   npth_t thread;
2494   npth_attr_t tattr;
2495   int err;
2496
2497   if (disable_check_own_socket)
2498     return;
2499
2500   if (check_own_socket_running || shutdown_pending)
2501     return;  /* Still running or already shutting down.  */
2502
2503   sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2504   if (!sockname)
2505     return; /* Out of memory.  */
2506
2507   err = npth_attr_init (&tattr);
2508   if (err)
2509     return;
2510   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2511   err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2512   if (err)
2513     log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2514   npth_attr_destroy (&tattr);
2515 }
2516
2517
2518
2519 /* Figure out whether an agent is available and running. Prints an
2520    error if not.  If SILENT is true, no messages are printed.
2521    Returns 0 if the agent is running. */
2522 static int
2523 check_for_running_agent (int silent)
2524 {
2525   gpg_error_t err;
2526   char *sockname;
2527   assuan_context_t ctx = NULL;
2528
2529   sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2530
2531   err = assuan_new (&ctx);
2532   if (!err)
2533     err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2534   xfree (sockname);
2535   if (err)
2536     {
2537       if (!silent)
2538         log_error (_("no gpg-agent running in this session\n"));
2539
2540       if (ctx)
2541         assuan_release (ctx);
2542       return -1;
2543     }
2544
2545   if (!opt.quiet && !silent)
2546     log_info ("gpg-agent running and available\n");
2547
2548   assuan_release (ctx);
2549   return 0;
2550 }