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
5 * This file is part of GnuPG.
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.
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.
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/>.
33 #ifdef HAVE_W32_SYSTEM
35 # define WINVER 0x0500 /* Same as in common/sysutils.c */
37 # ifdef HAVE_WINSOCK2_H
38 # include <winsock2.h>
42 #else /*!HAVE_W32_SYSTEM*/
43 # include <sys/socket.h>
45 #endif /*!HAVE_W32_SYSTEM*/
52 #define JNLIB_NEED_LOG_LOGV
53 #define JNLIB_NEED_AFLOCAL
55 #include <assuan.h> /* Malloc hooks and socket wrappers. */
58 #include "mkdtemp.h" /* Gnulib replacement. */
60 #include "gc-opt-flags.h"
63 #include "openpgpdefs.h" /* for PUBKEY_ALGO_ECDSA, PUBKEY_ALGO_ECDH */
64 #include "../common/init.h"
67 enum cmd_and_opt_values
107 oEnforcePassphraseConstraints,
109 oMinPassphraseNonalpha,
110 oCheckPassphrasePattern,
112 oEnablePassphraseHistory,
114 oNoUseStandardSocket,
117 oIgnoreCacheForSigning,
120 oAllowPresetPassphrase,
121 oAllowLoopbackPinentry,
127 oDisableCheckOwnSocket,
133 static ARGPARSE_OPTS opts[] = {
135 { aGPGConfList, "gpgconf-list", 256, "@" },
136 { aGPGConfTest, "gpgconf-test", 256, "@" },
137 { aUseStandardSocketP, "use-standard-socket-p", 256, "@" },
139 { 301, NULL, 0, N_("@Options:\n ") },
141 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
142 { oServer, "server", 0, N_("run in server mode (foreground)") },
143 { oVerbose, "verbose", 0, N_("verbose") },
144 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
145 { oSh, "sh", 0, N_("sh-style command output") },
146 { oCsh, "csh", 0, N_("csh-style command output") },
147 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
148 { oDebug, "debug" ,4|16, "@"},
149 { oDebugAll, "debug-all" ,0, "@"},
150 { oDebugLevel, "debug-level" ,2, "@"},
151 { oDebugWait,"debug-wait",1, "@"},
152 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
153 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
154 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
155 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
156 { oUseStandardSocket, "use-standard-socket", 0, "@"}, /* dummy */
157 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"}, /* dummy */
158 { oPinentryProgram, "pinentry-program", 2 ,
159 N_("|PGM|use PGM as the PIN-Entry program") },
160 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
161 { oScdaemonProgram, "scdaemon-program", 2 ,
162 N_("|PGM|use PGM as the SCdaemon program") },
163 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
164 { oDisableCheckOwnSocket, "disable-check-own-socket", 0, "@" },
165 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
167 { oBatch, "batch", 0, "@" },
168 { oHomedir, "homedir", 2, "@"},
170 { oDisplay, "display", 2, "@" },
171 { oTTYname, "ttyname", 2, "@" },
172 { oTTYtype, "ttytype", 2, "@" },
173 { oLCctype, "lc-ctype", 2, "@" },
174 { oLCmessages, "lc-messages", 2, "@" },
175 { oXauthority, "xauthority", 2, "@" },
176 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
177 { oKeepDISPLAY, "keep-display",
178 0, N_("ignore requests to change the X display")},
180 { oDefCacheTTL, "default-cache-ttl", 4,
181 N_("|N|expire cached PINs after N seconds")},
182 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
183 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
184 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
186 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
187 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
188 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
189 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
190 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
191 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
193 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
194 N_("do not use the PIN cache when signing")},
195 { oNoAllowMarkTrusted, "no-allow-mark-trusted", 0,
196 N_("disallow clients to mark keys as \"trusted\"")},
197 { oAllowMarkTrusted, "allow-mark-trusted", 0, "@"},
198 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
199 N_("allow presetting passphrase")},
200 { oAllowLoopbackPinentry, "allow-loopback-pinentry", 0,
201 N_("allow presetting passphrase")},
202 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh support") },
203 { oPuttySupport, "enable-putty-support", 0,
204 #ifdef HAVE_W32_SYSTEM
205 N_("enable putty support")
210 { oWriteEnvFile, "write-env-file", 2|8, "@" }, /* dummy */
215 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
216 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
217 #define MAX_CACHE_TTL (120*60) /* 2 hours */
218 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
219 #define MIN_PASSPHRASE_LEN (8)
220 #define MIN_PASSPHRASE_NONALPHA (1)
221 #define MAX_PASSPHRASE_DAYS (0)
223 /* The timer tick used for housekeeping stuff. For Windows we use a
224 longer period as the SetWaitableTimer seems to signal earlier than
225 the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
226 check our own socket in standard socket mode. If that value is 0
227 we don't check at all. All values are in seconds. */
228 #if defined(HAVE_W32CE_SYSTEM)
229 # define TIMERTICK_INTERVAL (60)
230 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
231 #elif defined(HAVE_W32_SYSTEM)
232 # define TIMERTICK_INTERVAL (4)
233 # define CHECK_OWN_SOCKET_INTERVAL (60)
235 # define TIMERTICK_INTERVAL (2)
236 # define CHECK_OWN_SOCKET_INTERVAL (60)
240 #ifdef HAVE_W32_SYSTEM
241 /* Flag indicating that support for Putty has been enabled. */
242 static int putty_support;
243 /* A magic value used with WM_COPYDATA. */
244 #define PUTTY_IPC_MAGIC 0x804e50ba
245 /* To avoid surprises we limit the size of the mapped IPC file to this
246 value. Putty currently (0.62) uses 8k, thus 16k should be enough
247 for the foreseeable future. */
248 #define PUTTY_IPC_MAXLEN 16384
249 #endif /*HAVE_W32_SYSTEM*/
251 /* The list of open file descriptors at startup. Note that this list
252 has been allocated using the standard malloc. */
253 static int *startup_fd_list;
255 /* The signal mask at startup and a flag telling whether it is valid. */
256 #ifdef HAVE_SIGPROCMASK
257 static sigset_t startup_signal_mask;
258 static int startup_signal_mask_valid;
261 /* Flag to indicate that a shutdown was requested. */
262 static int shutdown_pending;
264 /* Counter for the currently running own socket checks. */
265 static int check_own_socket_running;
267 /* Flags to indicate that check_own_socket shall not be called. */
268 static int disable_check_own_socket;
270 /* It is possible that we are currently running under setuid permissions */
271 static int maybe_setuid = 1;
273 /* Name of the communication socket used for native gpg-agent requests. */
274 static char *socket_name;
276 /* Name of the communication socket used for ssh-agent-emulation. */
277 static char *socket_name_ssh;
279 /* We need to keep track of the server's nonces (these are dummies for
281 static assuan_sock_nonce_t socket_nonce;
282 static assuan_sock_nonce_t socket_nonce_ssh;
285 /* Default values for options passed to the pinentry. */
286 static char *default_display;
287 static char *default_ttyname;
288 static char *default_ttytype;
289 static char *default_lc_ctype;
290 static char *default_lc_messages;
291 static char *default_xauthority;
293 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
294 static char *config_filename;
296 /* Helper to implement --debug-level */
297 static const char *debug_level;
299 /* Keep track of the current log file so that we can avoid updating
300 the log file after a SIGHUP if it didn't changed. Malloced. */
301 static char *current_logfile;
303 /* The handle_tick() function may test whether a parent is still
304 running. We record the PID of the parent here or -1 if it should be
306 static pid_t parent_pid = (pid_t)(-1);
308 /* Number of active connections. */
309 static int active_connections;
316 static char *create_socket_name (char *standard_name);
317 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
318 assuan_sock_nonce_t *nonce);
319 static void create_directories (void);
321 static void agent_init_default_ctrl (ctrl_t ctrl);
322 static void agent_deinit_default_ctrl (ctrl_t ctrl);
324 static void handle_connections (gnupg_fd_t listen_fd,
325 gnupg_fd_t listen_fd_ssh);
326 static void check_own_socket (void);
327 static int check_for_running_agent (int silent);
329 /* Pth wrapper function definitions. */
330 ASSUAN_SYSTEM_NPTH_IMPL;
337 /* Allocate a string describing a library version by calling a GETFNC.
338 This function is expected to be called only once. GETFNC is
339 expected to have a semantic like gcry_check_version (). */
341 make_libversion (const char *libname, const char *(*getfnc)(const char*))
348 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
352 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
353 strcpy (stpcpy (stpcpy (result, libname), " "), s);
357 /* Return strings describing this program. The case values are
358 described in common/argparse.c:strusage. The values here override
359 the default values given by strusage. */
361 my_strusage (int level)
363 static char *ver_gcry;
368 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
370 case 13: p = VERSION; break;
371 case 17: p = PRINTABLE_OS_NAME; break;
372 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
373 reporting address. This is so that we can change the
374 reporting address without breaking the translations. */
375 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
379 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
384 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
386 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
387 "Secret key management for @GNUPG@\n");
397 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
398 only the active debug flags are propagated to the subsystems. With
399 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
400 all flags already set. Note that we don't fail here, because it is
401 important to keep gpg-agent running even after re-reading the
402 options due to a SIGHUP. */
406 int numok = (debug_level && digitp (debug_level));
407 int numlvl = numok? atoi (debug_level) : 0;
411 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
413 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
414 opt.debug = DBG_ASSUAN_VALUE;
415 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
416 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
417 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
418 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
420 else if (!strcmp (debug_level, "guru") || numok)
423 /* Unless the "guru" string has been used we don't want to allow
424 hashing debugging. The rationale is that people tend to
425 select the highest debug value and would then clutter their
426 disk with debug files which may reveal confidential data. */
428 opt.debug &= ~(DBG_HASHING_VALUE);
432 log_error (_("invalid debug-level '%s' given\n"), debug_level);
433 opt.debug = 0; /* Reset debugging, so that prior debug
434 statements won't have an undesired effect. */
437 if (opt.debug && !opt.verbose)
439 if (opt.debug && opt.quiet)
442 if (opt.debug & DBG_MPI_VALUE)
443 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
444 if (opt.debug & DBG_CRYPTO_VALUE )
445 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
446 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
449 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
450 (opt.debug & DBG_COMMAND_VALUE)? " command":"",
451 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
452 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
453 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
454 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
455 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
456 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
457 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
461 /* Helper for cleanup to remove one socket with NAME. */
463 remove_socket (char *name)
470 p = strrchr (name, '/');
482 /* Cleanup code for this program. This is either called has an atexit
483 handler or directly. */
492 deinitialize_module_cache ();
493 remove_socket (socket_name);
494 remove_socket (socket_name_ssh);
499 /* Handle options which are allowed to be reset after program start.
500 Return true when the current option in PARGS could be handled and
501 false if not. As a special feature, passing a value of NULL for
502 PARGS, resets the options to the default. REREAD should be set
503 true if it is not the initial option parsing. */
505 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
513 opt.pinentry_program = NULL;
514 opt.pinentry_touch_file = NULL;
515 opt.scdaemon_program = NULL;
516 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
517 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
518 opt.max_cache_ttl = MAX_CACHE_TTL;
519 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
520 opt.enforce_passphrase_constraints = 0;
521 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
522 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
523 opt.check_passphrase_pattern = NULL;
524 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
525 opt.enable_passhrase_history = 0;
526 opt.ignore_cache_for_signing = 0;
527 opt.allow_mark_trusted = 1;
528 opt.disable_scdaemon = 0;
529 disable_check_own_socket = 0;
533 switch (pargs->r_opt)
535 case oQuiet: opt.quiet = 1; break;
536 case oVerbose: opt.verbose++; break;
538 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
539 case oDebugAll: opt.debug = ~0; break;
540 case oDebugLevel: debug_level = pargs->r.ret_str; break;
544 return 0; /* not handeld */
545 if (!current_logfile || !pargs->r.ret_str
546 || strcmp (current_logfile, pargs->r.ret_str))
548 log_set_file (pargs->r.ret_str);
549 xfree (current_logfile);
550 current_logfile = xtrystrdup (pargs->r.ret_str);
554 case oNoGrab: opt.no_grab = 1; break;
556 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
557 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
558 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
559 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
560 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
562 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
563 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
564 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
565 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
567 case oEnforcePassphraseConstraints:
568 opt.enforce_passphrase_constraints=1;
570 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
571 case oMinPassphraseNonalpha:
572 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
574 case oCheckPassphrasePattern:
575 opt.check_passphrase_pattern = pargs->r.ret_str;
577 case oMaxPassphraseDays:
578 opt.max_passphrase_days = pargs->r.ret_ulong;
580 case oEnablePassphraseHistory:
581 opt.enable_passhrase_history = 1;
584 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
586 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
587 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
589 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
591 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
594 return 0; /* not handled */
597 return 1; /* handled */
601 /* The main entry point. */
603 main (int argc, char **argv )
608 FILE *configfp = NULL;
609 char *configname = NULL;
611 unsigned configlineno;
613 int default_config =1;
618 char *logfile = NULL;
620 int gpgconf_list = 0;
622 struct assuan_malloc_hooks malloc_hooks;
624 /* Before we do anything else we save the list of currently open
625 file descriptors and the signal mask. This info is required to
626 do the exec call properly. */
627 startup_fd_list = get_all_open_fds ();
628 #ifdef HAVE_SIGPROCMASK
629 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
630 startup_signal_mask_valid = 1;
631 #endif /*HAVE_SIGPROCMASK*/
633 /* Set program name etc. */
634 set_strusage (my_strusage);
635 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
636 /* Please note that we may running SUID(ROOT), so be very CAREFUL
637 when adding any stuff between here and the call to INIT_SECMEM()
638 somewhere after the option parsing */
639 log_set_prefix (GPG_AGENT_NAME, JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
641 /* Make sure that our subsystems are ready. */
643 init_common_subsystems (&argc, &argv);
647 /* Check that the libraries are suitable. Do it here because
648 the option parsing may need services of the library. */
649 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
651 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
652 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
655 malloc_hooks.malloc = gcry_malloc;
656 malloc_hooks.realloc = gcry_realloc;
657 malloc_hooks.free = gcry_free;
658 assuan_set_malloc_hooks (&malloc_hooks);
659 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
660 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
662 setup_libassuan_logging (&opt.debug);
664 setup_libgcrypt_logging ();
665 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
667 disable_core_dumps ();
669 /* Set default options. */
670 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
672 shell = getenv ("SHELL");
673 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
676 opt.homedir = default_homedir ();
678 /* Record some of the original environment strings. */
682 static const char *names[] =
683 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
686 opt.startup_env = session_env_new ();
687 if (!opt.startup_env)
688 err = gpg_error_from_syserror ();
689 for (idx=0; !err && names[idx]; idx++)
691 s = getenv (names[idx]);
693 err = session_env_setenv (opt.startup_env, names[idx], s);
697 s = gnupg_ttyname (0);
699 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
702 log_fatal ("error recording startup environment: %s\n",
705 /* Fixme: Better use the locale function here. */
706 opt.startup_lc_ctype = getenv ("LC_CTYPE");
707 if (opt.startup_lc_ctype)
708 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
709 opt.startup_lc_messages = getenv ("LC_MESSAGES");
710 if (opt.startup_lc_messages)
711 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
714 /* Check whether we have a config file on the commandline */
719 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
720 while (arg_parse( &pargs, opts))
722 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
724 else if (pargs.r_opt == oOptions)
725 { /* yes there is one, so we do not try the default one, but
726 read the option file when it is encountered at the
730 else if (pargs.r_opt == oNoOptions)
731 default_config = 0; /* --no-options */
732 else if (pargs.r_opt == oHomedir)
733 opt.homedir = pargs.r.ret_str;
734 else if (pargs.r_opt == oDebugQuickRandom)
736 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
741 /* Initialize the secure memory. */
742 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
746 Now we are now working under our real uid
750 configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
757 pargs.flags= 1; /* do not remove the args */
762 configfp = fopen (configname, "r");
768 log_info (_("Note: no default option file '%s'\n"),
770 /* Save the default conf file name so that
771 reread_configuration is able to test whether the
772 config file has been created in the meantime. */
773 xfree (config_filename);
774 config_filename = configname;
779 log_error (_("option file '%s': %s\n"),
780 configname, strerror(errno) );
786 if (parse_debug && configname )
787 log_info (_("reading options from '%s'\n"), configname );
791 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
793 if (parse_rereadable_options (&pargs, 0))
794 continue; /* Already handled */
797 case aGPGConfList: gpgconf_list = 1; break;
798 case aGPGConfTest: gpgconf_list = 2; break;
799 case aUseStandardSocketP: gpgconf_list = 3; break;
800 case oBatch: opt.batch=1; break;
802 case oDebugWait: debug_wait = pargs.r.ret_int; break;
805 /* config files may not be nested (silently ignore them) */
809 configname = xstrdup(pargs.r.ret_str);
813 case oNoGreeting: /* Dummy option. */ break;
814 case oNoVerbose: opt.verbose = 0; break;
815 case oNoOptions: break; /* no-options */
816 case oHomedir: opt.homedir = pargs.r.ret_str; break;
817 case oNoDetach: nodetach = 1; break;
818 case oLogFile: logfile = pargs.r.ret_str; break;
819 case oCsh: csh_style = 1; break;
820 case oSh: csh_style = 0; break;
821 case oServer: pipe_server = 1; break;
822 case oDaemon: is_daemon = 1; break;
824 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
825 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
826 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
827 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
828 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
830 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
833 case oUseStandardSocket: /* dummy */ break;
834 case oNoUseStandardSocket: /* dummy */ break;
836 case oFakedSystemTime:
838 time_t faked_time = isotime2epoch (pargs.r.ret_str);
839 if (faked_time == (time_t)(-1))
840 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
841 gnupg_set_time (faked_time, 0);
845 case oKeepTTY: opt.keep_tty = 1; break;
846 case oKeepDISPLAY: opt.keep_display = 1; break;
848 case oSSHSupport: opt.ssh_support = 1; break;
850 # ifdef HAVE_W32_SYSTEM
856 case oDebugQuickRandom:
857 /* Only used by the first stage command line parser. */
860 case oWriteEnvFile: /* dummy */ break;
862 default : pargs.err = configfp? 1:2; break;
869 /* Keep a copy of the name so that it can be read on SIGHUP. */
870 if (config_filename != configname)
872 xfree (config_filename);
873 config_filename = configname;
881 if (log_get_errorcount(0))
884 /* Turn the homedir into an absolute one. */
885 opt.homedir = make_absfilename (opt.homedir, NULL);
887 /* Print a warning if an argument looks like an option. */
888 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
892 for (i=0; i < argc; i++)
893 if (argv[i][0] == '-' && argv[i][1] == '-')
894 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
898 /* gpg-agent usually does not output any messages because it runs in
899 the background. For log files it is acceptable to have messages
900 always encoded in utf-8. We switch here to utf-8, so that
901 commands like --help still give native messages. It is far
902 easier to switch only once instead of for every message and it
903 actually helps when more then one thread is active (avoids an
905 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
908 if (!pipe_server && !is_daemon && !gpgconf_list)
910 /* We have been called without any options and thus we merely
911 check whether an agent is already running. We do this right
912 here so that we don't clobber a logfile with this check but
913 print the status directly to stderr. */
916 check_for_running_agent (0);
922 if (atexit (cleanup))
924 log_error ("atexit failed\n");
929 initialize_module_cache ();
930 initialize_module_call_pinentry ();
931 initialize_module_call_scd ();
932 initialize_module_trustlist ();
934 /* Try to create missing directories. */
935 create_directories ();
937 if (debug_wait && pipe_server)
939 log_debug ("waiting for debugger - my pid is %u .....\n",
940 (unsigned int)getpid());
941 gnupg_sleep (debug_wait);
942 log_debug ("... okay\n");
945 if (gpgconf_list == 3)
947 /* We now use the standard socket always - return true for
948 backward compatibility. */
951 else if (gpgconf_list == 2)
953 else if (gpgconf_list)
958 /* List options and default values in the GPG Conf format. */
959 filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
961 filename_esc = percent_escape (filename, NULL);
963 es_printf ("%s-%s.conf:%lu:\"%s\n",
964 GPGCONF_NAME, GPG_AGENT_NAME,
965 GC_OPT_FLAG_DEFAULT, filename_esc);
967 xfree (filename_esc);
969 es_printf ("verbose:%lu:\n"
971 "debug-level:%lu:\"none:\n"
973 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
974 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
975 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
976 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
977 es_printf ("default-cache-ttl:%lu:%d:\n",
978 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
979 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
980 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
981 es_printf ("max-cache-ttl:%lu:%d:\n",
982 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
983 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
984 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
985 es_printf ("enforce-passphrase-constraints:%lu:\n",
986 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
987 es_printf ("min-passphrase-len:%lu:%d:\n",
988 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
989 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
990 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
991 MIN_PASSPHRASE_NONALPHA);
992 es_printf ("check-passphrase-pattern:%lu:\n",
993 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
994 es_printf ("max-passphrase-days:%lu:%d:\n",
995 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
996 MAX_PASSPHRASE_DAYS);
997 es_printf ("enable-passphrase-history:%lu:\n",
998 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
999 es_printf ("no-grab:%lu:\n",
1000 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1001 es_printf ("ignore-cache-for-signing:%lu:\n",
1002 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1003 es_printf ("no-allow-mark-trusted:%lu:\n",
1004 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1005 es_printf ("disable-scdaemon:%lu:\n",
1006 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1007 #ifdef HAVE_W32_SYSTEM
1008 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1010 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1016 /* Now start with logging to a file if this is desired. */
1019 log_set_file (logfile);
1020 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
1021 |JNLIB_LOG_WITH_TIME
1022 |JNLIB_LOG_WITH_PID));
1023 current_logfile = xstrdup (logfile);
1026 /* Make sure that we have a default ttyname. */
1027 if (!default_ttyname && gnupg_ttyname (1))
1028 default_ttyname = xstrdup (gnupg_ttyname (1));
1029 if (!default_ttytype && getenv ("TERM"))
1030 default_ttytype = xstrdup (getenv ("TERM"));
1035 /* This is the simple pipe based server */
1038 ctrl = xtrycalloc (1, sizeof *ctrl);
1041 log_error ("error allocating connection control data: %s\n",
1045 ctrl->session_env = session_env_new ();
1046 if (!ctrl->session_env)
1048 log_error ("error allocating session environment block: %s\n",
1053 agent_init_default_ctrl (ctrl);
1054 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1055 agent_deinit_default_ctrl (ctrl);
1058 else if (!is_daemon)
1061 { /* Regular server mode */
1066 /* Remove the DISPLAY variable so that a pinentry does not
1067 default to a specific display. There is still a default
1068 display when gpg-agent was started using --display or a
1069 client requested this using an OPTION command. Note, that we
1070 don't do this when running in reverse daemon mode (i.e. when
1071 exec the program given as arguments). */
1072 #ifndef HAVE_W32_SYSTEM
1073 if (!opt.keep_display && !argc)
1074 gnupg_unsetenv ("DISPLAY");
1078 /* Create the sockets. */
1079 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME);
1080 fd = create_server_socket (socket_name, 0, &socket_nonce);
1081 if (opt.ssh_support)
1083 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME);
1084 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
1087 fd_ssh = GNUPG_INVALID_FD;
1089 /* If we are going to exec a program in the parent, we record
1090 the PID, so that the child may check whether the program is
1093 parent_pid = getpid ();
1096 #ifdef HAVE_W32_SYSTEM
1100 #else /*!HAVE_W32_SYSTEM*/
1102 if (pid == (pid_t)-1)
1104 log_fatal ("fork failed: %s\n", strerror (errno) );
1108 { /* We are the parent */
1109 char *infostr_ssh_sock, *infostr_ssh_valid;
1111 /* Close the socket FD. */
1114 /* The signal mask might not be correct right now and thus
1115 we restore it. That is not strictly necessary but some
1116 programs falsely assume a cleared signal mask. */
1118 #ifdef HAVE_SIGPROCMASK
1119 if (startup_signal_mask_valid)
1121 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1122 log_error ("error restoring signal mask: %s\n",
1126 log_info ("no saved signal mask\n");
1127 #endif /*HAVE_SIGPROCMASK*/
1129 /* Create the SSH info string if enabled. */
1130 if (opt.ssh_support)
1132 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1133 socket_name_ssh) < 0)
1135 log_error ("out of core\n");
1136 kill (pid, SIGTERM);
1139 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1140 (unsigned long)getpid()) < 0)
1142 log_error ("out of core\n");
1143 kill (pid, SIGTERM);
1148 *socket_name = 0; /* Don't let cleanup() remove the socket -
1149 the child should do this from now on */
1150 if (opt.ssh_support)
1151 *socket_name_ssh = 0;
1154 { /* Run the program given on the commandline. */
1155 if (opt.ssh_support && (putenv (infostr_ssh_sock)
1156 || putenv (infostr_ssh_valid)))
1158 log_error ("failed to set environment: %s\n",
1160 kill (pid, SIGTERM );
1164 /* Close all the file descriptors except the standard
1165 ones and those open at startup. We explicitly don't
1166 close 0,1,2 in case something went wrong collecting
1168 close_all_fds (3, startup_fd_list);
1170 /* Run the command. */
1171 execvp (argv[0], argv);
1172 log_error ("failed to run the command: %s\n", strerror (errno));
1173 kill (pid, SIGTERM);
1178 /* Print the environment string, so that the caller can use
1179 shell's eval to set it */
1182 if (opt.ssh_support)
1184 *strchr (infostr_ssh_sock, '=') = ' ';
1185 es_printf ("setenv %s;\n", infostr_ssh_sock);
1190 if (opt.ssh_support)
1192 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1196 if (opt.ssh_support)
1198 xfree (infostr_ssh_sock);
1199 xfree (infostr_ssh_valid);
1210 /* Detach from tty and put process into a new session */
1214 unsigned int oldflags;
1216 /* Close stdin, stdout and stderr unless it is the log stream */
1217 for (i=0; i <= 2; i++)
1219 if (!log_test_fd (i) && i != fd )
1222 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1224 log_error ("failed to open '%s': %s\n",
1225 "/dev/null", strerror (errno));
1233 log_error ("setsid() failed: %s\n", strerror(errno) );
1238 log_get_prefix (&oldflags);
1239 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1240 opt.running_detached = 1;
1245 log_error ("chdir to / failed: %s\n", strerror (errno));
1250 struct sigaction sa;
1252 sa.sa_handler = SIG_IGN;
1253 sigemptyset (&sa.sa_mask);
1255 sigaction (SIGPIPE, &sa, NULL);
1257 #endif /*!HAVE_W32_SYSTEM*/
1259 log_info ("%s %s started\n", strusage(11), strusage(13) );
1260 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1261 assuan_sock_close (fd);
1268 /* Exit entry point. This function should be called instead of a
1273 /*FIXME: update_random_seed_file();*/
1275 /* We run our cleanup handler because that may close cipher contexts
1276 stored in secure memory and thus this needs to be done before we
1277 explicitly terminate secure memory. */
1281 /* at this time a bit annoying */
1282 if (opt.debug & DBG_MEMSTAT_VALUE)
1284 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1285 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1288 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1290 gcry_control (GCRYCTL_TERM_SECMEM );
1291 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1296 /* Each thread has its own local variables conveyed by a control
1297 structure usually identified by an argument named CTRL. This
1298 function is called immediately after allocating the control
1299 structure. Its purpose is to setup the default values for that
1302 agent_init_default_ctrl (ctrl_t ctrl)
1304 assert (ctrl->session_env);
1306 /* Note we ignore malloc errors because we can't do much about it
1307 and the request will fail anyway shortly after this
1309 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1310 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1311 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1312 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1313 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1316 xfree (ctrl->lc_ctype);
1317 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1319 if (ctrl->lc_messages)
1320 xfree (ctrl->lc_messages);
1321 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1323 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1327 /* Release all resources allocated by default in the control
1328 structure. This is the counterpart to agent_init_default_ctrl. */
1330 agent_deinit_default_ctrl (ctrl_t ctrl)
1332 session_env_release (ctrl->session_env);
1335 xfree (ctrl->lc_ctype);
1336 if (ctrl->lc_messages)
1337 xfree (ctrl->lc_messages);
1341 /* Reread parts of the configuration. Note, that this function is
1342 obviously not thread-safe and should only be called from the PTH
1345 Fixme: Due to the way the argument parsing works, we create a
1346 memory leak here for all string type arguments. There is currently
1347 no clean way to tell whether the memory for the argument has been
1348 allocated or points into the process' original arguments. Unless
1349 we have a mechanism to tell this, we need to live on with this. */
1351 reread_configuration (void)
1353 ARGPARSE_ARGS pargs;
1355 unsigned int configlineno = 0;
1358 if (!config_filename)
1359 return; /* No config file. */
1361 fp = fopen (config_filename, "r");
1364 log_info (_("option file '%s': %s\n"),
1365 config_filename, strerror(errno) );
1369 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1371 memset (&pargs, 0, sizeof pargs);
1373 pargs.argc = &dummy;
1374 pargs.flags = 1; /* do not remove the args */
1375 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1377 if (pargs.r_opt < -1)
1378 pargs.err = 1; /* Print a warning. */
1379 else /* Try to parse this option - ignore unchangeable ones. */
1380 parse_rereadable_options (&pargs, 1);
1387 /* Return the file name of the socket we are using for native
1390 get_agent_socket_name (void)
1392 const char *s = socket_name;
1394 return (s && *s)? s : NULL;
1397 /* Return the file name of the socket we are using for SSH
1400 get_agent_ssh_socket_name (void)
1402 const char *s = socket_name_ssh;
1404 return (s && *s)? s : NULL;
1408 /* Under W32, this function returns the handle of the scdaemon
1409 notification event. Calling it the first time creates that
1411 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1413 get_agent_scd_notify_event (void)
1415 static HANDLE the_event = INVALID_HANDLE_VALUE;
1417 if (the_event == INVALID_HANDLE_VALUE)
1420 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1422 /* We need to use a manual reset event object due to the way our
1423 w32-pth wait function works: If we would use an automatic
1424 reset event we are not able to figure out which handle has
1425 been signaled because at the time we single out the signaled
1426 handles using WFSO the event has already been reset due to
1428 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1430 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1431 else if (!DuplicateHandle (GetCurrentProcess(), h,
1432 GetCurrentProcess(), &h2,
1433 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1435 log_error ("setting syncronize for scd notify event failed: %s\n",
1436 w32_strerror (-1) );
1448 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1452 /* Create a name for the socket in the home directory as using
1453 STANDARD_NAME. We also check for valid characters as well as
1454 against a maximum allowed length for a unix domain socket is done.
1455 The function terminates the process in case of an error. Returns:
1456 Pointer to an allocated string with the absolute name of the socket
1459 create_socket_name (char *standard_name)
1463 name = make_filename (opt.homedir, standard_name, NULL);
1464 if (strchr (name, PATHSEP_C))
1466 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1469 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1471 log_error (_("name of socket too long\n"));
1479 /* Create a Unix domain socket with NAME. Returns the file descriptor
1480 or terminates the process in case of an error. Not that this
1481 function needs to be used for the regular socket first and only
1482 then for the ssh socket. */
1484 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1486 struct sockaddr_un *serv_addr;
1491 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1492 if (fd == ASSUAN_INVALID_FD)
1494 log_error (_("can't create socket: %s\n"), strerror (errno));
1498 serv_addr = xmalloc (sizeof (*serv_addr));
1499 memset (serv_addr, 0, sizeof *serv_addr);
1500 serv_addr->sun_family = AF_UNIX;
1501 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1503 log_error (_("socket name '%s' is too long\n"), name);
1506 strcpy (serv_addr->sun_path, name);
1507 len = SUN_LEN (serv_addr);
1508 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1510 /* Our error code mapping on W32CE returns EEXIST thus we also test
1513 && (errno == EADDRINUSE
1514 #ifdef HAVE_W32_SYSTEM
1519 /* Check whether a gpg-agent is already running.
1520 We do this test only if this is not the ssh socket.
1521 For ssh we assume that a test for gpg-agent has already been
1522 done and reuse the requested ssh socket. Testing the
1523 ssh-socket is not possible because at this point, though we
1524 know the new Assuan socket, the Assuan server and thus the
1525 ssh-agent server is not yet operational. This would lead to
1527 if (!is_ssh && !check_for_running_agent (1))
1529 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
1530 log_set_file (NULL);
1531 log_error (_("a gpg-agent is already running - "
1532 "not starting a new one\n"));
1533 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1534 assuan_sock_close (fd);
1537 gnupg_remove (name);
1538 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1541 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1542 log_error (_("error getting nonce for the socket\n"));
1545 /* We use gpg_strerror here because it allows us to get strings
1546 for some W32 socket error codes. */
1547 log_error (_("error binding socket to '%s': %s\n"),
1548 serv_addr->sun_path,
1549 gpg_strerror (gpg_error_from_errno (errno)));
1551 assuan_sock_close (fd);
1552 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1556 if (listen (FD2INT(fd), 5 ) == -1)
1558 log_error (_("listen() failed: %s\n"), strerror (errno));
1559 assuan_sock_close (fd);
1564 log_info (_("listening on socket '%s'\n"), serv_addr->sun_path);
1570 /* Check that the directory for storing the private keys exists and
1571 create it if not. This function won't fail as it is only a
1572 convenience function and not strictly necessary. */
1574 create_private_keys_directory (const char *home)
1577 struct stat statbuf;
1579 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1580 if (stat (fname, &statbuf) && errno == ENOENT)
1582 if (gnupg_mkdir (fname, "-rwx"))
1583 log_error (_("can't create directory '%s': %s\n"),
1584 fname, strerror (errno) );
1585 else if (!opt.quiet)
1586 log_info (_("directory '%s' created\n"), fname);
1591 /* Create the directory only if the supplied directory name is the
1592 same as the default one. This way we avoid to create arbitrary
1593 directories when a non-default home directory is used. To cope
1594 with HOME, we compare only the suffix if we see that the default
1595 homedir does start with a tilde. We don't stop here in case of
1596 problems because other functions will throw an error anyway.*/
1598 create_directories (void)
1600 struct stat statbuf;
1601 const char *defhome = standard_homedir ();
1604 home = make_filename (opt.homedir, NULL);
1605 if ( stat (home, &statbuf) )
1607 if (errno == ENOENT)
1610 #ifdef HAVE_W32_SYSTEM
1611 ( !compare_filenames (home, defhome) )
1614 && (strlen (home) >= strlen (defhome+1)
1615 && !strcmp (home + strlen(home)
1616 - strlen (defhome+1), defhome+1)))
1617 || (*defhome != '~' && !strcmp (home, defhome) )
1621 if (gnupg_mkdir (home, "-rwx"))
1622 log_error (_("can't create directory '%s': %s\n"),
1623 home, strerror (errno) );
1627 log_info (_("directory '%s' created\n"), home);
1628 create_private_keys_directory (home);
1633 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1635 else if ( !S_ISDIR(statbuf.st_mode))
1637 log_error (_("can't use '%s' as home directory\n"), home);
1639 else /* exists and is a directory. */
1641 create_private_keys_directory (home);
1648 /* This is the worker for the ticker. It is called every few seconds
1649 and may only do fast operations. */
1653 static time_t last_minute;
1656 last_minute = time (NULL);
1658 /* Check whether the scdaemon has died and cleanup in this case. */
1659 agent_scd_check_aliveness ();
1661 /* If we are running as a child of another process, check whether
1662 the parent is still alive and shutdown if not. */
1663 #ifndef HAVE_W32_SYSTEM
1664 if (parent_pid != (pid_t)(-1))
1666 if (kill (parent_pid, 0))
1668 shutdown_pending = 2;
1669 log_info ("parent process died - shutting down\n");
1670 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1675 #endif /*HAVE_W32_SYSTEM*/
1677 /* Code to be run from time to time. */
1678 #if CHECK_OWN_SOCKET_INTERVAL > 0
1679 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
1681 check_own_socket ();
1682 last_minute = time (NULL);
1689 /* A global function which allows us to call the reload stuff from
1690 other places too. This is only used when build for W32. */
1692 agent_sighup_action (void)
1694 log_info ("SIGHUP received - "
1695 "re-reading configuration and flushing cache\n");
1696 agent_flush_cache ();
1697 reread_configuration ();
1698 agent_reload_trustlist ();
1702 /* A helper function to handle SIGUSR2. */
1704 agent_sigusr2_action (void)
1707 log_info ("SIGUSR2 received - updating card event counter\n");
1708 /* Nothing to check right now. We only increment a counter. */
1709 bump_card_eventcounter ();
1713 #ifndef HAVE_W32_SYSTEM
1714 /* The signal handler for this program. It is expected to be run in
1715 its own trhead and not in the context of a signal handler. */
1717 handle_signal (int signo)
1721 #ifndef HAVE_W32_SYSTEM
1723 agent_sighup_action ();
1727 log_info ("SIGUSR1 received - printing internal information:\n");
1728 /* Fixme: We need to see how to integrate pth dumping into our
1730 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1731 agent_query_dump_state ();
1732 agent_scd_dump_state ();
1736 agent_sigusr2_action ();
1740 if (!shutdown_pending)
1741 log_info ("SIGTERM received - shutting down ...\n");
1743 log_info ("SIGTERM received - still %i open connections\n",
1744 active_connections);
1746 if (shutdown_pending > 2)
1748 log_info ("shutdown forced\n");
1749 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1756 log_info ("SIGINT received - immediate shutdown\n");
1757 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1763 log_info ("signal %d received - no action defined\n", signo);
1768 /* Check the nonce on a new connection. This is a NOP unless we we
1769 are using our Unix domain socket emulation under Windows. */
1771 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1773 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1775 log_info (_("error reading nonce on fd %d: %s\n"),
1776 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1777 assuan_sock_close (ctrl->thread_startup.fd);
1786 #ifdef HAVE_W32_SYSTEM
1787 /* The window message processing function for Putty. Warning: This
1788 code runs as a native Windows thread. Use of our own functions
1789 needs to be bracket with pth_leave/pth_enter. */
1790 static LRESULT CALLBACK
1791 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1795 COPYDATASTRUCT *cds;
1796 const char *mapfile;
1801 PSECURITY_DESCRIPTOR psd = NULL;
1804 if (msg != WM_COPYDATA)
1806 return DefWindowProc (hwnd, msg, wparam, lparam);
1809 cds = (COPYDATASTRUCT*)lparam;
1810 if (cds->dwData != PUTTY_IPC_MAGIC)
1811 return 0; /* Ignore data with the wrong magic. */
1812 mapfile = cds->lpData;
1813 if (!cds->cbData || mapfile[cds->cbData - 1])
1814 return 0; /* Ignore empty and non-properly terminated strings. */
1819 log_debug ("ssh map file '%s'", mapfile);
1823 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
1827 log_debug ("ssh map handle %p\n", maphd);
1831 if (!maphd || maphd == INVALID_HANDLE_VALUE)
1836 mysid = w32_get_user_sid ();
1839 log_error ("error getting my sid\n");
1843 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
1844 OWNER_SECURITY_INFORMATION,
1845 &mapsid, NULL, NULL, NULL,
1849 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
1857 if (!ConvertSidToStringSid (mysid, &sidstr))
1859 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
1861 if (!ConvertSidToStringSid (mapsid, &sidstr))
1863 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
1867 if (!EqualSid (mysid, mapsid))
1869 log_error ("ssh map file has a non-matching sid\n");
1873 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
1875 log_debug ("ssh IPC buffer at %p\n", data);
1879 /* log_printhex ("request:", data, 20); */
1881 ctrl = xtrycalloc (1, sizeof *ctrl);
1884 log_error ("error allocating connection control data: %s\n",
1888 ctrl->session_env = session_env_new ();
1889 if (!ctrl->session_env)
1891 log_error ("error allocating session environment block: %s\n",
1896 agent_init_default_ctrl (ctrl);
1897 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
1898 ret = 1; /* Valid ssh message has been constructed. */
1899 agent_deinit_default_ctrl (ctrl);
1900 /* log_printhex (" reply:", data, 20); */
1905 UnmapViewOfFile (data);
1910 CloseHandle (maphd);
1916 #endif /*HAVE_W32_SYSTEM*/
1919 #ifdef HAVE_W32_SYSTEM
1920 /* The thread handling Putty's IPC requests. */
1922 putty_message_thread (void *arg)
1924 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
1925 NULL, NULL, NULL, NULL, NULL, "Pageant"};
1932 log_info ("putty message loop thread started\n");
1934 /* The message loop runs as thread independent from our nPth system.
1935 This also means that we need to make sure that we switch back to
1936 our system before calling any no-windows function. */
1939 /* First create a window to make sure that a message queue exists
1941 if (!RegisterClass (&wndwclass))
1944 log_error ("error registering Pageant window class");
1947 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
1949 HWND_MESSAGE, /* hWndParent */
1950 NULL, /* hWndMenu */
1951 NULL, /* hInstance */
1956 log_error ("error creating Pageant window");
1960 while (GetMessage(&msg, NULL, 0, 0))
1962 TranslateMessage(&msg);
1963 DispatchMessage(&msg);
1970 log_info ("putty message loop thread stopped\n");
1973 #endif /*HAVE_W32_SYSTEM*/
1976 /* This is the standard connection thread's main function. */
1978 start_connection_thread (void *arg)
1982 if (check_nonce (ctrl, &socket_nonce))
1984 log_error ("handler 0x%lx nonce check FAILED\n",
1985 (unsigned long) npth_self());
1989 agent_init_default_ctrl (ctrl);
1991 log_info (_("handler 0x%lx for fd %d started\n"),
1992 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
1994 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1996 log_info (_("handler 0x%lx for fd %d terminated\n"),
1997 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
1999 agent_deinit_default_ctrl (ctrl);
2005 /* This is the ssh connection thread's main function. */
2007 start_connection_thread_ssh (void *arg)
2011 if (check_nonce (ctrl, &socket_nonce_ssh))
2014 agent_init_default_ctrl (ctrl);
2016 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2017 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2019 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2021 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2022 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2024 agent_deinit_default_ctrl (ctrl);
2030 /* Connection handler loop. Wait for connection requests and spawn a
2031 thread after accepting a connection. */
2033 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
2036 struct sockaddr_un paddr;
2038 fd_set fdset, read_fdset;
2043 struct timespec abstime;
2044 struct timespec curtime;
2045 struct timespec timeout;
2046 #ifdef HAVE_W32_SYSTEM
2048 unsigned int events_set;
2051 ret = npth_attr_init(&tattr);
2053 log_fatal ("error allocating thread attributes: %s\n",
2055 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2057 #ifndef HAVE_W32_SYSTEM
2059 npth_sigev_add (SIGHUP);
2060 npth_sigev_add (SIGUSR1);
2061 npth_sigev_add (SIGUSR2);
2062 npth_sigev_add (SIGINT);
2063 npth_sigev_add (SIGTERM);
2066 # ifdef HAVE_W32CE_SYSTEM
2067 /* Use a dummy event. */
2069 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2071 events[0] = get_agent_scd_notify_event ();
2072 events[1] = INVALID_HANDLE_VALUE;
2076 /* On Windows we need to fire up a separate thread to listen for
2077 requests from Putty (an SSH client), so we can replace Putty's
2078 Pageant (its ssh-agent implementation). */
2079 #ifdef HAVE_W32_SYSTEM
2084 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2087 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2090 #endif /*HAVE_W32_SYSTEM*/
2092 /* Set a flag to tell call-scd.c that it may enable event
2094 opt.sigusr2_enabled = 1;
2097 FD_SET (FD2INT (listen_fd), &fdset);
2098 nfd = FD2INT (listen_fd);
2099 if (listen_fd_ssh != GNUPG_INVALID_FD)
2101 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2102 if (FD2INT (listen_fd_ssh) > nfd)
2103 nfd = FD2INT (listen_fd_ssh);
2106 npth_clock_gettime (&abstime);
2107 abstime.tv_sec += TIMERTICK_INTERVAL;
2111 /* Shutdown test. */
2112 if (shutdown_pending)
2114 if (active_connections == 0)
2117 /* Do not accept new connections but keep on running the
2118 loop to cope with the timer events. */
2122 /* POSIX says that fd_set should be implemented as a structure,
2123 thus a simple assignment is fine to copy the entire set. */
2126 npth_clock_gettime (&curtime);
2127 if (!(npth_timercmp (&curtime, &abstime, <)))
2131 npth_clock_gettime (&abstime);
2132 abstime.tv_sec += TIMERTICK_INTERVAL;
2134 npth_timersub (&abstime, &curtime, &timeout);
2136 #ifndef HAVE_W32_SYSTEM
2137 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2138 npth_sigev_sigmask ());
2139 saved_errno = errno;
2143 while (npth_sigev_get_pending (&signo))
2144 handle_signal (signo);
2147 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2148 events, &events_set);
2149 saved_errno = errno;
2151 /* This is valid even if npth_eselect returns an error. */
2153 agent_sigusr2_action ();
2156 if (ret == -1 && saved_errno != EINTR)
2158 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2159 strerror (saved_errno));
2164 /* Interrupt or timeout. Will be handled when calculating the
2168 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
2172 plen = sizeof paddr;
2173 fd = INT2FD (npth_accept (FD2INT(listen_fd),
2174 (struct sockaddr *)&paddr, &plen));
2175 if (fd == GNUPG_INVALID_FD)
2177 log_error ("accept failed: %s\n", strerror (errno));
2179 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2181 log_error ("error allocating connection control data: %s\n",
2183 assuan_sock_close (fd);
2185 else if ( !(ctrl->session_env = session_env_new ()) )
2187 log_error ("error allocating session environment block: %s\n",
2190 assuan_sock_close (fd);
2196 ctrl->thread_startup.fd = fd;
2197 ret = npth_create (&thread, &tattr,
2198 start_connection_thread, ctrl);
2201 log_error ("error spawning connection handler: %s\n",
2203 assuan_sock_close (fd);
2208 fd = GNUPG_INVALID_FD;
2211 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
2212 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
2216 plen = sizeof paddr;
2217 fd = INT2FD(npth_accept (FD2INT(listen_fd_ssh),
2218 (struct sockaddr *)&paddr, &plen));
2219 if (fd == GNUPG_INVALID_FD)
2221 log_error ("accept failed for ssh: %s\n", strerror (errno));
2223 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2225 log_error ("error allocating connection control data: %s\n",
2227 assuan_sock_close (fd);
2229 else if ( !(ctrl->session_env = session_env_new ()) )
2231 log_error ("error allocating session environment block: %s\n",
2234 assuan_sock_close (fd);
2240 agent_init_default_ctrl (ctrl);
2241 ctrl->thread_startup.fd = fd;
2242 ret = npth_create (&thread, &tattr,
2243 start_connection_thread_ssh, ctrl);
2246 log_error ("error spawning ssh connection handler: %s\n",
2248 assuan_sock_close (fd);
2252 fd = GNUPG_INVALID_FD;
2257 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2258 npth_attr_destroy (&tattr);
2263 /* Helper for check_own_socket. */
2265 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2267 membuf_t *mb = opaque;
2268 put_membuf (mb, buffer, length);
2273 /* The thread running the actual check. We need to run this in a
2274 separate thread so that check_own_thread can be called from the
2277 check_own_socket_thread (void *arg)
2280 char *sockname = arg;
2281 assuan_context_t ctx = NULL;
2285 check_own_socket_running++;
2287 rc = assuan_new (&ctx);
2290 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2294 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2297 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2301 init_membuf (&mb, 100);
2302 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2303 NULL, NULL, NULL, NULL);
2304 put_membuf (&mb, "", 1);
2305 buffer = get_membuf (&mb, NULL);
2308 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2309 "GETINFO pid", gpg_strerror (rc));
2312 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2314 log_error ("socket is now serviced by another server\n");
2317 else if (opt.verbose > 1)
2318 log_error ("socket is still served by this server\n");
2325 assuan_release (ctx);
2328 /* We may not remove the socket as it is now in use by another
2329 server. Setting the name to empty does this. */
2332 if (socket_name_ssh)
2333 *socket_name_ssh = 0;
2334 shutdown_pending = 2;
2335 log_info ("this process is useless - shutting down\n");
2337 check_own_socket_running--;
2342 /* Check whether we are still listening on our own socket. In case
2343 another gpg-agent process started after us has taken ownership of
2344 our socket, we would linger around without any real task. Thus we
2345 better check once in a while whether we are really needed. */
2347 check_own_socket (void)
2354 if (disable_check_own_socket)
2357 if (check_own_socket_running || shutdown_pending)
2358 return; /* Still running or already shutting down. */
2360 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2362 return; /* Out of memory. */
2364 err = npth_attr_init (&tattr);
2367 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2368 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2370 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2371 npth_attr_destroy (&tattr);
2376 /* Figure out whether an agent is available and running. Prints an
2377 error if not. If SILENT is true, no messages are printed.
2378 Returns 0 if the agent is running. */
2380 check_for_running_agent (int silent)
2384 assuan_context_t ctx = NULL;
2386 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2388 err = assuan_new (&ctx);
2390 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2395 log_error (_("no gpg-agent running in this session\n"));
2398 assuan_release (ctx);
2402 if (!opt.quiet && !silent)
2403 log_info ("gpg-agent running and available\n");
2405 assuan_release (ctx);