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