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
95 oPinentryInvisibleChar,
107 oEnforcePassphraseConstraints,
109 oMinPassphraseNonalpha,
110 oCheckPassphrasePattern,
112 oEnablePassphraseHistory,
114 oNoUseStandardSocket,
119 oIgnoreCacheForSigning,
122 oAllowPresetPassphrase,
123 oAllowLoopbackPinentry,
124 oNoAllowExternalCache,
131 oDisableCheckOwnSocket,
137 # define ENAMETOOLONG EINVAL
141 static ARGPARSE_OPTS opts[] = {
143 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
144 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
145 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
147 ARGPARSE_group (301, N_("@Options:\n ")),
149 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
150 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
151 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
152 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
153 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
154 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
155 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
157 ARGPARSE_s_s (oDebug, "debug", "@"),
158 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
159 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
160 ARGPARSE_s_i (oDebugWait," debug-wait", "@"),
161 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
162 ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
164 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
165 ARGPARSE_s_n (oNoGrab, "no-grab", N_("do not grab keyboard and mouse")),
166 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
167 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
168 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
169 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
170 ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
171 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
172 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
173 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
174 /* */ N_("do not use the SCdaemon") ),
175 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
177 ARGPARSE_s_s (oExtraSocket, "extra-socket",
178 /* */ N_("|NAME|accept some commands via NAME")),
180 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
182 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
184 ARGPARSE_s_n (oBatch, "batch", "@"),
185 ARGPARSE_s_s (oHomedir, "homedir", "@"),
187 ARGPARSE_s_s (oDisplay, "display", "@"),
188 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
189 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
190 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
191 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
192 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
193 ARGPARSE_s_n (oKeepTTY, "keep-tty",
194 /* */ N_("ignore requests to change the TTY")),
195 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
196 /* */ N_("ignore requests to change the X display")),
198 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
199 N_("|N|expire cached PINs after N seconds")),
200 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
201 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
202 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
204 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
206 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
207 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
208 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
209 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
210 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
212 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
213 /* */ N_("do not use the PIN cache when signing")),
214 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
215 /* */ N_("disallow the use of an external password cache")),
216 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
217 /* */ N_("disallow clients to mark keys as \"trusted\"")),
218 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
219 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
220 /* */ N_("allow presetting passphrase")),
221 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry",
222 N_("allow caller to override the pinentry")),
223 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
224 /* */ N_("allow passphrase to be prompted through Emacs")),
226 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
227 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
228 #ifdef HAVE_W32_SYSTEM
229 /* */ N_("enable putty support")
235 /* Dummy options for backward compatibility. */
236 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
237 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
238 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
240 {0} /* End of list */
244 /* The list of supported debug flags. */
245 static struct debug_flags_s debug_flags [] =
247 { DBG_COMMAND_VALUE, "command" },
248 { DBG_MPI_VALUE , "mpi" },
249 { DBG_CRYPTO_VALUE , "crypto" },
250 { DBG_MEMORY_VALUE , "memory" },
251 { DBG_CACHE_VALUE , "cache" },
252 { DBG_MEMSTAT_VALUE, "memstat" },
253 { DBG_HASHING_VALUE, "hashing" },
254 { DBG_IPC_VALUE , "ipc" },
255 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
260 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
261 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
262 #define MAX_CACHE_TTL (120*60) /* 2 hours */
263 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
264 #define MIN_PASSPHRASE_LEN (8)
265 #define MIN_PASSPHRASE_NONALPHA (1)
266 #define MAX_PASSPHRASE_DAYS (0)
268 /* The timer tick used for housekeeping stuff. For Windows we use a
269 longer period as the SetWaitableTimer seems to signal earlier than
270 the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
271 check our own socket in standard socket mode. If that value is 0
272 we don't check at all. All values are in seconds. */
273 #if defined(HAVE_W32CE_SYSTEM)
274 # define TIMERTICK_INTERVAL (60)
275 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
276 #elif defined(HAVE_W32_SYSTEM)
277 # define TIMERTICK_INTERVAL (4)
278 # define CHECK_OWN_SOCKET_INTERVAL (60)
280 # define TIMERTICK_INTERVAL (2)
281 # define CHECK_OWN_SOCKET_INTERVAL (60)
285 /* Flag indicating that the ssh-agent subsystem has been enabled. */
286 static int ssh_support;
288 #ifdef HAVE_W32_SYSTEM
289 /* Flag indicating that support for Putty has been enabled. */
290 static int putty_support;
291 /* A magic value used with WM_COPYDATA. */
292 #define PUTTY_IPC_MAGIC 0x804e50ba
293 /* To avoid surprises we limit the size of the mapped IPC file to this
294 value. Putty currently (0.62) uses 8k, thus 16k should be enough
295 for the foreseeable future. */
296 #define PUTTY_IPC_MAXLEN 16384
297 #endif /*HAVE_W32_SYSTEM*/
299 /* The list of open file descriptors at startup. Note that this list
300 has been allocated using the standard malloc. */
301 static int *startup_fd_list;
303 /* The signal mask at startup and a flag telling whether it is valid. */
304 #ifdef HAVE_SIGPROCMASK
305 static sigset_t startup_signal_mask;
306 static int startup_signal_mask_valid;
309 /* Flag to indicate that a shutdown was requested. */
310 static int shutdown_pending;
312 /* Counter for the currently running own socket checks. */
313 static int check_own_socket_running;
315 /* Flags to indicate that check_own_socket shall not be called. */
316 static int disable_check_own_socket;
318 /* It is possible that we are currently running under setuid permissions */
319 static int maybe_setuid = 1;
321 /* Name of the communication socket used for native gpg-agent
322 requests. The second variable is either NULL or a malloced string
323 with the real socket name in case it has been redirected. */
324 static char *socket_name;
325 static char *redir_socket_name;
327 /* Name of the optional extra socket used for native gpg-agent requests. */
328 static char *socket_name_extra;
329 static char *redir_socket_name_extra;
331 /* Name of the optional browser socket used for native gpg-agent requests. */
332 static char *socket_name_browser;
333 static char *redir_socket_name_browser;
335 /* Name of the communication socket used for ssh-agent-emulation. */
336 static char *socket_name_ssh;
337 static char *redir_socket_name_ssh;
339 /* We need to keep track of the server's nonces (these are dummies for
341 static assuan_sock_nonce_t socket_nonce;
342 static assuan_sock_nonce_t socket_nonce_extra;
343 static assuan_sock_nonce_t socket_nonce_browser;
344 static assuan_sock_nonce_t socket_nonce_ssh;
347 /* Default values for options passed to the pinentry. */
348 static char *default_display;
349 static char *default_ttyname;
350 static char *default_ttytype;
351 static char *default_lc_ctype;
352 static char *default_lc_messages;
353 static char *default_xauthority;
355 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
356 static char *config_filename;
358 /* Helper to implement --debug-level */
359 static const char *debug_level;
361 /* Keep track of the current log file so that we can avoid updating
362 the log file after a SIGHUP if it didn't changed. Malloced. */
363 static char *current_logfile;
365 /* The handle_tick() function may test whether a parent is still
366 running. We record the PID of the parent here or -1 if it should be
368 static pid_t parent_pid = (pid_t)(-1);
370 /* Number of active connections. */
371 static int active_connections;
378 static char *create_socket_name (char *standard_name, int with_homedir);
379 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
381 assuan_sock_nonce_t *nonce);
382 static void create_directories (void);
384 static void agent_init_default_ctrl (ctrl_t ctrl);
385 static void agent_deinit_default_ctrl (ctrl_t ctrl);
387 static void handle_connections (gnupg_fd_t listen_fd,
388 gnupg_fd_t listen_fd_extra,
389 gnupg_fd_t listen_fd_browser,
390 gnupg_fd_t listen_fd_ssh);
391 static void check_own_socket (void);
392 static int check_for_running_agent (int silent);
394 /* Pth wrapper function definitions. */
395 ASSUAN_SYSTEM_NPTH_IMPL;
402 /* Allocate a string describing a library version by calling a GETFNC.
403 This function is expected to be called only once. GETFNC is
404 expected to have a semantic like gcry_check_version (). */
406 make_libversion (const char *libname, const char *(*getfnc)(const char*))
413 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
417 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
418 strcpy (stpcpy (stpcpy (result, libname), " "), s);
422 /* Return strings describing this program. The case values are
423 described in common/argparse.c:strusage. The values here override
424 the default values given by strusage. */
426 my_strusage (int level)
428 static char *ver_gcry;
433 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
435 case 13: p = VERSION; break;
436 case 17: p = PRINTABLE_OS_NAME; break;
437 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
438 reporting address. This is so that we can change the
439 reporting address without breaking the translations. */
440 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
444 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
449 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
451 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
452 "Secret key management for @GNUPG@\n");
462 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
463 only the active debug flags are propagated to the subsystems. With
464 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
465 all flags already set. Note that we don't fail here, because it is
466 important to keep gpg-agent running even after re-reading the
467 options due to a SIGHUP. */
471 int numok = (debug_level && digitp (debug_level));
472 int numlvl = numok? atoi (debug_level) : 0;
476 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
478 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
479 opt.debug = DBG_IPC_VALUE;
480 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
481 opt.debug = DBG_IPC_VALUE|DBG_COMMAND_VALUE;
482 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
483 opt.debug = (DBG_IPC_VALUE|DBG_COMMAND_VALUE
485 else if (!strcmp (debug_level, "guru") || numok)
488 /* Unless the "guru" string has been used we don't want to allow
489 hashing debugging. The rationale is that people tend to
490 select the highest debug value and would then clutter their
491 disk with debug files which may reveal confidential data. */
493 opt.debug &= ~(DBG_HASHING_VALUE);
497 log_error (_("invalid debug-level '%s' given\n"), debug_level);
498 opt.debug = 0; /* Reset debugging, so that prior debug
499 statements won't have an undesired effect. */
502 if (opt.debug && !opt.verbose)
504 if (opt.debug && opt.quiet)
507 if (opt.debug & DBG_MPI_VALUE)
508 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
509 if (opt.debug & DBG_CRYPTO_VALUE )
510 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
511 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
514 parse_debug_flag (NULL, &opt.debug, debug_flags);
518 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
519 the corresponding real name if the socket has been redirected. */
521 remove_socket (char *name, char *redir_name)
531 p = strrchr (name, '/');
543 /* Cleanup code for this program. This is either called has an atexit
544 handler or directly. */
553 deinitialize_module_cache ();
554 remove_socket (socket_name, redir_socket_name);
555 if (opt.extra_socket > 1)
556 remove_socket (socket_name_extra, redir_socket_name_extra);
557 if (opt.browser_socket > 1)
558 remove_socket (socket_name_browser, redir_socket_name_browser);
559 remove_socket (socket_name_ssh, redir_socket_name_ssh);
564 /* Handle options which are allowed to be reset after program start.
565 Return true when the current option in PARGS could be handled and
566 false if not. As a special feature, passing a value of NULL for
567 PARGS, resets the options to the default. REREAD should be set
568 true if it is not the initial option parsing. */
570 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
578 opt.debug_pinentry = 0;
579 opt.pinentry_program = NULL;
580 opt.pinentry_touch_file = NULL;
581 xfree (opt.pinentry_invisible_char);
582 opt.pinentry_invisible_char = NULL;
583 opt.scdaemon_program = NULL;
584 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
585 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
586 opt.max_cache_ttl = MAX_CACHE_TTL;
587 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
588 opt.enforce_passphrase_constraints = 0;
589 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
590 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
591 opt.check_passphrase_pattern = NULL;
592 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
593 opt.enable_passhrase_history = 0;
594 opt.ignore_cache_for_signing = 0;
595 opt.allow_mark_trusted = 1;
596 opt.allow_external_cache = 1;
597 opt.allow_emacs_pinentry = 0;
598 opt.disable_scdaemon = 0;
599 disable_check_own_socket = 0;
603 switch (pargs->r_opt)
605 case oQuiet: opt.quiet = 1; break;
606 case oVerbose: opt.verbose++; break;
609 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
611 case oDebugAll: opt.debug = ~0; break;
612 case oDebugLevel: debug_level = pargs->r.ret_str; break;
613 case oDebugPinentry: opt.debug_pinentry = 1; break;
617 return 0; /* not handeld */
618 if (!current_logfile || !pargs->r.ret_str
619 || strcmp (current_logfile, pargs->r.ret_str))
621 log_set_file (pargs->r.ret_str);
622 xfree (current_logfile);
623 current_logfile = xtrystrdup (pargs->r.ret_str);
627 case oNoGrab: opt.no_grab = 1; break;
629 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
630 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
631 case oPinentryInvisibleChar:
632 xfree (opt.pinentry_invisible_char);
633 opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
635 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
636 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
637 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
639 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
640 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
641 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
642 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
644 case oEnforcePassphraseConstraints:
645 opt.enforce_passphrase_constraints=1;
647 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
648 case oMinPassphraseNonalpha:
649 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
651 case oCheckPassphrasePattern:
652 opt.check_passphrase_pattern = pargs->r.ret_str;
654 case oMaxPassphraseDays:
655 opt.max_passphrase_days = pargs->r.ret_ulong;
657 case oEnablePassphraseHistory:
658 opt.enable_passhrase_history = 1;
661 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
663 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
664 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
666 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
668 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
670 case oNoAllowExternalCache: opt.allow_external_cache = 0;
673 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
677 return 0; /* not handled */
680 return 1; /* handled */
684 /* Fixup some options after all have been processed. */
686 finalize_rereadable_options (void)
692 /* The main entry point. */
694 main (int argc, char **argv )
699 FILE *configfp = NULL;
700 char *configname = NULL;
702 unsigned configlineno;
704 int default_config =1;
709 char *logfile = NULL;
711 int gpgconf_list = 0;
713 struct assuan_malloc_hooks malloc_hooks;
715 early_system_init ();
717 /* Before we do anything else we save the list of currently open
718 file descriptors and the signal mask. This info is required to
719 do the exec call properly. */
720 startup_fd_list = get_all_open_fds ();
721 #ifdef HAVE_SIGPROCMASK
722 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
723 startup_signal_mask_valid = 1;
724 #endif /*HAVE_SIGPROCMASK*/
726 /* Set program name etc. */
727 set_strusage (my_strusage);
728 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
729 /* Please note that we may running SUID(ROOT), so be very CAREFUL
730 when adding any stuff between here and the call to INIT_SECMEM()
731 somewhere after the option parsing */
732 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
734 /* Make sure that our subsystems are ready. */
736 init_common_subsystems (&argc, &argv);
740 /* Check that the libraries are suitable. Do it here because
741 the option parsing may need services of the library. */
742 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
744 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
745 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
748 malloc_hooks.malloc = gcry_malloc;
749 malloc_hooks.realloc = gcry_realloc;
750 malloc_hooks.free = gcry_free;
751 assuan_set_malloc_hooks (&malloc_hooks);
752 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
753 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
755 setup_libassuan_logging (&opt.debug);
757 setup_libgcrypt_logging ();
758 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
760 disable_core_dumps ();
762 /* Set default options. */
763 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
765 shell = getenv ("SHELL");
766 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
769 opt.homedir = default_homedir ();
771 /* Record some of the original environment strings. */
775 static const char *names[] =
776 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
779 opt.startup_env = session_env_new ();
780 if (!opt.startup_env)
781 err = gpg_error_from_syserror ();
782 for (idx=0; !err && names[idx]; idx++)
784 s = getenv (names[idx]);
786 err = session_env_setenv (opt.startup_env, names[idx], s);
790 s = gnupg_ttyname (0);
792 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
795 log_fatal ("error recording startup environment: %s\n",
798 /* Fixme: Better use the locale function here. */
799 opt.startup_lc_ctype = getenv ("LC_CTYPE");
800 if (opt.startup_lc_ctype)
801 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
802 opt.startup_lc_messages = getenv ("LC_MESSAGES");
803 if (opt.startup_lc_messages)
804 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
807 /* Check whether we have a config file on the commandline */
812 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
813 while (arg_parse( &pargs, opts))
815 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
817 else if (pargs.r_opt == oOptions)
818 { /* yes there is one, so we do not try the default one, but
819 read the option file when it is encountered at the
823 else if (pargs.r_opt == oNoOptions)
824 default_config = 0; /* --no-options */
825 else if (pargs.r_opt == oHomedir)
826 opt.homedir = pargs.r.ret_str;
827 else if (pargs.r_opt == oDebugQuickRandom)
829 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
834 /* Initialize the secure memory. */
835 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
839 Now we are now working under our real uid
843 configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
850 pargs.flags= 1; /* do not remove the args */
855 configfp = fopen (configname, "r");
861 log_info (_("Note: no default option file '%s'\n"),
863 /* Save the default conf file name so that
864 reread_configuration is able to test whether the
865 config file has been created in the meantime. */
866 xfree (config_filename);
867 config_filename = configname;
872 log_error (_("option file '%s': %s\n"),
873 configname, strerror(errno) );
879 if (parse_debug && configname )
880 log_info (_("reading options from '%s'\n"), configname );
884 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
886 if (parse_rereadable_options (&pargs, 0))
887 continue; /* Already handled */
890 case aGPGConfList: gpgconf_list = 1; break;
891 case aGPGConfTest: gpgconf_list = 2; break;
892 case aUseStandardSocketP: gpgconf_list = 3; break;
893 case oBatch: opt.batch=1; break;
895 case oDebugWait: debug_wait = pargs.r.ret_int; break;
898 /* config files may not be nested (silently ignore them) */
902 configname = xstrdup(pargs.r.ret_str);
906 case oNoGreeting: /* Dummy option. */ break;
907 case oNoVerbose: opt.verbose = 0; break;
908 case oNoOptions: break; /* no-options */
909 case oHomedir: opt.homedir = pargs.r.ret_str; break;
910 case oNoDetach: nodetach = 1; break;
911 case oLogFile: logfile = pargs.r.ret_str; break;
912 case oCsh: csh_style = 1; break;
913 case oSh: csh_style = 0; break;
914 case oServer: pipe_server = 1; break;
915 case oDaemon: is_daemon = 1; break;
917 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
918 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
919 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
920 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
921 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
923 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
926 case oUseStandardSocket:
927 case oNoUseStandardSocket:
928 obsolete_option (configname, configlineno, "use-standard-socket");
931 case oFakedSystemTime:
933 time_t faked_time = isotime2epoch (pargs.r.ret_str);
934 if (faked_time == (time_t)(-1))
935 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
936 gnupg_set_time (faked_time, 0);
940 case oKeepTTY: opt.keep_tty = 1; break;
941 case oKeepDISPLAY: opt.keep_display = 1; break;
947 # ifdef HAVE_W32_SYSTEM
953 opt.extra_socket = 1; /* (1 = points into argv) */
954 socket_name_extra = pargs.r.ret_str;
958 opt.browser_socket = 1; /* (1 = points into argv) */
959 socket_name_browser = pargs.r.ret_str;
962 case oDebugQuickRandom:
963 /* Only used by the first stage command line parser. */
967 obsolete_option (configname, configlineno, "write-env-file");
970 default : pargs.err = configfp? 1:2; break;
977 /* Keep a copy of the name so that it can be read on SIGHUP. */
978 if (config_filename != configname)
980 xfree (config_filename);
981 config_filename = configname;
989 if (log_get_errorcount(0))
992 finalize_rereadable_options ();
994 /* Turn the homedir into an absolute one. */
995 opt.homedir = make_absfilename (opt.homedir, NULL);
997 /* Print a warning if an argument looks like an option. */
998 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1002 for (i=0; i < argc; i++)
1003 if (argv[i][0] == '-' && argv[i][1] == '-')
1004 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1008 /* gpg-agent usually does not output any messages because it runs in
1009 the background. For log files it is acceptable to have messages
1010 always encoded in utf-8. We switch here to utf-8, so that
1011 commands like --help still give native messages. It is far
1012 easier to switch only once instead of for every message and it
1013 actually helps when more then one thread is active (avoids an
1014 extra copy step). */
1015 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1018 if (!pipe_server && !is_daemon && !gpgconf_list)
1020 /* We have been called without any options and thus we merely
1021 check whether an agent is already running. We do this right
1022 here so that we don't clobber a logfile with this check but
1023 print the status directly to stderr. */
1026 check_for_running_agent (0);
1032 if (atexit (cleanup))
1034 log_error ("atexit failed\n");
1039 initialize_module_cache ();
1040 initialize_module_call_pinentry ();
1041 initialize_module_call_scd ();
1042 initialize_module_trustlist ();
1044 /* Try to create missing directories. */
1045 create_directories ();
1047 if (debug_wait && pipe_server)
1049 log_debug ("waiting for debugger - my pid is %u .....\n",
1050 (unsigned int)getpid());
1051 gnupg_sleep (debug_wait);
1052 log_debug ("... okay\n");
1055 if (gpgconf_list == 3)
1057 /* We now use the standard socket always - return true for
1058 backward compatibility. */
1061 else if (gpgconf_list == 2)
1063 else if (gpgconf_list)
1068 /* List options and default values in the GPG Conf format. */
1069 filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
1071 filename_esc = percent_escape (filename, NULL);
1073 es_printf ("%s-%s.conf:%lu:\"%s\n",
1074 GPGCONF_NAME, GPG_AGENT_NAME,
1075 GC_OPT_FLAG_DEFAULT, filename_esc);
1077 xfree (filename_esc);
1079 es_printf ("verbose:%lu:\n"
1081 "debug-level:%lu:\"none:\n"
1083 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1084 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1085 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1086 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1087 es_printf ("default-cache-ttl:%lu:%d:\n",
1088 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1089 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1090 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1091 es_printf ("max-cache-ttl:%lu:%d:\n",
1092 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1093 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1094 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1095 es_printf ("enforce-passphrase-constraints:%lu:\n",
1096 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1097 es_printf ("min-passphrase-len:%lu:%d:\n",
1098 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1099 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1100 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1101 MIN_PASSPHRASE_NONALPHA);
1102 es_printf ("check-passphrase-pattern:%lu:\n",
1103 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1104 es_printf ("max-passphrase-days:%lu:%d:\n",
1105 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1106 MAX_PASSPHRASE_DAYS);
1107 es_printf ("enable-passphrase-history:%lu:\n",
1108 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1109 es_printf ("no-grab:%lu:\n",
1110 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1111 es_printf ("ignore-cache-for-signing:%lu:\n",
1112 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1113 es_printf ("no-allow-external-cache:%lu:\n",
1114 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1115 es_printf ("no-allow-mark-trusted:%lu:\n",
1116 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1117 es_printf ("disable-scdaemon:%lu:\n",
1118 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1119 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1120 #ifdef HAVE_W32_SYSTEM
1121 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1123 es_printf ("allow-loopback-pinentry:%lu:\n",
1124 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1125 es_printf ("allow-emacs-pinentry:%lu:\n",
1126 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1131 /* Now start with logging to a file if this is desired. */
1134 log_set_file (logfile);
1135 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1136 | GPGRT_LOG_WITH_TIME
1137 | GPGRT_LOG_WITH_PID));
1138 current_logfile = xstrdup (logfile);
1141 /* Make sure that we have a default ttyname. */
1142 if (!default_ttyname && gnupg_ttyname (1))
1143 default_ttyname = xstrdup (gnupg_ttyname (1));
1144 if (!default_ttytype && getenv ("TERM"))
1145 default_ttytype = xstrdup (getenv ("TERM"));
1150 /* This is the simple pipe based server */
1153 ctrl = xtrycalloc (1, sizeof *ctrl);
1156 log_error ("error allocating connection control data: %s\n",
1160 ctrl->session_env = session_env_new ();
1161 if (!ctrl->session_env)
1163 log_error ("error allocating session environment block: %s\n",
1168 agent_init_default_ctrl (ctrl);
1169 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1170 agent_deinit_default_ctrl (ctrl);
1173 else if (!is_daemon)
1176 { /* Regular server mode */
1178 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1179 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1180 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1183 /* Remove the DISPLAY variable so that a pinentry does not
1184 default to a specific display. There is still a default
1185 display when gpg-agent was started using --display or a
1186 client requested this using an OPTION command. Note, that we
1187 don't do this when running in reverse daemon mode (i.e. when
1188 exec the program given as arguments). */
1189 #ifndef HAVE_W32_SYSTEM
1190 if (!opt.keep_display && !argc)
1191 gnupg_unsetenv ("DISPLAY");
1194 /* Remove the INSIDE_EMACS variable so that a pinentry does not
1195 always try to interact with Emacs. The variable is set when
1196 a client requested this using an OPTION command. */
1197 gnupg_unsetenv ("INSIDE_EMACS");
1199 /* Create the sockets. */
1200 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1201 fd = create_server_socket (socket_name, 1, 0,
1202 &redir_socket_name, &socket_nonce);
1204 if (opt.extra_socket)
1206 socket_name_extra = create_socket_name (socket_name_extra, 0);
1207 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1208 fd_extra = create_server_socket (socket_name_extra, 0, 0,
1209 &redir_socket_name_extra,
1210 &socket_nonce_extra);
1213 if (opt.browser_socket)
1215 socket_name_browser = create_socket_name (socket_name_browser, 0);
1216 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1217 fd_browser = create_server_socket (socket_name_browser, 0, 0,
1218 &redir_socket_name_browser,
1219 &socket_nonce_browser);
1224 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1225 fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1226 &redir_socket_name_ssh,
1230 /* If we are going to exec a program in the parent, we record
1231 the PID, so that the child may check whether the program is
1234 parent_pid = getpid ();
1237 #ifdef HAVE_W32_SYSTEM
1241 #else /*!HAVE_W32_SYSTEM*/
1243 if (pid == (pid_t)-1)
1245 log_fatal ("fork failed: %s\n", strerror (errno) );
1249 { /* We are the parent */
1250 char *infostr_ssh_sock, *infostr_ssh_valid;
1252 /* Close the socket FD. */
1255 /* The signal mask might not be correct right now and thus
1256 we restore it. That is not strictly necessary but some
1257 programs falsely assume a cleared signal mask. */
1259 #ifdef HAVE_SIGPROCMASK
1260 if (startup_signal_mask_valid)
1262 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1263 log_error ("error restoring signal mask: %s\n",
1267 log_info ("no saved signal mask\n");
1268 #endif /*HAVE_SIGPROCMASK*/
1270 /* Create the SSH info string if enabled. */
1273 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1274 socket_name_ssh) < 0)
1276 log_error ("out of core\n");
1277 kill (pid, SIGTERM);
1280 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1281 (unsigned long)getpid()) < 0)
1283 log_error ("out of core\n");
1284 kill (pid, SIGTERM);
1289 *socket_name = 0; /* Don't let cleanup() remove the socket -
1290 the child should do this from now on */
1291 if (opt.extra_socket)
1292 *socket_name_extra = 0;
1293 if (opt.browser_socket)
1294 *socket_name_browser = 0;
1296 *socket_name_ssh = 0;
1299 { /* Run the program given on the commandline. */
1300 if (ssh_support && (putenv (infostr_ssh_sock)
1301 || putenv (infostr_ssh_valid)))
1303 log_error ("failed to set environment: %s\n",
1305 kill (pid, SIGTERM );
1309 /* Close all the file descriptors except the standard
1310 ones and those open at startup. We explicitly don't
1311 close 0,1,2 in case something went wrong collecting
1313 close_all_fds (3, startup_fd_list);
1315 /* Run the command. */
1316 execvp (argv[0], argv);
1317 log_error ("failed to run the command: %s\n", strerror (errno));
1318 kill (pid, SIGTERM);
1323 /* Print the environment string, so that the caller can use
1324 shell's eval to set it */
1329 *strchr (infostr_ssh_sock, '=') = ' ';
1330 es_printf ("setenv %s;\n", infostr_ssh_sock);
1337 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1343 xfree (infostr_ssh_sock);
1344 xfree (infostr_ssh_valid);
1355 /* Detach from tty and put process into a new session */
1359 unsigned int oldflags;
1361 /* Close stdin, stdout and stderr unless it is the log stream */
1362 for (i=0; i <= 2; i++)
1364 if (!log_test_fd (i) && i != fd )
1367 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1369 log_error ("failed to open '%s': %s\n",
1370 "/dev/null", strerror (errno));
1378 log_error ("setsid() failed: %s\n", strerror(errno) );
1383 log_get_prefix (&oldflags);
1384 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1385 opt.running_detached = 1;
1390 log_error ("chdir to / failed: %s\n", strerror (errno));
1395 struct sigaction sa;
1397 sa.sa_handler = SIG_IGN;
1398 sigemptyset (&sa.sa_mask);
1400 sigaction (SIGPIPE, &sa, NULL);
1402 #endif /*!HAVE_W32_SYSTEM*/
1404 log_info ("%s %s started\n", strusage(11), strusage(13) );
1405 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1406 assuan_sock_close (fd);
1413 /* Exit entry point. This function should be called instead of a
1418 /*FIXME: update_random_seed_file();*/
1420 /* We run our cleanup handler because that may close cipher contexts
1421 stored in secure memory and thus this needs to be done before we
1422 explicitly terminate secure memory. */
1426 /* at this time a bit annoying */
1427 if (opt.debug & DBG_MEMSTAT_VALUE)
1429 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1430 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1433 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1435 gcry_control (GCRYCTL_TERM_SECMEM );
1436 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1441 /* Each thread has its own local variables conveyed by a control
1442 structure usually identified by an argument named CTRL. This
1443 function is called immediately after allocating the control
1444 structure. Its purpose is to setup the default values for that
1445 structure. Note that some values may have already been set. */
1447 agent_init_default_ctrl (ctrl_t ctrl)
1449 assert (ctrl->session_env);
1451 /* Note we ignore malloc errors because we can't do much about it
1452 and the request will fail anyway shortly after this
1454 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1455 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1456 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1457 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1458 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1461 xfree (ctrl->lc_ctype);
1462 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1464 if (ctrl->lc_messages)
1465 xfree (ctrl->lc_messages);
1466 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1468 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1472 /* Release all resources allocated by default in the control
1473 structure. This is the counterpart to agent_init_default_ctrl. */
1475 agent_deinit_default_ctrl (ctrl_t ctrl)
1477 session_env_release (ctrl->session_env);
1480 xfree (ctrl->lc_ctype);
1481 if (ctrl->lc_messages)
1482 xfree (ctrl->lc_messages);
1486 /* Because the ssh protocol does not send us information about the
1487 current TTY setting, we use this function to use those from startup
1488 or those explictly set. This is also used for the restricted mode
1489 where we ignore requests to change the environment. */
1491 agent_copy_startup_env (ctrl_t ctrl)
1493 static const char *names[] =
1494 {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1495 gpg_error_t err = 0;
1499 for (idx=0; !err && names[idx]; idx++)
1500 if ((value = session_env_getenv (opt.startup_env, names[idx])))
1501 err = session_env_setenv (ctrl->session_env, names[idx], value);
1503 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1504 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1505 err = gpg_error_from_syserror ();
1507 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1508 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1509 err = gpg_error_from_syserror ();
1512 log_error ("error setting default session environment: %s\n",
1513 gpg_strerror (err));
1519 /* Reread parts of the configuration. Note, that this function is
1520 obviously not thread-safe and should only be called from the PTH
1523 Fixme: Due to the way the argument parsing works, we create a
1524 memory leak here for all string type arguments. There is currently
1525 no clean way to tell whether the memory for the argument has been
1526 allocated or points into the process' original arguments. Unless
1527 we have a mechanism to tell this, we need to live on with this. */
1529 reread_configuration (void)
1531 ARGPARSE_ARGS pargs;
1533 unsigned int configlineno = 0;
1536 if (!config_filename)
1537 return; /* No config file. */
1539 fp = fopen (config_filename, "r");
1542 log_info (_("option file '%s': %s\n"),
1543 config_filename, strerror(errno) );
1547 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1549 memset (&pargs, 0, sizeof pargs);
1551 pargs.argc = &dummy;
1552 pargs.flags = 1; /* do not remove the args */
1553 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1555 if (pargs.r_opt < -1)
1556 pargs.err = 1; /* Print a warning. */
1557 else /* Try to parse this option - ignore unchangeable ones. */
1558 parse_rereadable_options (&pargs, 1);
1561 finalize_rereadable_options ();
1566 /* Return the file name of the socket we are using for native
1569 get_agent_socket_name (void)
1571 const char *s = socket_name;
1573 return (s && *s)? s : NULL;
1576 /* Return the file name of the socket we are using for SSH
1579 get_agent_ssh_socket_name (void)
1581 const char *s = socket_name_ssh;
1583 return (s && *s)? s : NULL;
1587 /* Under W32, this function returns the handle of the scdaemon
1588 notification event. Calling it the first time creates that
1590 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1592 get_agent_scd_notify_event (void)
1594 static HANDLE the_event = INVALID_HANDLE_VALUE;
1596 if (the_event == INVALID_HANDLE_VALUE)
1599 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1601 /* We need to use a manual reset event object due to the way our
1602 w32-pth wait function works: If we would use an automatic
1603 reset event we are not able to figure out which handle has
1604 been signaled because at the time we single out the signaled
1605 handles using WFSO the event has already been reset due to
1607 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1609 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1610 else if (!DuplicateHandle (GetCurrentProcess(), h,
1611 GetCurrentProcess(), &h2,
1612 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1614 log_error ("setting syncronize for scd notify event failed: %s\n",
1615 w32_strerror (-1) );
1627 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1631 /* Create a name for the socket in the home directory as using
1632 STANDARD_NAME. We also check for valid characters as well as
1633 against a maximum allowed length for a unix domain socket is done.
1634 The function terminates the process in case of an error. Returns:
1635 Pointer to an allocated string with the absolute name of the socket
1638 create_socket_name (char *standard_name, int with_homedir)
1643 name = make_filename (opt.homedir, standard_name, NULL);
1645 name = make_filename (standard_name, NULL);
1646 if (strchr (name, PATHSEP_C))
1648 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1656 /* Create a Unix domain socket with NAME. Returns the file descriptor
1657 or terminates the process in case of an error. Note that this
1658 function needs to be used for the regular socket first (indicated
1659 by PRIMARY) and only then for the extra and the ssh sockets. If
1660 the socket has been redirected the name of the real socket is
1661 stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
1662 Cygwin compatible socket is created (Windows only). */
1664 create_server_socket (char *name, int primary, int cygwin,
1665 char **r_redir_name, assuan_sock_nonce_t *nonce)
1667 struct sockaddr *addr;
1668 struct sockaddr_un *unaddr;
1673 xfree (*r_redir_name);
1674 *r_redir_name = NULL;
1676 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1677 if (fd == ASSUAN_INVALID_FD)
1679 log_error (_("can't create socket: %s\n"), strerror (errno));
1680 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1684 #if ASSUAN_VERSION_NUMBER >= 0x020300 /* >= 2.3.0 */
1686 assuan_sock_set_flag (fd, "cygwin", 1);
1691 unaddr = xmalloc (sizeof *unaddr);
1692 addr = (struct sockaddr*)unaddr;
1694 #if ASSUAN_VERSION_NUMBER >= 0x020104 /* >= 2.1.4 */
1698 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1700 if (errno == ENAMETOOLONG)
1701 log_error (_("socket name '%s' is too long\n"), name);
1703 log_error ("error preparing socket '%s': %s\n",
1704 name, gpg_strerror (gpg_error_from_syserror ()));
1705 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1710 *r_redir_name = xstrdup (unaddr->sun_path);
1712 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1715 #else /* Assuan < 2.1.4 */
1716 memset (unaddr, 0, sizeof *unaddr);
1717 unaddr->sun_family = AF_UNIX;
1718 if (strlen (name) + 1 >= sizeof (unaddr->sun_path))
1720 log_error (_("socket name '%s' is too long\n"), name);
1721 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1724 strcpy (unaddr->sun_path, name);
1725 #endif /* Assuan < 2.1.4 */
1727 len = SUN_LEN (unaddr);
1728 rc = assuan_sock_bind (fd, addr, len);
1730 /* Our error code mapping on W32CE returns EEXIST thus we also test
1733 && (errno == EADDRINUSE
1734 #ifdef HAVE_W32_SYSTEM
1739 /* Check whether a gpg-agent is already running. We do this
1740 test only if this is the primary socket. For secondary
1741 sockets we assume that a test for gpg-agent has already been
1742 done and reuse the requested socket. Testing the ssh-socket
1743 is not possible because at this point, though we know the new
1744 Assuan socket, the Assuan server and thus the ssh-agent
1745 server is not yet operational; this would lead to a hang. */
1746 if (primary && !check_for_running_agent (1))
1748 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
1749 log_set_file (NULL);
1750 log_error (_("a gpg-agent is already running - "
1751 "not starting a new one\n"));
1752 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1753 assuan_sock_close (fd);
1756 gnupg_remove (unaddr->sun_path);
1757 rc = assuan_sock_bind (fd, addr, len);
1759 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1760 log_error (_("error getting nonce for the socket\n"));
1763 /* We use gpg_strerror here because it allows us to get strings
1764 for some W32 socket error codes. */
1765 log_error (_("error binding socket to '%s': %s\n"),
1767 gpg_strerror (gpg_error_from_syserror ()));
1769 assuan_sock_close (fd);
1770 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1774 if (listen (FD2INT(fd), 5 ) == -1)
1776 log_error (_("listen() failed: %s\n"), strerror (errno));
1777 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1778 assuan_sock_close (fd);
1783 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1789 /* Check that the directory for storing the private keys exists and
1790 create it if not. This function won't fail as it is only a
1791 convenience function and not strictly necessary. */
1793 create_private_keys_directory (const char *home)
1796 struct stat statbuf;
1798 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1799 if (stat (fname, &statbuf) && errno == ENOENT)
1801 if (gnupg_mkdir (fname, "-rwx"))
1802 log_error (_("can't create directory '%s': %s\n"),
1803 fname, strerror (errno) );
1804 else if (!opt.quiet)
1805 log_info (_("directory '%s' created\n"), fname);
1810 /* Create the directory only if the supplied directory name is the
1811 same as the default one. This way we avoid to create arbitrary
1812 directories when a non-default home directory is used. To cope
1813 with HOME, we compare only the suffix if we see that the default
1814 homedir does start with a tilde. We don't stop here in case of
1815 problems because other functions will throw an error anyway.*/
1817 create_directories (void)
1819 struct stat statbuf;
1820 const char *defhome = standard_homedir ();
1823 home = make_filename (opt.homedir, NULL);
1824 if ( stat (home, &statbuf) )
1826 if (errno == ENOENT)
1829 #ifdef HAVE_W32_SYSTEM
1830 ( !compare_filenames (home, defhome) )
1833 && (strlen (home) >= strlen (defhome+1)
1834 && !strcmp (home + strlen(home)
1835 - strlen (defhome+1), defhome+1)))
1836 || (*defhome != '~' && !strcmp (home, defhome) )
1840 if (gnupg_mkdir (home, "-rwx"))
1841 log_error (_("can't create directory '%s': %s\n"),
1842 home, strerror (errno) );
1846 log_info (_("directory '%s' created\n"), home);
1847 create_private_keys_directory (home);
1852 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1854 else if ( !S_ISDIR(statbuf.st_mode))
1856 log_error (_("can't use '%s' as home directory\n"), home);
1858 else /* exists and is a directory. */
1860 create_private_keys_directory (home);
1867 /* This is the worker for the ticker. It is called every few seconds
1868 and may only do fast operations. */
1872 static time_t last_minute;
1875 last_minute = time (NULL);
1877 /* Check whether the scdaemon has died and cleanup in this case. */
1878 agent_scd_check_aliveness ();
1880 /* If we are running as a child of another process, check whether
1881 the parent is still alive and shutdown if not. */
1882 #ifndef HAVE_W32_SYSTEM
1883 if (parent_pid != (pid_t)(-1))
1885 if (kill (parent_pid, 0))
1887 shutdown_pending = 2;
1888 log_info ("parent process died - shutting down\n");
1889 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1894 #endif /*HAVE_W32_SYSTEM*/
1896 /* Code to be run from time to time. */
1897 #if CHECK_OWN_SOCKET_INTERVAL > 0
1898 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
1900 check_own_socket ();
1901 last_minute = time (NULL);
1908 /* A global function which allows us to call the reload stuff from
1909 other places too. This is only used when build for W32. */
1911 agent_sighup_action (void)
1913 log_info ("SIGHUP received - "
1914 "re-reading configuration and flushing cache\n");
1916 agent_flush_cache ();
1917 reread_configuration ();
1918 agent_reload_trustlist ();
1919 /* We flush the module name cache so that after installing a
1920 "pinentry" binary that one can be used in case the
1921 "pinentry-basic" fallback was in use. */
1922 gnupg_module_name_flush_some ();
1926 /* A helper function to handle SIGUSR2. */
1928 agent_sigusr2_action (void)
1931 log_info ("SIGUSR2 received - updating card event counter\n");
1932 /* Nothing to check right now. We only increment a counter. */
1933 bump_card_eventcounter ();
1937 #ifndef HAVE_W32_SYSTEM
1938 /* The signal handler for this program. It is expected to be run in
1939 its own trhead and not in the context of a signal handler. */
1941 handle_signal (int signo)
1945 #ifndef HAVE_W32_SYSTEM
1947 agent_sighup_action ();
1951 log_info ("SIGUSR1 received - printing internal information:\n");
1952 /* Fixme: We need to see how to integrate pth dumping into our
1954 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1955 agent_query_dump_state ();
1956 agent_scd_dump_state ();
1960 agent_sigusr2_action ();
1964 if (!shutdown_pending)
1965 log_info ("SIGTERM received - shutting down ...\n");
1967 log_info ("SIGTERM received - still %i open connections\n",
1968 active_connections);
1970 if (shutdown_pending > 2)
1972 log_info ("shutdown forced\n");
1973 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1980 log_info ("SIGINT received - immediate shutdown\n");
1981 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1987 log_info ("signal %d received - no action defined\n", signo);
1992 /* Check the nonce on a new connection. This is a NOP unless we we
1993 are using our Unix domain socket emulation under Windows. */
1995 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1997 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1999 log_info (_("error reading nonce on fd %d: %s\n"),
2000 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2001 assuan_sock_close (ctrl->thread_startup.fd);
2010 #ifdef HAVE_W32_SYSTEM
2011 /* The window message processing function for Putty. Warning: This
2012 code runs as a native Windows thread. Use of our own functions
2013 needs to be bracket with pth_leave/pth_enter. */
2014 static LRESULT CALLBACK
2015 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2019 COPYDATASTRUCT *cds;
2020 const char *mapfile;
2025 PSECURITY_DESCRIPTOR psd = NULL;
2028 if (msg != WM_COPYDATA)
2030 return DefWindowProc (hwnd, msg, wparam, lparam);
2033 cds = (COPYDATASTRUCT*)lparam;
2034 if (cds->dwData != PUTTY_IPC_MAGIC)
2035 return 0; /* Ignore data with the wrong magic. */
2036 mapfile = cds->lpData;
2037 if (!cds->cbData || mapfile[cds->cbData - 1])
2038 return 0; /* Ignore empty and non-properly terminated strings. */
2043 log_debug ("ssh map file '%s'", mapfile);
2047 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2051 log_debug ("ssh map handle %p\n", maphd);
2055 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2060 mysid = w32_get_user_sid ();
2063 log_error ("error getting my sid\n");
2067 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2068 OWNER_SECURITY_INFORMATION,
2069 &mapsid, NULL, NULL, NULL,
2073 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2081 if (!ConvertSidToStringSid (mysid, &sidstr))
2083 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2085 if (!ConvertSidToStringSid (mapsid, &sidstr))
2087 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2091 if (!EqualSid (mysid, mapsid))
2093 log_error ("ssh map file has a non-matching sid\n");
2097 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2099 log_debug ("ssh IPC buffer at %p\n", data);
2103 /* log_printhex ("request:", data, 20); */
2105 ctrl = xtrycalloc (1, sizeof *ctrl);
2108 log_error ("error allocating connection control data: %s\n",
2112 ctrl->session_env = session_env_new ();
2113 if (!ctrl->session_env)
2115 log_error ("error allocating session environment block: %s\n",
2120 agent_init_default_ctrl (ctrl);
2121 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2122 ret = 1; /* Valid ssh message has been constructed. */
2123 agent_deinit_default_ctrl (ctrl);
2124 /* log_printhex (" reply:", data, 20); */
2129 UnmapViewOfFile (data);
2134 CloseHandle (maphd);
2140 #endif /*HAVE_W32_SYSTEM*/
2143 #ifdef HAVE_W32_SYSTEM
2144 /* The thread handling Putty's IPC requests. */
2146 putty_message_thread (void *arg)
2148 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2149 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2156 log_info ("putty message loop thread started\n");
2158 /* The message loop runs as thread independent from our nPth system.
2159 This also means that we need to make sure that we switch back to
2160 our system before calling any no-windows function. */
2163 /* First create a window to make sure that a message queue exists
2165 if (!RegisterClass (&wndwclass))
2168 log_error ("error registering Pageant window class");
2171 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2173 HWND_MESSAGE, /* hWndParent */
2174 NULL, /* hWndMenu */
2175 NULL, /* hInstance */
2180 log_error ("error creating Pageant window");
2184 while (GetMessage(&msg, NULL, 0, 0))
2186 TranslateMessage(&msg);
2187 DispatchMessage(&msg);
2194 log_info ("putty message loop thread stopped\n");
2197 #endif /*HAVE_W32_SYSTEM*/
2201 do_start_connection_thread (ctrl_t ctrl)
2203 agent_init_default_ctrl (ctrl);
2205 log_info (_("handler 0x%lx for fd %d started\n"),
2206 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2208 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2210 log_info (_("handler 0x%lx for fd %d terminated\n"),
2211 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2213 agent_deinit_default_ctrl (ctrl);
2219 /* This is the standard connection thread's main function. */
2221 start_connection_thread_std (void *arg)
2225 if (check_nonce (ctrl, &socket_nonce))
2227 log_error ("handler 0x%lx nonce check FAILED\n",
2228 (unsigned long) npth_self());
2232 return do_start_connection_thread (ctrl);
2236 /* This is the extra socket connection thread's main function. */
2238 start_connection_thread_extra (void *arg)
2242 if (check_nonce (ctrl, &socket_nonce_extra))
2244 log_error ("handler 0x%lx nonce check FAILED\n",
2245 (unsigned long) npth_self());
2249 ctrl->restricted = 1;
2250 return do_start_connection_thread (ctrl);
2254 /* This is the browser socket connection thread's main function. */
2256 start_connection_thread_browser (void *arg)
2260 if (check_nonce (ctrl, &socket_nonce_browser))
2262 log_error ("handler 0x%lx nonce check FAILED\n",
2263 (unsigned long) npth_self());
2267 ctrl->restricted = 2;
2268 return do_start_connection_thread (ctrl);
2272 /* This is the ssh connection thread's main function. */
2274 start_connection_thread_ssh (void *arg)
2278 if (check_nonce (ctrl, &socket_nonce_ssh))
2281 agent_init_default_ctrl (ctrl);
2283 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2284 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2286 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2288 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2289 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2291 agent_deinit_default_ctrl (ctrl);
2297 /* Connection handler loop. Wait for connection requests and spawn a
2298 thread after accepting a connection. */
2300 handle_connections (gnupg_fd_t listen_fd,
2301 gnupg_fd_t listen_fd_extra,
2302 gnupg_fd_t listen_fd_browser,
2303 gnupg_fd_t listen_fd_ssh)
2306 struct sockaddr_un paddr;
2308 fd_set fdset, read_fdset;
2313 struct timespec abstime;
2314 struct timespec curtime;
2315 struct timespec timeout;
2316 #ifdef HAVE_W32_SYSTEM
2318 unsigned int events_set;
2322 void *(*func) (void *arg);
2325 { "std", start_connection_thread_std },
2326 { "extra", start_connection_thread_extra },
2327 { "browser", start_connection_thread_browser },
2328 { "ssh", start_connection_thread_ssh }
2332 ret = npth_attr_init(&tattr);
2334 log_fatal ("error allocating thread attributes: %s\n",
2336 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2338 #ifndef HAVE_W32_SYSTEM
2340 npth_sigev_add (SIGHUP);
2341 npth_sigev_add (SIGUSR1);
2342 npth_sigev_add (SIGUSR2);
2343 npth_sigev_add (SIGINT);
2344 npth_sigev_add (SIGTERM);
2347 # ifdef HAVE_W32CE_SYSTEM
2348 /* Use a dummy event. */
2350 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2352 events[0] = get_agent_scd_notify_event ();
2353 events[1] = INVALID_HANDLE_VALUE;
2357 /* On Windows we need to fire up a separate thread to listen for
2358 requests from Putty (an SSH client), so we can replace Putty's
2359 Pageant (its ssh-agent implementation). */
2360 #ifdef HAVE_W32_SYSTEM
2365 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2368 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2371 #endif /*HAVE_W32_SYSTEM*/
2373 /* Set a flag to tell call-scd.c that it may enable event
2375 opt.sigusr2_enabled = 1;
2378 FD_SET (FD2INT (listen_fd), &fdset);
2379 nfd = FD2INT (listen_fd);
2380 if (listen_fd_extra != GNUPG_INVALID_FD)
2382 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2383 if (FD2INT (listen_fd_extra) > nfd)
2384 nfd = FD2INT (listen_fd_extra);
2386 if (listen_fd_browser != GNUPG_INVALID_FD)
2388 FD_SET ( FD2INT(listen_fd_browser), &fdset);
2389 if (FD2INT (listen_fd_browser) > nfd)
2390 nfd = FD2INT (listen_fd_browser);
2392 if (listen_fd_ssh != GNUPG_INVALID_FD)
2394 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2395 if (FD2INT (listen_fd_ssh) > nfd)
2396 nfd = FD2INT (listen_fd_ssh);
2399 listentbl[0].l_fd = listen_fd;
2400 listentbl[1].l_fd = listen_fd_extra;
2401 listentbl[2].l_fd = listen_fd_browser;
2402 listentbl[3].l_fd = listen_fd_ssh;
2404 npth_clock_gettime (&abstime);
2405 abstime.tv_sec += TIMERTICK_INTERVAL;
2409 /* Shutdown test. */
2410 if (shutdown_pending)
2412 if (active_connections == 0)
2415 /* Do not accept new connections but keep on running the
2416 loop to cope with the timer events. */
2420 /* POSIX says that fd_set should be implemented as a structure,
2421 thus a simple assignment is fine to copy the entire set. */
2424 npth_clock_gettime (&curtime);
2425 if (!(npth_timercmp (&curtime, &abstime, <)))
2429 npth_clock_gettime (&abstime);
2430 abstime.tv_sec += TIMERTICK_INTERVAL;
2432 npth_timersub (&abstime, &curtime, &timeout);
2434 #ifndef HAVE_W32_SYSTEM
2435 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2436 npth_sigev_sigmask ());
2437 saved_errno = errno;
2441 while (npth_sigev_get_pending (&signo))
2442 handle_signal (signo);
2445 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2446 events, &events_set);
2447 saved_errno = errno;
2449 /* This is valid even if npth_eselect returns an error. */
2451 agent_sigusr2_action ();
2454 if (ret == -1 && saved_errno != EINTR)
2456 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2457 strerror (saved_errno));
2462 /* Interrupt or timeout. Will be handled when calculating the
2466 if (!shutdown_pending)
2472 for (idx=0; idx < DIM(listentbl); idx++)
2474 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2476 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2479 plen = sizeof paddr;
2480 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2481 (struct sockaddr *)&paddr, &plen));
2482 if (fd == GNUPG_INVALID_FD)
2484 log_error ("accept failed for %s: %s\n",
2485 listentbl[idx].name, strerror (errno));
2487 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2489 log_error ("error allocating connection data for %s: %s\n",
2490 listentbl[idx].name, strerror (errno) );
2491 assuan_sock_close (fd);
2493 else if ( !(ctrl->session_env = session_env_new ()))
2495 log_error ("error allocating session env block for %s: %s\n",
2496 listentbl[idx].name, strerror (errno) );
2498 assuan_sock_close (fd);
2502 ctrl->thread_startup.fd = fd;
2503 ret = npth_create (&thread, &tattr,
2504 listentbl[idx].func, ctrl);
2507 log_error ("error spawning connection handler for %s:"
2508 " %s\n", listentbl[idx].name, strerror (ret));
2509 assuan_sock_close (fd);
2513 fd = GNUPG_INVALID_FD;
2519 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2520 npth_attr_destroy (&tattr);
2525 /* Helper for check_own_socket. */
2527 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2529 membuf_t *mb = opaque;
2530 put_membuf (mb, buffer, length);
2535 /* The thread running the actual check. We need to run this in a
2536 separate thread so that check_own_thread can be called from the
2539 check_own_socket_thread (void *arg)
2542 char *sockname = arg;
2543 assuan_context_t ctx = NULL;
2547 check_own_socket_running++;
2549 rc = assuan_new (&ctx);
2552 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2556 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2559 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2563 init_membuf (&mb, 100);
2564 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2565 NULL, NULL, NULL, NULL);
2566 put_membuf (&mb, "", 1);
2567 buffer = get_membuf (&mb, NULL);
2570 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2571 "GETINFO pid", gpg_strerror (rc));
2574 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2576 log_error ("socket is now serviced by another server\n");
2579 else if (opt.verbose > 1)
2580 log_error ("socket is still served by this server\n");
2587 assuan_release (ctx);
2590 /* We may not remove the socket as it is now in use by another
2591 server. Setting the name to empty does this. */
2594 if (socket_name_ssh)
2595 *socket_name_ssh = 0;
2596 shutdown_pending = 2;
2597 log_info ("this process is useless - shutting down\n");
2599 check_own_socket_running--;
2604 /* Check whether we are still listening on our own socket. In case
2605 another gpg-agent process started after us has taken ownership of
2606 our socket, we would linger around without any real task. Thus we
2607 better check once in a while whether we are really needed. */
2609 check_own_socket (void)
2616 if (disable_check_own_socket)
2619 if (check_own_socket_running || shutdown_pending)
2620 return; /* Still running or already shutting down. */
2622 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2624 return; /* Out of memory. */
2626 err = npth_attr_init (&tattr);
2629 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2630 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2632 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2633 npth_attr_destroy (&tattr);
2638 /* Figure out whether an agent is available and running. Prints an
2639 error if not. If SILENT is true, no messages are printed.
2640 Returns 0 if the agent is running. */
2642 check_for_running_agent (int silent)
2646 assuan_context_t ctx = NULL;
2648 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2650 err = assuan_new (&ctx);
2652 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2657 log_error (_("no gpg-agent running in this session\n"));
2660 assuan_release (ctx);
2664 if (!opt.quiet && !silent)
2665 log_info ("gpg-agent running and available\n");
2667 assuan_release (ctx);