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 GNUPG_COMMON_NEED_AFLOCAL
54 #include <assuan.h> /* Malloc hooks and socket wrappers. */
58 #include "gc-opt-flags.h"
61 #include "openpgpdefs.h" /* for PUBKEY_ALGO_ECDSA, PUBKEY_ALGO_ECDH */
62 #include "../common/init.h"
65 enum cmd_and_opt_values
106 oEnforcePassphraseConstraints,
108 oMinPassphraseNonalpha,
109 oCheckPassphrasePattern,
111 oEnablePassphraseHistory,
113 oNoUseStandardSocket,
118 oIgnoreCacheForSigning,
121 oAllowPresetPassphrase,
122 oAllowLoopbackPinentry,
123 oNoAllowExternalCache,
130 oDisableCheckOwnSocket,
136 # define ENAMETOOLONG EINVAL
140 static ARGPARSE_OPTS opts[] = {
142 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
143 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
144 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
146 ARGPARSE_group (301, N_("@Options:\n ")),
148 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
149 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
150 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
151 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
152 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
153 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
154 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
156 ARGPARSE_s_u (oDebug, "debug", "@"),
157 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
158 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
159 ARGPARSE_s_i (oDebugWait," debug-wait", "@"),
160 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
161 ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
163 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
164 ARGPARSE_s_n (oNoGrab, "no-grab", N_("do not grab keyboard and mouse")),
165 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
166 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
167 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
168 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
169 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
170 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
171 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
172 /* */ N_("do not use the SCdaemon") ),
173 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
175 ARGPARSE_s_s (oExtraSocket, "extra-socket",
176 /* */ N_("|NAME|accept some commands via NAME")),
178 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
180 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
182 ARGPARSE_s_n (oBatch, "batch", "@"),
183 ARGPARSE_s_s (oHomedir, "homedir", "@"),
185 ARGPARSE_s_s (oDisplay, "display", "@"),
186 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
187 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
188 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
189 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
190 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
191 ARGPARSE_s_n (oKeepTTY, "keep-tty",
192 /* */ N_("ignore requests to change the TTY")),
193 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
194 /* */ N_("ignore requests to change the X display")),
196 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
197 N_("|N|expire cached PINs after N seconds")),
198 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
199 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
200 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
202 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
204 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
205 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
206 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
207 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
208 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
210 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
211 /* */ N_("do not use the PIN cache when signing")),
212 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
213 /* */ N_("disallow the use of an external password cache")),
214 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
215 /* */ N_("disallow clients to mark keys as \"trusted\"")),
216 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
217 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
218 /* */ N_("allow presetting passphrase")),
219 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry",
220 N_("allow caller to override the pinentry")),
221 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
222 /* */ N_("allow passphrase to be prompted through Emacs")),
224 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
225 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
226 #ifdef HAVE_W32_SYSTEM
227 /* */ N_("enable putty support")
233 /* Dummy options for backward compatibility. */
234 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
235 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
236 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
238 {0} /* End of list */
242 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
243 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
244 #define MAX_CACHE_TTL (120*60) /* 2 hours */
245 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
246 #define MIN_PASSPHRASE_LEN (8)
247 #define MIN_PASSPHRASE_NONALPHA (1)
248 #define MAX_PASSPHRASE_DAYS (0)
250 /* The timer tick used for housekeeping stuff. For Windows we use a
251 longer period as the SetWaitableTimer seems to signal earlier than
252 the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
253 check our own socket in standard socket mode. If that value is 0
254 we don't check at all. All values are in seconds. */
255 #if defined(HAVE_W32CE_SYSTEM)
256 # define TIMERTICK_INTERVAL (60)
257 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
258 #elif defined(HAVE_W32_SYSTEM)
259 # define TIMERTICK_INTERVAL (4)
260 # define CHECK_OWN_SOCKET_INTERVAL (60)
262 # define TIMERTICK_INTERVAL (2)
263 # define CHECK_OWN_SOCKET_INTERVAL (60)
267 #ifdef HAVE_W32_SYSTEM
268 /* Flag indicating that support for Putty has been enabled. */
269 static int putty_support;
270 /* A magic value used with WM_COPYDATA. */
271 #define PUTTY_IPC_MAGIC 0x804e50ba
272 /* To avoid surprises we limit the size of the mapped IPC file to this
273 value. Putty currently (0.62) uses 8k, thus 16k should be enough
274 for the foreseeable future. */
275 #define PUTTY_IPC_MAXLEN 16384
276 #endif /*HAVE_W32_SYSTEM*/
278 /* The list of open file descriptors at startup. Note that this list
279 has been allocated using the standard malloc. */
280 static int *startup_fd_list;
282 /* The signal mask at startup and a flag telling whether it is valid. */
283 #ifdef HAVE_SIGPROCMASK
284 static sigset_t startup_signal_mask;
285 static int startup_signal_mask_valid;
288 /* Flag to indicate that a shutdown was requested. */
289 static int shutdown_pending;
291 /* Counter for the currently running own socket checks. */
292 static int check_own_socket_running;
294 /* Flags to indicate that check_own_socket shall not be called. */
295 static int disable_check_own_socket;
297 /* It is possible that we are currently running under setuid permissions */
298 static int maybe_setuid = 1;
300 /* Name of the communication socket used for native gpg-agent
301 requests. The second variable is either NULL or a malloced string
302 with the real socket name in case it has been redirected. */
303 static char *socket_name;
304 static char *redir_socket_name;
306 /* Name of the optional extra socket used for native gpg-agent requests. */
307 static char *socket_name_extra;
308 static char *redir_socket_name_extra;
310 /* Name of the optional browser socket used for native gpg-agent requests. */
311 static char *socket_name_browser;
312 static char *redir_socket_name_browser;
314 /* Name of the communication socket used for ssh-agent-emulation. */
315 static char *socket_name_ssh;
316 static char *redir_socket_name_ssh;
318 /* We need to keep track of the server's nonces (these are dummies for
320 static assuan_sock_nonce_t socket_nonce;
321 static assuan_sock_nonce_t socket_nonce_extra;
322 static assuan_sock_nonce_t socket_nonce_browser;
323 static assuan_sock_nonce_t socket_nonce_ssh;
326 /* Default values for options passed to the pinentry. */
327 static char *default_display;
328 static char *default_ttyname;
329 static char *default_ttytype;
330 static char *default_lc_ctype;
331 static char *default_lc_messages;
332 static char *default_xauthority;
334 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
335 static char *config_filename;
337 /* Helper to implement --debug-level */
338 static const char *debug_level;
340 /* Keep track of the current log file so that we can avoid updating
341 the log file after a SIGHUP if it didn't changed. Malloced. */
342 static char *current_logfile;
344 /* The handle_tick() function may test whether a parent is still
345 running. We record the PID of the parent here or -1 if it should be
347 static pid_t parent_pid = (pid_t)(-1);
349 /* Number of active connections. */
350 static int active_connections;
357 static char *create_socket_name (char *standard_name, int with_homedir);
358 static gnupg_fd_t create_server_socket (char *name, int primary,
360 assuan_sock_nonce_t *nonce);
361 static void create_directories (void);
363 static void agent_init_default_ctrl (ctrl_t ctrl);
364 static void agent_deinit_default_ctrl (ctrl_t ctrl);
366 static void handle_connections (gnupg_fd_t listen_fd,
367 gnupg_fd_t listen_fd_extra,
368 gnupg_fd_t listen_fd_browser,
369 gnupg_fd_t listen_fd_ssh);
370 static void check_own_socket (void);
371 static int check_for_running_agent (int silent);
373 /* Pth wrapper function definitions. */
374 ASSUAN_SYSTEM_NPTH_IMPL;
381 /* Allocate a string describing a library version by calling a GETFNC.
382 This function is expected to be called only once. GETFNC is
383 expected to have a semantic like gcry_check_version (). */
385 make_libversion (const char *libname, const char *(*getfnc)(const char*))
392 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
396 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
397 strcpy (stpcpy (stpcpy (result, libname), " "), s);
401 /* Return strings describing this program. The case values are
402 described in common/argparse.c:strusage. The values here override
403 the default values given by strusage. */
405 my_strusage (int level)
407 static char *ver_gcry;
412 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
414 case 13: p = VERSION; break;
415 case 17: p = PRINTABLE_OS_NAME; break;
416 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
417 reporting address. This is so that we can change the
418 reporting address without breaking the translations. */
419 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
423 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
428 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
430 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
431 "Secret key management for @GNUPG@\n");
441 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
442 only the active debug flags are propagated to the subsystems. With
443 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
444 all flags already set. Note that we don't fail here, because it is
445 important to keep gpg-agent running even after re-reading the
446 options due to a SIGHUP. */
450 int numok = (debug_level && digitp (debug_level));
451 int numlvl = numok? atoi (debug_level) : 0;
455 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
457 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
458 opt.debug = DBG_IPC_VALUE;
459 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
460 opt.debug = DBG_IPC_VALUE|DBG_COMMAND_VALUE;
461 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
462 opt.debug = (DBG_IPC_VALUE|DBG_COMMAND_VALUE
464 else if (!strcmp (debug_level, "guru") || numok)
467 /* Unless the "guru" string has been used we don't want to allow
468 hashing debugging. The rationale is that people tend to
469 select the highest debug value and would then clutter their
470 disk with debug files which may reveal confidential data. */
472 opt.debug &= ~(DBG_HASHING_VALUE);
476 log_error (_("invalid debug-level '%s' given\n"), debug_level);
477 opt.debug = 0; /* Reset debugging, so that prior debug
478 statements won't have an undesired effect. */
481 if (opt.debug && !opt.verbose)
483 if (opt.debug && opt.quiet)
486 if (opt.debug & DBG_MPI_VALUE)
487 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
488 if (opt.debug & DBG_CRYPTO_VALUE )
489 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
490 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
493 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
494 (opt.debug & DBG_COMMAND_VALUE)? " command":"",
495 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
496 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
497 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
498 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
499 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
500 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
501 (opt.debug & DBG_IPC_VALUE )? " ipc":"");
505 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
506 the corresponding real name if the socket has been redirected. */
508 remove_socket (char *name, char *redir_name)
518 p = strrchr (name, '/');
530 /* Cleanup code for this program. This is either called has an atexit
531 handler or directly. */
540 deinitialize_module_cache ();
541 remove_socket (socket_name, redir_socket_name);
542 if (opt.extra_socket > 1)
543 remove_socket (socket_name_extra, redir_socket_name_extra);
544 if (opt.browser_socket > 1)
545 remove_socket (socket_name_browser, redir_socket_name_browser);
546 remove_socket (socket_name_ssh, redir_socket_name_ssh);
551 /* Handle options which are allowed to be reset after program start.
552 Return true when the current option in PARGS could be handled and
553 false if not. As a special feature, passing a value of NULL for
554 PARGS, resets the options to the default. REREAD should be set
555 true if it is not the initial option parsing. */
557 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
565 opt.debug_pinentry = 0;
566 opt.pinentry_program = NULL;
567 opt.pinentry_touch_file = NULL;
568 opt.scdaemon_program = NULL;
569 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
570 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
571 opt.max_cache_ttl = MAX_CACHE_TTL;
572 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
573 opt.enforce_passphrase_constraints = 0;
574 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
575 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
576 opt.check_passphrase_pattern = NULL;
577 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
578 opt.enable_passhrase_history = 0;
579 opt.ignore_cache_for_signing = 0;
580 opt.allow_mark_trusted = 1;
581 opt.allow_external_cache = 1;
582 opt.allow_emacs_pinentry = 0;
583 opt.disable_scdaemon = 0;
584 disable_check_own_socket = 0;
588 switch (pargs->r_opt)
590 case oQuiet: opt.quiet = 1; break;
591 case oVerbose: opt.verbose++; break;
593 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
594 case oDebugAll: opt.debug = ~0; break;
595 case oDebugLevel: debug_level = pargs->r.ret_str; break;
596 case oDebugPinentry: opt.debug_pinentry = 1; break;
600 return 0; /* not handeld */
601 if (!current_logfile || !pargs->r.ret_str
602 || strcmp (current_logfile, pargs->r.ret_str))
604 log_set_file (pargs->r.ret_str);
605 xfree (current_logfile);
606 current_logfile = xtrystrdup (pargs->r.ret_str);
610 case oNoGrab: opt.no_grab = 1; break;
612 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
613 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
614 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
615 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
616 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
618 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
619 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
620 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
621 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
623 case oEnforcePassphraseConstraints:
624 opt.enforce_passphrase_constraints=1;
626 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
627 case oMinPassphraseNonalpha:
628 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
630 case oCheckPassphrasePattern:
631 opt.check_passphrase_pattern = pargs->r.ret_str;
633 case oMaxPassphraseDays:
634 opt.max_passphrase_days = pargs->r.ret_ulong;
636 case oEnablePassphraseHistory:
637 opt.enable_passhrase_history = 1;
640 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
642 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
643 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
645 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
647 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
649 case oNoAllowExternalCache: opt.allow_external_cache = 0;
652 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
656 return 0; /* not handled */
659 return 1; /* handled */
663 /* Fixup some options after all have been processed. */
665 finalize_rereadable_options (void)
667 /* It would be too surprising if the max-cache-ttl is lower than the
668 default-cache-ttl - thus we silently correct that. */
669 if (opt.def_cache_ttl > opt.max_cache_ttl)
670 opt.max_cache_ttl = opt.def_cache_ttl;
671 if (opt.def_cache_ttl_ssh > opt.max_cache_ttl_ssh)
672 opt.max_cache_ttl_ssh = opt.def_cache_ttl_ssh;
677 /* The main entry point. */
679 main (int argc, char **argv )
684 FILE *configfp = NULL;
685 char *configname = NULL;
687 unsigned configlineno;
689 int default_config =1;
694 char *logfile = NULL;
696 int gpgconf_list = 0;
698 struct assuan_malloc_hooks malloc_hooks;
700 early_system_init ();
702 /* Before we do anything else we save the list of currently open
703 file descriptors and the signal mask. This info is required to
704 do the exec call properly. */
705 startup_fd_list = get_all_open_fds ();
706 #ifdef HAVE_SIGPROCMASK
707 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
708 startup_signal_mask_valid = 1;
709 #endif /*HAVE_SIGPROCMASK*/
711 /* Set program name etc. */
712 set_strusage (my_strusage);
713 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
714 /* Please note that we may running SUID(ROOT), so be very CAREFUL
715 when adding any stuff between here and the call to INIT_SECMEM()
716 somewhere after the option parsing */
717 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
719 /* Make sure that our subsystems are ready. */
721 init_common_subsystems (&argc, &argv);
725 /* Check that the libraries are suitable. Do it here because
726 the option parsing may need services of the library. */
727 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
729 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
730 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
733 malloc_hooks.malloc = gcry_malloc;
734 malloc_hooks.realloc = gcry_realloc;
735 malloc_hooks.free = gcry_free;
736 assuan_set_malloc_hooks (&malloc_hooks);
737 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
738 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
740 setup_libassuan_logging (&opt.debug);
742 setup_libgcrypt_logging ();
743 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
745 disable_core_dumps ();
747 /* Set default options. */
748 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
750 shell = getenv ("SHELL");
751 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
754 opt.homedir = default_homedir ();
756 /* Record some of the original environment strings. */
760 static const char *names[] =
761 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
764 opt.startup_env = session_env_new ();
765 if (!opt.startup_env)
766 err = gpg_error_from_syserror ();
767 for (idx=0; !err && names[idx]; idx++)
769 s = getenv (names[idx]);
771 err = session_env_setenv (opt.startup_env, names[idx], s);
775 s = gnupg_ttyname (0);
777 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
780 log_fatal ("error recording startup environment: %s\n",
783 /* Fixme: Better use the locale function here. */
784 opt.startup_lc_ctype = getenv ("LC_CTYPE");
785 if (opt.startup_lc_ctype)
786 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
787 opt.startup_lc_messages = getenv ("LC_MESSAGES");
788 if (opt.startup_lc_messages)
789 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
792 /* Check whether we have a config file on the commandline */
797 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
798 while (arg_parse( &pargs, opts))
800 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
802 else if (pargs.r_opt == oOptions)
803 { /* yes there is one, so we do not try the default one, but
804 read the option file when it is encountered at the
808 else if (pargs.r_opt == oNoOptions)
809 default_config = 0; /* --no-options */
810 else if (pargs.r_opt == oHomedir)
811 opt.homedir = pargs.r.ret_str;
812 else if (pargs.r_opt == oDebugQuickRandom)
814 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
819 /* Initialize the secure memory. */
820 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
824 Now we are now working under our real uid
828 configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
835 pargs.flags= 1; /* do not remove the args */
840 configfp = fopen (configname, "r");
846 log_info (_("Note: no default option file '%s'\n"),
848 /* Save the default conf file name so that
849 reread_configuration is able to test whether the
850 config file has been created in the meantime. */
851 xfree (config_filename);
852 config_filename = configname;
857 log_error (_("option file '%s': %s\n"),
858 configname, strerror(errno) );
864 if (parse_debug && configname )
865 log_info (_("reading options from '%s'\n"), configname );
869 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
871 if (parse_rereadable_options (&pargs, 0))
872 continue; /* Already handled */
875 case aGPGConfList: gpgconf_list = 1; break;
876 case aGPGConfTest: gpgconf_list = 2; break;
877 case aUseStandardSocketP: gpgconf_list = 3; break;
878 case oBatch: opt.batch=1; break;
880 case oDebugWait: debug_wait = pargs.r.ret_int; break;
883 /* config files may not be nested (silently ignore them) */
887 configname = xstrdup(pargs.r.ret_str);
891 case oNoGreeting: /* Dummy option. */ break;
892 case oNoVerbose: opt.verbose = 0; break;
893 case oNoOptions: break; /* no-options */
894 case oHomedir: opt.homedir = pargs.r.ret_str; break;
895 case oNoDetach: nodetach = 1; break;
896 case oLogFile: logfile = pargs.r.ret_str; break;
897 case oCsh: csh_style = 1; break;
898 case oSh: csh_style = 0; break;
899 case oServer: pipe_server = 1; break;
900 case oDaemon: is_daemon = 1; break;
902 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
903 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
904 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
905 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
906 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
908 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
911 case oUseStandardSocket: /* dummy */ break;
912 case oNoUseStandardSocket: /* dummy */ break;
914 case oFakedSystemTime:
916 time_t faked_time = isotime2epoch (pargs.r.ret_str);
917 if (faked_time == (time_t)(-1))
918 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
919 gnupg_set_time (faked_time, 0);
923 case oKeepTTY: opt.keep_tty = 1; break;
924 case oKeepDISPLAY: opt.keep_display = 1; break;
926 case oSSHSupport: opt.ssh_support = 1; break;
928 # ifdef HAVE_W32_SYSTEM
935 opt.extra_socket = 1; /* (1 = points into argv) */
936 socket_name_extra = pargs.r.ret_str;
940 opt.browser_socket = 1; /* (1 = points into argv) */
941 socket_name_browser = pargs.r.ret_str;
944 case oDebugQuickRandom:
945 /* Only used by the first stage command line parser. */
948 case oWriteEnvFile: /* dummy */ break;
950 default : pargs.err = configfp? 1:2; break;
957 /* Keep a copy of the name so that it can be read on SIGHUP. */
958 if (config_filename != configname)
960 xfree (config_filename);
961 config_filename = configname;
969 if (log_get_errorcount(0))
972 finalize_rereadable_options ();
974 /* Turn the homedir into an absolute one. */
975 opt.homedir = make_absfilename (opt.homedir, NULL);
977 /* Print a warning if an argument looks like an option. */
978 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
982 for (i=0; i < argc; i++)
983 if (argv[i][0] == '-' && argv[i][1] == '-')
984 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
988 /* gpg-agent usually does not output any messages because it runs in
989 the background. For log files it is acceptable to have messages
990 always encoded in utf-8. We switch here to utf-8, so that
991 commands like --help still give native messages. It is far
992 easier to switch only once instead of for every message and it
993 actually helps when more then one thread is active (avoids an
995 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
998 if (!pipe_server && !is_daemon && !gpgconf_list)
1000 /* We have been called without any options and thus we merely
1001 check whether an agent is already running. We do this right
1002 here so that we don't clobber a logfile with this check but
1003 print the status directly to stderr. */
1006 check_for_running_agent (0);
1012 if (atexit (cleanup))
1014 log_error ("atexit failed\n");
1019 initialize_module_cache ();
1020 initialize_module_call_pinentry ();
1021 initialize_module_call_scd ();
1022 initialize_module_trustlist ();
1024 /* Try to create missing directories. */
1025 create_directories ();
1027 if (debug_wait && pipe_server)
1029 log_debug ("waiting for debugger - my pid is %u .....\n",
1030 (unsigned int)getpid());
1031 gnupg_sleep (debug_wait);
1032 log_debug ("... okay\n");
1035 if (gpgconf_list == 3)
1037 /* We now use the standard socket always - return true for
1038 backward compatibility. */
1041 else if (gpgconf_list == 2)
1043 else if (gpgconf_list)
1048 /* List options and default values in the GPG Conf format. */
1049 filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
1051 filename_esc = percent_escape (filename, NULL);
1053 es_printf ("%s-%s.conf:%lu:\"%s\n",
1054 GPGCONF_NAME, GPG_AGENT_NAME,
1055 GC_OPT_FLAG_DEFAULT, filename_esc);
1057 xfree (filename_esc);
1059 es_printf ("verbose:%lu:\n"
1061 "debug-level:%lu:\"none:\n"
1063 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1064 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1065 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1066 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1067 es_printf ("default-cache-ttl:%lu:%d:\n",
1068 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1069 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1070 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1071 es_printf ("max-cache-ttl:%lu:%d:\n",
1072 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1073 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1074 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1075 es_printf ("enforce-passphrase-constraints:%lu:\n",
1076 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1077 es_printf ("min-passphrase-len:%lu:%d:\n",
1078 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1079 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1080 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1081 MIN_PASSPHRASE_NONALPHA);
1082 es_printf ("check-passphrase-pattern:%lu:\n",
1083 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1084 es_printf ("max-passphrase-days:%lu:%d:\n",
1085 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1086 MAX_PASSPHRASE_DAYS);
1087 es_printf ("enable-passphrase-history:%lu:\n",
1088 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1089 es_printf ("no-grab:%lu:\n",
1090 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1091 es_printf ("ignore-cache-for-signing:%lu:\n",
1092 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1093 es_printf ("no-allow-external-cache:%lu:\n",
1094 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1095 es_printf ("no-allow-mark-trusted:%lu:\n",
1096 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1097 es_printf ("disable-scdaemon:%lu:\n",
1098 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1099 #ifdef HAVE_W32_SYSTEM
1100 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1102 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1104 es_printf ("allow-loopback-pinentry:%lu:\n",
1105 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1106 es_printf ("allow-emacs-pinentry:%lu:\n",
1107 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1112 /* Now start with logging to a file if this is desired. */
1115 log_set_file (logfile);
1116 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1117 | GPGRT_LOG_WITH_TIME
1118 | GPGRT_LOG_WITH_PID));
1119 current_logfile = xstrdup (logfile);
1122 /* Make sure that we have a default ttyname. */
1123 if (!default_ttyname && gnupg_ttyname (1))
1124 default_ttyname = xstrdup (gnupg_ttyname (1));
1125 if (!default_ttytype && getenv ("TERM"))
1126 default_ttytype = xstrdup (getenv ("TERM"));
1131 /* This is the simple pipe based server */
1134 ctrl = xtrycalloc (1, sizeof *ctrl);
1137 log_error ("error allocating connection control data: %s\n",
1141 ctrl->session_env = session_env_new ();
1142 if (!ctrl->session_env)
1144 log_error ("error allocating session environment block: %s\n",
1149 agent_init_default_ctrl (ctrl);
1150 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1151 agent_deinit_default_ctrl (ctrl);
1154 else if (!is_daemon)
1157 { /* Regular server mode */
1159 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1160 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1161 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1164 /* Remove the DISPLAY variable so that a pinentry does not
1165 default to a specific display. There is still a default
1166 display when gpg-agent was started using --display or a
1167 client requested this using an OPTION command. Note, that we
1168 don't do this when running in reverse daemon mode (i.e. when
1169 exec the program given as arguments). */
1170 #ifndef HAVE_W32_SYSTEM
1171 if (!opt.keep_display && !argc)
1172 gnupg_unsetenv ("DISPLAY");
1175 /* Create the sockets. */
1176 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1177 fd = create_server_socket (socket_name, 1,
1178 &redir_socket_name, &socket_nonce);
1180 if (opt.extra_socket)
1182 socket_name_extra = create_socket_name (socket_name_extra, 0);
1183 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1184 fd_extra = create_server_socket (socket_name_extra, 0,
1185 &redir_socket_name_extra,
1186 &socket_nonce_extra);
1189 if (opt.browser_socket)
1191 socket_name_browser = create_socket_name (socket_name_browser, 0);
1192 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1193 fd_browser = create_server_socket (socket_name_browser, 0,
1194 &redir_socket_name_browser,
1195 &socket_nonce_browser);
1198 if (opt.ssh_support)
1200 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1201 fd_ssh = create_server_socket (socket_name_ssh, 0,
1202 &redir_socket_name_ssh,
1206 /* If we are going to exec a program in the parent, we record
1207 the PID, so that the child may check whether the program is
1210 parent_pid = getpid ();
1213 #ifdef HAVE_W32_SYSTEM
1217 #else /*!HAVE_W32_SYSTEM*/
1219 if (pid == (pid_t)-1)
1221 log_fatal ("fork failed: %s\n", strerror (errno) );
1225 { /* We are the parent */
1226 char *infostr_ssh_sock, *infostr_ssh_valid;
1228 /* Close the socket FD. */
1231 /* The signal mask might not be correct right now and thus
1232 we restore it. That is not strictly necessary but some
1233 programs falsely assume a cleared signal mask. */
1235 #ifdef HAVE_SIGPROCMASK
1236 if (startup_signal_mask_valid)
1238 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1239 log_error ("error restoring signal mask: %s\n",
1243 log_info ("no saved signal mask\n");
1244 #endif /*HAVE_SIGPROCMASK*/
1246 /* Create the SSH info string if enabled. */
1247 if (opt.ssh_support)
1249 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1250 socket_name_ssh) < 0)
1252 log_error ("out of core\n");
1253 kill (pid, SIGTERM);
1256 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1257 (unsigned long)getpid()) < 0)
1259 log_error ("out of core\n");
1260 kill (pid, SIGTERM);
1265 *socket_name = 0; /* Don't let cleanup() remove the socket -
1266 the child should do this from now on */
1267 if (opt.extra_socket)
1268 *socket_name_extra = 0;
1269 if (opt.browser_socket)
1270 *socket_name_browser = 0;
1271 if (opt.ssh_support)
1272 *socket_name_ssh = 0;
1275 { /* Run the program given on the commandline. */
1276 if (opt.ssh_support && (putenv (infostr_ssh_sock)
1277 || putenv (infostr_ssh_valid)))
1279 log_error ("failed to set environment: %s\n",
1281 kill (pid, SIGTERM );
1285 /* Close all the file descriptors except the standard
1286 ones and those open at startup. We explicitly don't
1287 close 0,1,2 in case something went wrong collecting
1289 close_all_fds (3, startup_fd_list);
1291 /* Run the command. */
1292 execvp (argv[0], argv);
1293 log_error ("failed to run the command: %s\n", strerror (errno));
1294 kill (pid, SIGTERM);
1299 /* Print the environment string, so that the caller can use
1300 shell's eval to set it */
1303 if (opt.ssh_support)
1305 *strchr (infostr_ssh_sock, '=') = ' ';
1306 es_printf ("setenv %s;\n", infostr_ssh_sock);
1311 if (opt.ssh_support)
1313 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1317 if (opt.ssh_support)
1319 xfree (infostr_ssh_sock);
1320 xfree (infostr_ssh_valid);
1331 /* Detach from tty and put process into a new session */
1335 unsigned int oldflags;
1337 /* Close stdin, stdout and stderr unless it is the log stream */
1338 for (i=0; i <= 2; i++)
1340 if (!log_test_fd (i) && i != fd )
1343 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1345 log_error ("failed to open '%s': %s\n",
1346 "/dev/null", strerror (errno));
1354 log_error ("setsid() failed: %s\n", strerror(errno) );
1359 log_get_prefix (&oldflags);
1360 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1361 opt.running_detached = 1;
1366 log_error ("chdir to / failed: %s\n", strerror (errno));
1371 struct sigaction sa;
1373 sa.sa_handler = SIG_IGN;
1374 sigemptyset (&sa.sa_mask);
1376 sigaction (SIGPIPE, &sa, NULL);
1378 #endif /*!HAVE_W32_SYSTEM*/
1380 log_info ("%s %s started\n", strusage(11), strusage(13) );
1381 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1382 assuan_sock_close (fd);
1389 /* Exit entry point. This function should be called instead of a
1394 /*FIXME: update_random_seed_file();*/
1396 /* We run our cleanup handler because that may close cipher contexts
1397 stored in secure memory and thus this needs to be done before we
1398 explicitly terminate secure memory. */
1402 /* at this time a bit annoying */
1403 if (opt.debug & DBG_MEMSTAT_VALUE)
1405 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1406 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1409 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1411 gcry_control (GCRYCTL_TERM_SECMEM );
1412 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1417 /* Each thread has its own local variables conveyed by a control
1418 structure usually identified by an argument named CTRL. This
1419 function is called immediately after allocating the control
1420 structure. Its purpose is to setup the default values for that
1421 structure. Note that some values may have already been set. */
1423 agent_init_default_ctrl (ctrl_t ctrl)
1425 assert (ctrl->session_env);
1427 /* Note we ignore malloc errors because we can't do much about it
1428 and the request will fail anyway shortly after this
1430 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1431 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1432 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1433 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1434 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1437 xfree (ctrl->lc_ctype);
1438 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1440 if (ctrl->lc_messages)
1441 xfree (ctrl->lc_messages);
1442 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1444 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1448 /* Release all resources allocated by default in the control
1449 structure. This is the counterpart to agent_init_default_ctrl. */
1451 agent_deinit_default_ctrl (ctrl_t ctrl)
1453 session_env_release (ctrl->session_env);
1456 xfree (ctrl->lc_ctype);
1457 if (ctrl->lc_messages)
1458 xfree (ctrl->lc_messages);
1462 /* Because the ssh protocol does not send us information about the
1463 current TTY setting, we use this function to use those from startup
1464 or those explictly set. This is also used for the restricted mode
1465 where we ignore requests to change the environment. */
1467 agent_copy_startup_env (ctrl_t ctrl)
1469 static const char *names[] =
1470 {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1471 gpg_error_t err = 0;
1475 for (idx=0; !err && names[idx]; idx++)
1476 if ((value = session_env_getenv (opt.startup_env, names[idx])))
1477 err = session_env_setenv (ctrl->session_env, names[idx], value);
1479 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1480 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1481 err = gpg_error_from_syserror ();
1483 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1484 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1485 err = gpg_error_from_syserror ();
1488 log_error ("error setting default session environment: %s\n",
1489 gpg_strerror (err));
1495 /* Reread parts of the configuration. Note, that this function is
1496 obviously not thread-safe and should only be called from the PTH
1499 Fixme: Due to the way the argument parsing works, we create a
1500 memory leak here for all string type arguments. There is currently
1501 no clean way to tell whether the memory for the argument has been
1502 allocated or points into the process' original arguments. Unless
1503 we have a mechanism to tell this, we need to live on with this. */
1505 reread_configuration (void)
1507 ARGPARSE_ARGS pargs;
1509 unsigned int configlineno = 0;
1512 if (!config_filename)
1513 return; /* No config file. */
1515 fp = fopen (config_filename, "r");
1518 log_info (_("option file '%s': %s\n"),
1519 config_filename, strerror(errno) );
1523 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1525 memset (&pargs, 0, sizeof pargs);
1527 pargs.argc = &dummy;
1528 pargs.flags = 1; /* do not remove the args */
1529 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1531 if (pargs.r_opt < -1)
1532 pargs.err = 1; /* Print a warning. */
1533 else /* Try to parse this option - ignore unchangeable ones. */
1534 parse_rereadable_options (&pargs, 1);
1537 finalize_rereadable_options ();
1542 /* Return the file name of the socket we are using for native
1545 get_agent_socket_name (void)
1547 const char *s = socket_name;
1549 return (s && *s)? s : NULL;
1552 /* Return the file name of the socket we are using for SSH
1555 get_agent_ssh_socket_name (void)
1557 const char *s = socket_name_ssh;
1559 return (s && *s)? s : NULL;
1563 /* Under W32, this function returns the handle of the scdaemon
1564 notification event. Calling it the first time creates that
1566 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1568 get_agent_scd_notify_event (void)
1570 static HANDLE the_event = INVALID_HANDLE_VALUE;
1572 if (the_event == INVALID_HANDLE_VALUE)
1575 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1577 /* We need to use a manual reset event object due to the way our
1578 w32-pth wait function works: If we would use an automatic
1579 reset event we are not able to figure out which handle has
1580 been signaled because at the time we single out the signaled
1581 handles using WFSO the event has already been reset due to
1583 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1585 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1586 else if (!DuplicateHandle (GetCurrentProcess(), h,
1587 GetCurrentProcess(), &h2,
1588 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1590 log_error ("setting syncronize for scd notify event failed: %s\n",
1591 w32_strerror (-1) );
1603 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1607 /* Create a name for the socket in the home directory as using
1608 STANDARD_NAME. We also check for valid characters as well as
1609 against a maximum allowed length for a unix domain socket is done.
1610 The function terminates the process in case of an error. Returns:
1611 Pointer to an allocated string with the absolute name of the socket
1614 create_socket_name (char *standard_name, int with_homedir)
1619 name = make_filename (opt.homedir, standard_name, NULL);
1621 name = make_filename (standard_name, NULL);
1622 if (strchr (name, PATHSEP_C))
1624 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1632 /* Create a Unix domain socket with NAME. Returns the file descriptor
1633 or terminates the process in case of an error. Note that this
1634 function needs to be used for the regular socket first (indicated
1635 by PRIMARY) and only then for the extra and the ssh sockets. If
1636 the socket has been redirected the name of the real socket is
1637 stored as a malloced string at R_REDIR_NAME. */
1639 create_server_socket (char *name, int primary,
1640 char **r_redir_name, assuan_sock_nonce_t *nonce)
1642 struct sockaddr *addr;
1643 struct sockaddr_un *unaddr;
1648 xfree (*r_redir_name);
1649 *r_redir_name = NULL;
1651 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1652 if (fd == ASSUAN_INVALID_FD)
1654 log_error (_("can't create socket: %s\n"), strerror (errno));
1655 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1659 unaddr = xmalloc (sizeof *unaddr);
1660 addr = (struct sockaddr*)unaddr;
1662 #if ASSUAN_VERSION_NUMBER >= 0x020104 /* >= 2.1.4 */
1666 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1668 if (errno == ENAMETOOLONG)
1669 log_error (_("socket name '%s' is too long\n"), name);
1671 log_error ("error preparing socket '%s': %s\n",
1672 name, gpg_strerror (gpg_error_from_syserror ()));
1673 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1678 *r_redir_name = xstrdup (unaddr->sun_path);
1680 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1683 #else /* Assuan < 2.1.4 */
1684 memset (unaddr, 0, sizeof *unaddr);
1685 unaddr->sun_family = AF_UNIX;
1686 if (strlen (name) + 1 >= sizeof (unaddr->sun_path))
1688 log_error (_("socket name '%s' is too long\n"), name);
1689 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1692 strcpy (unaddr->sun_path, name);
1693 #endif /* Assuan < 2.1.4 */
1695 len = SUN_LEN (unaddr);
1696 rc = assuan_sock_bind (fd, addr, len);
1698 /* Our error code mapping on W32CE returns EEXIST thus we also test
1701 && (errno == EADDRINUSE
1702 #ifdef HAVE_W32_SYSTEM
1707 /* Check whether a gpg-agent is already running. We do this
1708 test only if this is the primary socket. For secondary
1709 sockets we assume that a test for gpg-agent has already been
1710 done and reuse the requested socket. Testing the ssh-socket
1711 is not possible because at this point, though we know the new
1712 Assuan socket, the Assuan server and thus the ssh-agent
1713 server is not yet operational; this would lead to a hang. */
1714 if (primary && !check_for_running_agent (1))
1716 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
1717 log_set_file (NULL);
1718 log_error (_("a gpg-agent is already running - "
1719 "not starting a new one\n"));
1720 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1721 assuan_sock_close (fd);
1724 gnupg_remove (unaddr->sun_path);
1725 rc = assuan_sock_bind (fd, addr, len);
1727 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1728 log_error (_("error getting nonce for the socket\n"));
1731 /* We use gpg_strerror here because it allows us to get strings
1732 for some W32 socket error codes. */
1733 log_error (_("error binding socket to '%s': %s\n"),
1735 gpg_strerror (gpg_error_from_syserror ()));
1737 assuan_sock_close (fd);
1738 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1742 if (listen (FD2INT(fd), 5 ) == -1)
1744 log_error (_("listen() failed: %s\n"), strerror (errno));
1745 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1746 assuan_sock_close (fd);
1751 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1757 /* Check that the directory for storing the private keys exists and
1758 create it if not. This function won't fail as it is only a
1759 convenience function and not strictly necessary. */
1761 create_private_keys_directory (const char *home)
1764 struct stat statbuf;
1766 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1767 if (stat (fname, &statbuf) && errno == ENOENT)
1769 if (gnupg_mkdir (fname, "-rwx"))
1770 log_error (_("can't create directory '%s': %s\n"),
1771 fname, strerror (errno) );
1772 else if (!opt.quiet)
1773 log_info (_("directory '%s' created\n"), fname);
1778 /* Create the directory only if the supplied directory name is the
1779 same as the default one. This way we avoid to create arbitrary
1780 directories when a non-default home directory is used. To cope
1781 with HOME, we compare only the suffix if we see that the default
1782 homedir does start with a tilde. We don't stop here in case of
1783 problems because other functions will throw an error anyway.*/
1785 create_directories (void)
1787 struct stat statbuf;
1788 const char *defhome = standard_homedir ();
1791 home = make_filename (opt.homedir, NULL);
1792 if ( stat (home, &statbuf) )
1794 if (errno == ENOENT)
1797 #ifdef HAVE_W32_SYSTEM
1798 ( !compare_filenames (home, defhome) )
1801 && (strlen (home) >= strlen (defhome+1)
1802 && !strcmp (home + strlen(home)
1803 - strlen (defhome+1), defhome+1)))
1804 || (*defhome != '~' && !strcmp (home, defhome) )
1808 if (gnupg_mkdir (home, "-rwx"))
1809 log_error (_("can't create directory '%s': %s\n"),
1810 home, strerror (errno) );
1814 log_info (_("directory '%s' created\n"), home);
1815 create_private_keys_directory (home);
1820 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1822 else if ( !S_ISDIR(statbuf.st_mode))
1824 log_error (_("can't use '%s' as home directory\n"), home);
1826 else /* exists and is a directory. */
1828 create_private_keys_directory (home);
1835 /* This is the worker for the ticker. It is called every few seconds
1836 and may only do fast operations. */
1840 static time_t last_minute;
1843 last_minute = time (NULL);
1845 /* Check whether the scdaemon has died and cleanup in this case. */
1846 agent_scd_check_aliveness ();
1848 /* If we are running as a child of another process, check whether
1849 the parent is still alive and shutdown if not. */
1850 #ifndef HAVE_W32_SYSTEM
1851 if (parent_pid != (pid_t)(-1))
1853 if (kill (parent_pid, 0))
1855 shutdown_pending = 2;
1856 log_info ("parent process died - shutting down\n");
1857 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1862 #endif /*HAVE_W32_SYSTEM*/
1864 /* Code to be run from time to time. */
1865 #if CHECK_OWN_SOCKET_INTERVAL > 0
1866 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
1868 check_own_socket ();
1869 last_minute = time (NULL);
1876 /* A global function which allows us to call the reload stuff from
1877 other places too. This is only used when build for W32. */
1879 agent_sighup_action (void)
1881 log_info ("SIGHUP received - "
1882 "re-reading configuration and flushing cache\n");
1884 agent_flush_cache ();
1885 reread_configuration ();
1886 agent_reload_trustlist ();
1887 /* We flush the module name cache so that after installing a
1888 "pinentry" binary that one can be used in case the
1889 "pinentry-basic" fallback was in use. */
1890 gnupg_module_name_flush_some ();
1894 /* A helper function to handle SIGUSR2. */
1896 agent_sigusr2_action (void)
1899 log_info ("SIGUSR2 received - updating card event counter\n");
1900 /* Nothing to check right now. We only increment a counter. */
1901 bump_card_eventcounter ();
1905 #ifndef HAVE_W32_SYSTEM
1906 /* The signal handler for this program. It is expected to be run in
1907 its own trhead and not in the context of a signal handler. */
1909 handle_signal (int signo)
1913 #ifndef HAVE_W32_SYSTEM
1915 agent_sighup_action ();
1919 log_info ("SIGUSR1 received - printing internal information:\n");
1920 /* Fixme: We need to see how to integrate pth dumping into our
1922 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1923 agent_query_dump_state ();
1924 agent_scd_dump_state ();
1928 agent_sigusr2_action ();
1932 if (!shutdown_pending)
1933 log_info ("SIGTERM received - shutting down ...\n");
1935 log_info ("SIGTERM received - still %i open connections\n",
1936 active_connections);
1938 if (shutdown_pending > 2)
1940 log_info ("shutdown forced\n");
1941 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1948 log_info ("SIGINT received - immediate shutdown\n");
1949 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1955 log_info ("signal %d received - no action defined\n", signo);
1960 /* Check the nonce on a new connection. This is a NOP unless we we
1961 are using our Unix domain socket emulation under Windows. */
1963 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1965 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1967 log_info (_("error reading nonce on fd %d: %s\n"),
1968 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1969 assuan_sock_close (ctrl->thread_startup.fd);
1978 #ifdef HAVE_W32_SYSTEM
1979 /* The window message processing function for Putty. Warning: This
1980 code runs as a native Windows thread. Use of our own functions
1981 needs to be bracket with pth_leave/pth_enter. */
1982 static LRESULT CALLBACK
1983 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1987 COPYDATASTRUCT *cds;
1988 const char *mapfile;
1993 PSECURITY_DESCRIPTOR psd = NULL;
1996 if (msg != WM_COPYDATA)
1998 return DefWindowProc (hwnd, msg, wparam, lparam);
2001 cds = (COPYDATASTRUCT*)lparam;
2002 if (cds->dwData != PUTTY_IPC_MAGIC)
2003 return 0; /* Ignore data with the wrong magic. */
2004 mapfile = cds->lpData;
2005 if (!cds->cbData || mapfile[cds->cbData - 1])
2006 return 0; /* Ignore empty and non-properly terminated strings. */
2011 log_debug ("ssh map file '%s'", mapfile);
2015 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2019 log_debug ("ssh map handle %p\n", maphd);
2023 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2028 mysid = w32_get_user_sid ();
2031 log_error ("error getting my sid\n");
2035 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2036 OWNER_SECURITY_INFORMATION,
2037 &mapsid, NULL, NULL, NULL,
2041 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2049 if (!ConvertSidToStringSid (mysid, &sidstr))
2051 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2053 if (!ConvertSidToStringSid (mapsid, &sidstr))
2055 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2059 if (!EqualSid (mysid, mapsid))
2061 log_error ("ssh map file has a non-matching sid\n");
2065 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2067 log_debug ("ssh IPC buffer at %p\n", data);
2071 /* log_printhex ("request:", data, 20); */
2073 ctrl = xtrycalloc (1, sizeof *ctrl);
2076 log_error ("error allocating connection control data: %s\n",
2080 ctrl->session_env = session_env_new ();
2081 if (!ctrl->session_env)
2083 log_error ("error allocating session environment block: %s\n",
2088 agent_init_default_ctrl (ctrl);
2089 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2090 ret = 1; /* Valid ssh message has been constructed. */
2091 agent_deinit_default_ctrl (ctrl);
2092 /* log_printhex (" reply:", data, 20); */
2097 UnmapViewOfFile (data);
2102 CloseHandle (maphd);
2108 #endif /*HAVE_W32_SYSTEM*/
2111 #ifdef HAVE_W32_SYSTEM
2112 /* The thread handling Putty's IPC requests. */
2114 putty_message_thread (void *arg)
2116 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2117 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2124 log_info ("putty message loop thread started\n");
2126 /* The message loop runs as thread independent from our nPth system.
2127 This also means that we need to make sure that we switch back to
2128 our system before calling any no-windows function. */
2131 /* First create a window to make sure that a message queue exists
2133 if (!RegisterClass (&wndwclass))
2136 log_error ("error registering Pageant window class");
2139 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2141 HWND_MESSAGE, /* hWndParent */
2142 NULL, /* hWndMenu */
2143 NULL, /* hInstance */
2148 log_error ("error creating Pageant window");
2152 while (GetMessage(&msg, NULL, 0, 0))
2154 TranslateMessage(&msg);
2155 DispatchMessage(&msg);
2162 log_info ("putty message loop thread stopped\n");
2165 #endif /*HAVE_W32_SYSTEM*/
2169 do_start_connection_thread (ctrl_t ctrl)
2171 agent_init_default_ctrl (ctrl);
2173 log_info (_("handler 0x%lx for fd %d started\n"),
2174 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2176 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2178 log_info (_("handler 0x%lx for fd %d terminated\n"),
2179 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2181 agent_deinit_default_ctrl (ctrl);
2187 /* This is the standard connection thread's main function. */
2189 start_connection_thread_std (void *arg)
2193 if (check_nonce (ctrl, &socket_nonce))
2195 log_error ("handler 0x%lx nonce check FAILED\n",
2196 (unsigned long) npth_self());
2200 return do_start_connection_thread (ctrl);
2204 /* This is the extra socket connection thread's main function. */
2206 start_connection_thread_extra (void *arg)
2210 if (check_nonce (ctrl, &socket_nonce_extra))
2212 log_error ("handler 0x%lx nonce check FAILED\n",
2213 (unsigned long) npth_self());
2217 ctrl->restricted = 1;
2218 return do_start_connection_thread (ctrl);
2222 /* This is the browser socket connection thread's main function. */
2224 start_connection_thread_browser (void *arg)
2228 if (check_nonce (ctrl, &socket_nonce_browser))
2230 log_error ("handler 0x%lx nonce check FAILED\n",
2231 (unsigned long) npth_self());
2235 ctrl->restricted = 2;
2236 return do_start_connection_thread (ctrl);
2240 /* This is the ssh connection thread's main function. */
2242 start_connection_thread_ssh (void *arg)
2246 if (check_nonce (ctrl, &socket_nonce_ssh))
2249 agent_init_default_ctrl (ctrl);
2251 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2252 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2254 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2256 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2257 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2259 agent_deinit_default_ctrl (ctrl);
2265 /* Connection handler loop. Wait for connection requests and spawn a
2266 thread after accepting a connection. */
2268 handle_connections (gnupg_fd_t listen_fd,
2269 gnupg_fd_t listen_fd_extra,
2270 gnupg_fd_t listen_fd_browser,
2271 gnupg_fd_t listen_fd_ssh)
2274 struct sockaddr_un paddr;
2276 fd_set fdset, read_fdset;
2281 struct timespec abstime;
2282 struct timespec curtime;
2283 struct timespec timeout;
2284 #ifdef HAVE_W32_SYSTEM
2286 unsigned int events_set;
2290 void *(*func) (void *arg);
2293 { "std", start_connection_thread_std },
2294 { "extra", start_connection_thread_extra },
2295 { "browser", start_connection_thread_browser },
2296 { "ssh", start_connection_thread_ssh }
2300 ret = npth_attr_init(&tattr);
2302 log_fatal ("error allocating thread attributes: %s\n",
2304 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2306 #ifndef HAVE_W32_SYSTEM
2308 npth_sigev_add (SIGHUP);
2309 npth_sigev_add (SIGUSR1);
2310 npth_sigev_add (SIGUSR2);
2311 npth_sigev_add (SIGINT);
2312 npth_sigev_add (SIGTERM);
2315 # ifdef HAVE_W32CE_SYSTEM
2316 /* Use a dummy event. */
2318 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2320 events[0] = get_agent_scd_notify_event ();
2321 events[1] = INVALID_HANDLE_VALUE;
2325 /* On Windows we need to fire up a separate thread to listen for
2326 requests from Putty (an SSH client), so we can replace Putty's
2327 Pageant (its ssh-agent implementation). */
2328 #ifdef HAVE_W32_SYSTEM
2333 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2336 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2339 #endif /*HAVE_W32_SYSTEM*/
2341 /* Set a flag to tell call-scd.c that it may enable event
2343 opt.sigusr2_enabled = 1;
2346 FD_SET (FD2INT (listen_fd), &fdset);
2347 nfd = FD2INT (listen_fd);
2348 if (listen_fd_extra != GNUPG_INVALID_FD)
2350 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2351 if (FD2INT (listen_fd_extra) > nfd)
2352 nfd = FD2INT (listen_fd_extra);
2354 if (listen_fd_browser != GNUPG_INVALID_FD)
2356 FD_SET ( FD2INT(listen_fd_browser), &fdset);
2357 if (FD2INT (listen_fd_browser) > nfd)
2358 nfd = FD2INT (listen_fd_browser);
2360 if (listen_fd_ssh != GNUPG_INVALID_FD)
2362 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2363 if (FD2INT (listen_fd_ssh) > nfd)
2364 nfd = FD2INT (listen_fd_ssh);
2367 listentbl[0].l_fd = listen_fd;
2368 listentbl[1].l_fd = listen_fd_extra;
2369 listentbl[2].l_fd = listen_fd_browser;
2370 listentbl[3].l_fd = listen_fd_ssh;
2372 npth_clock_gettime (&abstime);
2373 abstime.tv_sec += TIMERTICK_INTERVAL;
2377 /* Shutdown test. */
2378 if (shutdown_pending)
2380 if (active_connections == 0)
2383 /* Do not accept new connections but keep on running the
2384 loop to cope with the timer events. */
2388 /* POSIX says that fd_set should be implemented as a structure,
2389 thus a simple assignment is fine to copy the entire set. */
2392 npth_clock_gettime (&curtime);
2393 if (!(npth_timercmp (&curtime, &abstime, <)))
2397 npth_clock_gettime (&abstime);
2398 abstime.tv_sec += TIMERTICK_INTERVAL;
2400 npth_timersub (&abstime, &curtime, &timeout);
2402 #ifndef HAVE_W32_SYSTEM
2403 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2404 npth_sigev_sigmask ());
2405 saved_errno = errno;
2409 while (npth_sigev_get_pending (&signo))
2410 handle_signal (signo);
2413 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2414 events, &events_set);
2415 saved_errno = errno;
2417 /* This is valid even if npth_eselect returns an error. */
2419 agent_sigusr2_action ();
2422 if (ret == -1 && saved_errno != EINTR)
2424 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2425 strerror (saved_errno));
2430 /* Interrupt or timeout. Will be handled when calculating the
2434 if (!shutdown_pending)
2440 for (idx=0; idx < DIM(listentbl); idx++)
2442 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2444 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2447 plen = sizeof paddr;
2448 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2449 (struct sockaddr *)&paddr, &plen));
2450 if (fd == GNUPG_INVALID_FD)
2452 log_error ("accept failed for %s: %s\n",
2453 listentbl[idx].name, strerror (errno));
2455 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2457 log_error ("error allocating connection data for %s: %s\n",
2458 listentbl[idx].name, strerror (errno) );
2459 assuan_sock_close (fd);
2461 else if ( !(ctrl->session_env = session_env_new ()))
2463 log_error ("error allocating session env block for %s: %s\n",
2464 listentbl[idx].name, strerror (errno) );
2466 assuan_sock_close (fd);
2470 ctrl->thread_startup.fd = fd;
2471 ret = npth_create (&thread, &tattr,
2472 listentbl[idx].func, ctrl);
2475 log_error ("error spawning connection handler for %s:"
2476 " %s\n", listentbl[idx].name, strerror (ret));
2477 assuan_sock_close (fd);
2481 fd = GNUPG_INVALID_FD;
2487 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2488 npth_attr_destroy (&tattr);
2493 /* Helper for check_own_socket. */
2495 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2497 membuf_t *mb = opaque;
2498 put_membuf (mb, buffer, length);
2503 /* The thread running the actual check. We need to run this in a
2504 separate thread so that check_own_thread can be called from the
2507 check_own_socket_thread (void *arg)
2510 char *sockname = arg;
2511 assuan_context_t ctx = NULL;
2515 check_own_socket_running++;
2517 rc = assuan_new (&ctx);
2520 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2524 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2527 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2531 init_membuf (&mb, 100);
2532 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2533 NULL, NULL, NULL, NULL);
2534 put_membuf (&mb, "", 1);
2535 buffer = get_membuf (&mb, NULL);
2538 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2539 "GETINFO pid", gpg_strerror (rc));
2542 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2544 log_error ("socket is now serviced by another server\n");
2547 else if (opt.verbose > 1)
2548 log_error ("socket is still served by this server\n");
2555 assuan_release (ctx);
2558 /* We may not remove the socket as it is now in use by another
2559 server. Setting the name to empty does this. */
2562 if (socket_name_ssh)
2563 *socket_name_ssh = 0;
2564 shutdown_pending = 2;
2565 log_info ("this process is useless - shutting down\n");
2567 check_own_socket_running--;
2572 /* Check whether we are still listening on our own socket. In case
2573 another gpg-agent process started after us has taken ownership of
2574 our socket, we would linger around without any real task. Thus we
2575 better check once in a while whether we are really needed. */
2577 check_own_socket (void)
2584 if (disable_check_own_socket)
2587 if (check_own_socket_running || shutdown_pending)
2588 return; /* Still running or already shutting down. */
2590 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2592 return; /* Out of memory. */
2594 err = npth_attr_init (&tattr);
2597 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2598 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2600 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2601 npth_attr_destroy (&tattr);
2606 /* Figure out whether an agent is available and running. Prints an
2607 error if not. If SILENT is true, no messages are printed.
2608 Returns 0 if the agent is running. */
2610 check_for_running_agent (int silent)
2614 assuan_context_t ctx = NULL;
2616 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2618 err = assuan_new (&ctx);
2620 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2625 log_error (_("no gpg-agent running in this session\n"));
2628 assuan_release (ctx);
2632 if (!opt.quiet && !silent)
2633 log_info ("gpg-agent running and available\n");
2635 assuan_release (ctx);