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,
108 oEnforcePassphraseConstraints,
110 oMinPassphraseNonalpha,
111 oCheckPassphrasePattern,
113 oEnablePassphraseHistory,
115 oNoUseStandardSocket,
120 oIgnoreCacheForSigning,
123 oAllowPresetPassphrase,
124 oAllowLoopbackPinentry,
125 oNoAllowExternalCache,
132 oDisableCheckOwnSocket,
138 # define ENAMETOOLONG EINVAL
142 static ARGPARSE_OPTS opts[] = {
144 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
145 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
146 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
148 ARGPARSE_group (301, N_("@Options:\n ")),
150 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
151 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
152 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
153 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
154 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
155 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
156 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
158 ARGPARSE_s_s (oDebug, "debug", "@"),
159 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
160 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
161 ARGPARSE_s_i (oDebugWait," debug-wait", "@"),
162 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
163 ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
165 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
166 ARGPARSE_s_n (oNoGrab, "no-grab", N_("do not grab keyboard and mouse")),
167 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
168 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
169 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
170 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
171 ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
172 ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
173 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
174 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
175 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
176 /* */ N_("do not use the SCdaemon") ),
177 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
179 ARGPARSE_s_s (oExtraSocket, "extra-socket",
180 /* */ N_("|NAME|accept some commands via NAME")),
182 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
184 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
186 ARGPARSE_s_n (oBatch, "batch", "@"),
187 ARGPARSE_s_s (oHomedir, "homedir", "@"),
189 ARGPARSE_s_s (oDisplay, "display", "@"),
190 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
191 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
192 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
193 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
194 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
195 ARGPARSE_s_n (oKeepTTY, "keep-tty",
196 /* */ N_("ignore requests to change the TTY")),
197 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
198 /* */ N_("ignore requests to change the X display")),
200 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
201 N_("|N|expire cached PINs after N seconds")),
202 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
203 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
204 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
206 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
208 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
209 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
210 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
211 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
212 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
214 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
215 /* */ N_("do not use the PIN cache when signing")),
216 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
217 /* */ N_("disallow the use of an external password cache")),
218 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
219 /* */ N_("disallow clients to mark keys as \"trusted\"")),
220 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
221 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
222 /* */ N_("allow presetting passphrase")),
223 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry",
224 N_("allow caller to override the pinentry")),
225 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
226 /* */ N_("allow passphrase to be prompted through Emacs")),
228 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
229 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
230 #ifdef HAVE_W32_SYSTEM
231 /* */ N_("enable putty support")
237 /* Dummy options for backward compatibility. */
238 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
239 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
240 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
242 {0} /* End of list */
246 /* The list of supported debug flags. */
247 static struct debug_flags_s debug_flags [] =
249 { DBG_COMMAND_VALUE, "command" },
250 { DBG_MPI_VALUE , "mpi" },
251 { DBG_CRYPTO_VALUE , "crypto" },
252 { DBG_MEMORY_VALUE , "memory" },
253 { DBG_CACHE_VALUE , "cache" },
254 { DBG_MEMSTAT_VALUE, "memstat" },
255 { DBG_HASHING_VALUE, "hashing" },
256 { DBG_IPC_VALUE , "ipc" },
257 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
262 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
263 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
264 #define MAX_CACHE_TTL (120*60) /* 2 hours */
265 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
266 #define MIN_PASSPHRASE_LEN (8)
267 #define MIN_PASSPHRASE_NONALPHA (1)
268 #define MAX_PASSPHRASE_DAYS (0)
270 /* The timer tick used for housekeeping stuff. For Windows we use a
271 longer period as the SetWaitableTimer seems to signal earlier than
272 the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
273 check our own socket in standard socket mode. If that value is 0
274 we don't check at all. All values are in seconds. */
275 #if defined(HAVE_W32CE_SYSTEM)
276 # define TIMERTICK_INTERVAL (60)
277 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
278 #elif defined(HAVE_W32_SYSTEM)
279 # define TIMERTICK_INTERVAL (4)
280 # define CHECK_OWN_SOCKET_INTERVAL (60)
282 # define TIMERTICK_INTERVAL (2)
283 # define CHECK_OWN_SOCKET_INTERVAL (60)
287 /* Flag indicating that the ssh-agent subsystem has been enabled. */
288 static int ssh_support;
290 #ifdef HAVE_W32_SYSTEM
291 /* Flag indicating that support for Putty has been enabled. */
292 static int putty_support;
293 /* A magic value used with WM_COPYDATA. */
294 #define PUTTY_IPC_MAGIC 0x804e50ba
295 /* To avoid surprises we limit the size of the mapped IPC file to this
296 value. Putty currently (0.62) uses 8k, thus 16k should be enough
297 for the foreseeable future. */
298 #define PUTTY_IPC_MAXLEN 16384
299 #endif /*HAVE_W32_SYSTEM*/
301 /* The list of open file descriptors at startup. Note that this list
302 has been allocated using the standard malloc. */
303 static int *startup_fd_list;
305 /* The signal mask at startup and a flag telling whether it is valid. */
306 #ifdef HAVE_SIGPROCMASK
307 static sigset_t startup_signal_mask;
308 static int startup_signal_mask_valid;
311 /* Flag to indicate that a shutdown was requested. */
312 static int shutdown_pending;
314 /* Counter for the currently running own socket checks. */
315 static int check_own_socket_running;
317 /* Flags to indicate that check_own_socket shall not be called. */
318 static int disable_check_own_socket;
320 /* It is possible that we are currently running under setuid permissions */
321 static int maybe_setuid = 1;
323 /* Name of the communication socket used for native gpg-agent
324 requests. The second variable is either NULL or a malloced string
325 with the real socket name in case it has been redirected. */
326 static char *socket_name;
327 static char *redir_socket_name;
329 /* Name of the optional extra socket used for native gpg-agent requests. */
330 static char *socket_name_extra;
331 static char *redir_socket_name_extra;
333 /* Name of the optional browser socket used for native gpg-agent requests. */
334 static char *socket_name_browser;
335 static char *redir_socket_name_browser;
337 /* Name of the communication socket used for ssh-agent-emulation. */
338 static char *socket_name_ssh;
339 static char *redir_socket_name_ssh;
341 /* We need to keep track of the server's nonces (these are dummies for
343 static assuan_sock_nonce_t socket_nonce;
344 static assuan_sock_nonce_t socket_nonce_extra;
345 static assuan_sock_nonce_t socket_nonce_browser;
346 static assuan_sock_nonce_t socket_nonce_ssh;
349 /* Default values for options passed to the pinentry. */
350 static char *default_display;
351 static char *default_ttyname;
352 static char *default_ttytype;
353 static char *default_lc_ctype;
354 static char *default_lc_messages;
355 static char *default_xauthority;
357 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
358 static char *config_filename;
360 /* Helper to implement --debug-level */
361 static const char *debug_level;
363 /* Keep track of the current log file so that we can avoid updating
364 the log file after a SIGHUP if it didn't changed. Malloced. */
365 static char *current_logfile;
367 /* The handle_tick() function may test whether a parent is still
368 running. We record the PID of the parent here or -1 if it should be
370 static pid_t parent_pid = (pid_t)(-1);
372 /* Number of active connections. */
373 static int active_connections;
375 /* This object is used to dispatch progress messages from Libgcrypt to
376 * the right thread. Given that we won't have at max a few dozen
377 * connections at the same time using a linked list is the easiest way
379 struct progress_dispatch_s
381 struct progress_dispatch_s *next;
382 /* The control object of the connection. If this is NULL no
383 * connection is associated with this item and it is free for reuse
384 * by new connections. */
387 /* The thread id of (npth_self) of the connection. */
390 /* The callback set by the connection. This is similar to the
391 * Libgcrypt callback but with the control object passed as the
393 void (*cb)(ctrl_t ctrl,
394 const char *what, int printchar,
395 int current, int total);
397 struct progress_dispatch_s *progress_dispatch_list;
406 static char *create_socket_name (char *standard_name, int with_homedir);
407 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
409 assuan_sock_nonce_t *nonce);
410 static void create_directories (void);
412 static void agent_libgcrypt_progress_cb (void *data, const char *what,
414 int current, int total);
415 static void agent_init_default_ctrl (ctrl_t ctrl);
416 static void agent_deinit_default_ctrl (ctrl_t ctrl);
418 static void handle_connections (gnupg_fd_t listen_fd,
419 gnupg_fd_t listen_fd_extra,
420 gnupg_fd_t listen_fd_browser,
421 gnupg_fd_t listen_fd_ssh);
422 static void check_own_socket (void);
423 static int check_for_running_agent (int silent);
425 /* Pth wrapper function definitions. */
426 ASSUAN_SYSTEM_NPTH_IMPL;
433 /* Allocate a string describing a library version by calling a GETFNC.
434 This function is expected to be called only once. GETFNC is
435 expected to have a semantic like gcry_check_version (). */
437 make_libversion (const char *libname, const char *(*getfnc)(const char*))
444 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
448 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
449 strcpy (stpcpy (stpcpy (result, libname), " "), s);
453 /* Return strings describing this program. The case values are
454 described in common/argparse.c:strusage. The values here override
455 the default values given by strusage. */
457 my_strusage (int level)
459 static char *ver_gcry;
464 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
466 case 13: p = VERSION; break;
467 case 17: p = PRINTABLE_OS_NAME; break;
468 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
469 reporting address. This is so that we can change the
470 reporting address without breaking the translations. */
471 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
475 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
480 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
482 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
483 "Secret key management for @GNUPG@\n");
493 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
494 only the active debug flags are propagated to the subsystems. With
495 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
496 all flags already set. Note that we don't fail here, because it is
497 important to keep gpg-agent running even after re-reading the
498 options due to a SIGHUP. */
502 int numok = (debug_level && digitp (debug_level));
503 int numlvl = numok? atoi (debug_level) : 0;
507 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
509 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
510 opt.debug = DBG_IPC_VALUE;
511 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
512 opt.debug = DBG_IPC_VALUE|DBG_COMMAND_VALUE;
513 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
514 opt.debug = (DBG_IPC_VALUE|DBG_COMMAND_VALUE
516 else if (!strcmp (debug_level, "guru") || numok)
519 /* Unless the "guru" string has been used we don't want to allow
520 hashing debugging. The rationale is that people tend to
521 select the highest debug value and would then clutter their
522 disk with debug files which may reveal confidential data. */
524 opt.debug &= ~(DBG_HASHING_VALUE);
528 log_error (_("invalid debug-level '%s' given\n"), debug_level);
529 opt.debug = 0; /* Reset debugging, so that prior debug
530 statements won't have an undesired effect. */
533 if (opt.debug && !opt.verbose)
535 if (opt.debug && opt.quiet)
538 if (opt.debug & DBG_MPI_VALUE)
539 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
540 if (opt.debug & DBG_CRYPTO_VALUE )
541 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
542 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
545 parse_debug_flag (NULL, &opt.debug, debug_flags);
549 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
550 the corresponding real name if the socket has been redirected. */
552 remove_socket (char *name, char *redir_name)
562 p = strrchr (name, '/');
574 /* Cleanup code for this program. This is either called has an atexit
575 handler or directly. */
584 deinitialize_module_cache ();
585 remove_socket (socket_name, redir_socket_name);
586 if (opt.extra_socket > 1)
587 remove_socket (socket_name_extra, redir_socket_name_extra);
588 if (opt.browser_socket > 1)
589 remove_socket (socket_name_browser, redir_socket_name_browser);
590 remove_socket (socket_name_ssh, redir_socket_name_ssh);
595 /* Handle options which are allowed to be reset after program start.
596 Return true when the current option in PARGS could be handled and
597 false if not. As a special feature, passing a value of NULL for
598 PARGS, resets the options to the default. REREAD should be set
599 true if it is not the initial option parsing. */
601 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
609 opt.debug_pinentry = 0;
610 opt.pinentry_program = NULL;
611 opt.pinentry_touch_file = NULL;
612 xfree (opt.pinentry_invisible_char);
613 opt.pinentry_invisible_char = NULL;
614 opt.pinentry_timeout = 0;
615 opt.scdaemon_program = NULL;
616 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
617 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
618 opt.max_cache_ttl = MAX_CACHE_TTL;
619 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
620 opt.enforce_passphrase_constraints = 0;
621 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
622 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
623 opt.check_passphrase_pattern = NULL;
624 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
625 opt.enable_passhrase_history = 0;
626 opt.ignore_cache_for_signing = 0;
627 opt.allow_mark_trusted = 1;
628 opt.allow_external_cache = 1;
629 opt.allow_emacs_pinentry = 0;
630 opt.disable_scdaemon = 0;
631 disable_check_own_socket = 0;
635 switch (pargs->r_opt)
637 case oQuiet: opt.quiet = 1; break;
638 case oVerbose: opt.verbose++; break;
641 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
643 case oDebugAll: opt.debug = ~0; break;
644 case oDebugLevel: debug_level = pargs->r.ret_str; break;
645 case oDebugPinentry: opt.debug_pinentry = 1; break;
649 return 0; /* not handeld */
650 if (!current_logfile || !pargs->r.ret_str
651 || strcmp (current_logfile, pargs->r.ret_str))
653 log_set_file (pargs->r.ret_str);
654 xfree (current_logfile);
655 current_logfile = xtrystrdup (pargs->r.ret_str);
659 case oNoGrab: opt.no_grab = 1; break;
661 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
662 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
663 case oPinentryInvisibleChar:
664 xfree (opt.pinentry_invisible_char);
665 opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
667 case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
668 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
669 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
670 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
672 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
673 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
674 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
675 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
677 case oEnforcePassphraseConstraints:
678 opt.enforce_passphrase_constraints=1;
680 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
681 case oMinPassphraseNonalpha:
682 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
684 case oCheckPassphrasePattern:
685 opt.check_passphrase_pattern = pargs->r.ret_str;
687 case oMaxPassphraseDays:
688 opt.max_passphrase_days = pargs->r.ret_ulong;
690 case oEnablePassphraseHistory:
691 opt.enable_passhrase_history = 1;
694 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
696 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
697 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
699 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
701 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
703 case oNoAllowExternalCache: opt.allow_external_cache = 0;
706 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
710 return 0; /* not handled */
713 return 1; /* handled */
717 /* Fixup some options after all have been processed. */
719 finalize_rereadable_options (void)
725 /* The main entry point. */
727 main (int argc, char **argv )
732 FILE *configfp = NULL;
733 char *configname = NULL;
735 unsigned configlineno;
737 int default_config =1;
742 char *logfile = NULL;
744 int gpgconf_list = 0;
746 struct assuan_malloc_hooks malloc_hooks;
748 early_system_init ();
750 /* Before we do anything else we save the list of currently open
751 file descriptors and the signal mask. This info is required to
752 do the exec call properly. */
753 startup_fd_list = get_all_open_fds ();
754 #ifdef HAVE_SIGPROCMASK
755 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
756 startup_signal_mask_valid = 1;
757 #endif /*HAVE_SIGPROCMASK*/
759 /* Set program name etc. */
760 set_strusage (my_strusage);
761 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
762 /* Please note that we may running SUID(ROOT), so be very CAREFUL
763 when adding any stuff between here and the call to INIT_SECMEM()
764 somewhere after the option parsing */
765 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
767 /* Make sure that our subsystems are ready. */
769 init_common_subsystems (&argc, &argv);
773 /* Check that the libraries are suitable. Do it here because
774 the option parsing may need services of the library. */
775 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
777 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
778 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
781 malloc_hooks.malloc = gcry_malloc;
782 malloc_hooks.realloc = gcry_realloc;
783 malloc_hooks.free = gcry_free;
784 assuan_set_malloc_hooks (&malloc_hooks);
785 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
786 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
788 setup_libassuan_logging (&opt.debug);
790 setup_libgcrypt_logging ();
791 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
792 gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
794 disable_core_dumps ();
796 /* Set default options. */
797 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
799 shell = getenv ("SHELL");
800 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
803 opt.homedir = default_homedir ();
805 /* Record some of the original environment strings. */
809 static const char *names[] =
810 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
813 opt.startup_env = session_env_new ();
814 if (!opt.startup_env)
815 err = gpg_error_from_syserror ();
816 for (idx=0; !err && names[idx]; idx++)
818 s = getenv (names[idx]);
820 err = session_env_setenv (opt.startup_env, names[idx], s);
824 s = gnupg_ttyname (0);
826 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
829 log_fatal ("error recording startup environment: %s\n",
832 /* Fixme: Better use the locale function here. */
833 opt.startup_lc_ctype = getenv ("LC_CTYPE");
834 if (opt.startup_lc_ctype)
835 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
836 opt.startup_lc_messages = getenv ("LC_MESSAGES");
837 if (opt.startup_lc_messages)
838 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
841 /* Check whether we have a config file on the commandline */
846 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
847 while (arg_parse( &pargs, opts))
849 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
851 else if (pargs.r_opt == oOptions)
852 { /* yes there is one, so we do not try the default one, but
853 read the option file when it is encountered at the
857 else if (pargs.r_opt == oNoOptions)
858 default_config = 0; /* --no-options */
859 else if (pargs.r_opt == oHomedir)
860 opt.homedir = pargs.r.ret_str;
861 else if (pargs.r_opt == oDebugQuickRandom)
863 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
868 /* Initialize the secure memory. */
869 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
873 Now we are now working under our real uid
877 configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
884 pargs.flags= 1; /* do not remove the args */
889 configfp = fopen (configname, "r");
895 log_info (_("Note: no default option file '%s'\n"),
897 /* Save the default conf file name so that
898 reread_configuration is able to test whether the
899 config file has been created in the meantime. */
900 xfree (config_filename);
901 config_filename = configname;
906 log_error (_("option file '%s': %s\n"),
907 configname, strerror(errno) );
913 if (parse_debug && configname )
914 log_info (_("reading options from '%s'\n"), configname );
918 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
920 if (parse_rereadable_options (&pargs, 0))
921 continue; /* Already handled */
924 case aGPGConfList: gpgconf_list = 1; break;
925 case aGPGConfTest: gpgconf_list = 2; break;
926 case aUseStandardSocketP: gpgconf_list = 3; break;
927 case oBatch: opt.batch=1; break;
929 case oDebugWait: debug_wait = pargs.r.ret_int; break;
932 /* config files may not be nested (silently ignore them) */
936 configname = xstrdup(pargs.r.ret_str);
940 case oNoGreeting: /* Dummy option. */ break;
941 case oNoVerbose: opt.verbose = 0; break;
942 case oNoOptions: break; /* no-options */
943 case oHomedir: opt.homedir = pargs.r.ret_str; break;
944 case oNoDetach: nodetach = 1; break;
945 case oLogFile: logfile = pargs.r.ret_str; break;
946 case oCsh: csh_style = 1; break;
947 case oSh: csh_style = 0; break;
948 case oServer: pipe_server = 1; break;
949 case oDaemon: is_daemon = 1; break;
951 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
952 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
953 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
954 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
955 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
957 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
960 case oUseStandardSocket:
961 case oNoUseStandardSocket:
962 obsolete_option (configname, configlineno, "use-standard-socket");
965 case oFakedSystemTime:
967 time_t faked_time = isotime2epoch (pargs.r.ret_str);
968 if (faked_time == (time_t)(-1))
969 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
970 gnupg_set_time (faked_time, 0);
974 case oKeepTTY: opt.keep_tty = 1; break;
975 case oKeepDISPLAY: opt.keep_display = 1; break;
981 # ifdef HAVE_W32_SYSTEM
987 opt.extra_socket = 1; /* (1 = points into argv) */
988 socket_name_extra = pargs.r.ret_str;
992 opt.browser_socket = 1; /* (1 = points into argv) */
993 socket_name_browser = pargs.r.ret_str;
996 case oDebugQuickRandom:
997 /* Only used by the first stage command line parser. */
1001 obsolete_option (configname, configlineno, "write-env-file");
1004 default : pargs.err = configfp? 1:2; break;
1011 /* Keep a copy of the name so that it can be read on SIGHUP. */
1012 if (config_filename != configname)
1014 xfree (config_filename);
1015 config_filename = configname;
1023 if (log_get_errorcount(0))
1026 finalize_rereadable_options ();
1028 /* Turn the homedir into an absolute one. */
1029 opt.homedir = make_absfilename (opt.homedir, NULL);
1031 /* Print a warning if an argument looks like an option. */
1032 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1036 for (i=0; i < argc; i++)
1037 if (argv[i][0] == '-' && argv[i][1] == '-')
1038 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1042 /* gpg-agent usually does not output any messages because it runs in
1043 the background. For log files it is acceptable to have messages
1044 always encoded in utf-8. We switch here to utf-8, so that
1045 commands like --help still give native messages. It is far
1046 easier to switch only once instead of for every message and it
1047 actually helps when more then one thread is active (avoids an
1048 extra copy step). */
1049 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1052 if (!pipe_server && !is_daemon && !gpgconf_list)
1054 /* We have been called without any options and thus we merely
1055 check whether an agent is already running. We do this right
1056 here so that we don't clobber a logfile with this check but
1057 print the status directly to stderr. */
1060 check_for_running_agent (0);
1066 if (atexit (cleanup))
1068 log_error ("atexit failed\n");
1073 initialize_module_cache ();
1074 initialize_module_call_pinentry ();
1075 initialize_module_call_scd ();
1076 initialize_module_trustlist ();
1078 /* Try to create missing directories. */
1079 create_directories ();
1081 if (debug_wait && pipe_server)
1083 log_debug ("waiting for debugger - my pid is %u .....\n",
1084 (unsigned int)getpid());
1085 gnupg_sleep (debug_wait);
1086 log_debug ("... okay\n");
1089 if (gpgconf_list == 3)
1091 /* We now use the standard socket always - return true for
1092 backward compatibility. */
1095 else if (gpgconf_list == 2)
1097 else if (gpgconf_list)
1102 /* List options and default values in the GPG Conf format. */
1103 filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
1105 filename_esc = percent_escape (filename, NULL);
1107 es_printf ("%s-%s.conf:%lu:\"%s\n",
1108 GPGCONF_NAME, GPG_AGENT_NAME,
1109 GC_OPT_FLAG_DEFAULT, filename_esc);
1111 xfree (filename_esc);
1113 es_printf ("verbose:%lu:\n"
1115 "debug-level:%lu:\"none:\n"
1117 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1118 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1119 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1120 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1121 es_printf ("default-cache-ttl:%lu:%d:\n",
1122 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1123 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1124 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1125 es_printf ("max-cache-ttl:%lu:%d:\n",
1126 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1127 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1128 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1129 es_printf ("enforce-passphrase-constraints:%lu:\n",
1130 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1131 es_printf ("min-passphrase-len:%lu:%d:\n",
1132 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1133 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1134 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1135 MIN_PASSPHRASE_NONALPHA);
1136 es_printf ("check-passphrase-pattern:%lu:\n",
1137 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1138 es_printf ("max-passphrase-days:%lu:%d:\n",
1139 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1140 MAX_PASSPHRASE_DAYS);
1141 es_printf ("enable-passphrase-history:%lu:\n",
1142 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1143 es_printf ("no-grab:%lu:\n",
1144 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1145 es_printf ("ignore-cache-for-signing:%lu:\n",
1146 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1147 es_printf ("no-allow-external-cache:%lu:\n",
1148 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1149 es_printf ("no-allow-mark-trusted:%lu:\n",
1150 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1151 es_printf ("disable-scdaemon:%lu:\n",
1152 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1153 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1154 #ifdef HAVE_W32_SYSTEM
1155 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1157 es_printf ("allow-loopback-pinentry:%lu:\n",
1158 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1159 es_printf ("allow-emacs-pinentry:%lu:\n",
1160 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1161 es_printf ("pinentry-timeout:%lu:0:\n",
1162 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1167 /* Now start with logging to a file if this is desired. */
1170 log_set_file (logfile);
1171 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1172 | GPGRT_LOG_WITH_TIME
1173 | GPGRT_LOG_WITH_PID));
1174 current_logfile = xstrdup (logfile);
1177 /* Make sure that we have a default ttyname. */
1178 if (!default_ttyname && gnupg_ttyname (1))
1179 default_ttyname = xstrdup (gnupg_ttyname (1));
1180 if (!default_ttytype && getenv ("TERM"))
1181 default_ttytype = xstrdup (getenv ("TERM"));
1186 /* This is the simple pipe based server */
1189 ctrl = xtrycalloc (1, sizeof *ctrl);
1192 log_error ("error allocating connection control data: %s\n",
1196 ctrl->session_env = session_env_new ();
1197 if (!ctrl->session_env)
1199 log_error ("error allocating session environment block: %s\n",
1204 agent_init_default_ctrl (ctrl);
1205 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1206 agent_deinit_default_ctrl (ctrl);
1209 else if (!is_daemon)
1212 { /* Regular server mode */
1214 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1215 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1216 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1217 #ifndef HAVE_W32_SYSTEM
1221 /* Remove the DISPLAY variable so that a pinentry does not
1222 default to a specific display. There is still a default
1223 display when gpg-agent was started using --display or a
1224 client requested this using an OPTION command. Note, that we
1225 don't do this when running in reverse daemon mode (i.e. when
1226 exec the program given as arguments). */
1227 #ifndef HAVE_W32_SYSTEM
1228 if (!opt.keep_display && !argc)
1229 gnupg_unsetenv ("DISPLAY");
1232 /* Remove the INSIDE_EMACS variable so that a pinentry does not
1233 always try to interact with Emacs. The variable is set when
1234 a client requested this using an OPTION command. */
1235 gnupg_unsetenv ("INSIDE_EMACS");
1237 /* Create the sockets. */
1238 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1239 fd = create_server_socket (socket_name, 1, 0,
1240 &redir_socket_name, &socket_nonce);
1242 if (opt.extra_socket)
1244 socket_name_extra = create_socket_name (socket_name_extra, 0);
1245 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1246 fd_extra = create_server_socket (socket_name_extra, 0, 0,
1247 &redir_socket_name_extra,
1248 &socket_nonce_extra);
1251 if (opt.browser_socket)
1253 socket_name_browser = create_socket_name (socket_name_browser, 0);
1254 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1255 fd_browser = create_server_socket (socket_name_browser, 0, 0,
1256 &redir_socket_name_browser,
1257 &socket_nonce_browser);
1262 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1263 fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1264 &redir_socket_name_ssh,
1268 /* If we are going to exec a program in the parent, we record
1269 the PID, so that the child may check whether the program is
1272 parent_pid = getpid ();
1275 #ifdef HAVE_W32_SYSTEM
1278 #else /*!HAVE_W32_SYSTEM*/
1280 if (pid == (pid_t)-1)
1282 log_fatal ("fork failed: %s\n", strerror (errno) );
1286 { /* We are the parent */
1287 char *infostr_ssh_sock, *infostr_ssh_valid;
1289 /* Close the socket FD. */
1292 /* The signal mask might not be correct right now and thus
1293 we restore it. That is not strictly necessary but some
1294 programs falsely assume a cleared signal mask. */
1296 #ifdef HAVE_SIGPROCMASK
1297 if (startup_signal_mask_valid)
1299 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1300 log_error ("error restoring signal mask: %s\n",
1304 log_info ("no saved signal mask\n");
1305 #endif /*HAVE_SIGPROCMASK*/
1307 /* Create the SSH info string if enabled. */
1310 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1311 socket_name_ssh) < 0)
1313 log_error ("out of core\n");
1314 kill (pid, SIGTERM);
1317 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1318 (unsigned long)getpid()) < 0)
1320 log_error ("out of core\n");
1321 kill (pid, SIGTERM);
1326 *socket_name = 0; /* Don't let cleanup() remove the socket -
1327 the child should do this from now on */
1328 if (opt.extra_socket)
1329 *socket_name_extra = 0;
1330 if (opt.browser_socket)
1331 *socket_name_browser = 0;
1333 *socket_name_ssh = 0;
1336 { /* Run the program given on the commandline. */
1337 if (ssh_support && (putenv (infostr_ssh_sock)
1338 || putenv (infostr_ssh_valid)))
1340 log_error ("failed to set environment: %s\n",
1342 kill (pid, SIGTERM );
1346 /* Close all the file descriptors except the standard
1347 ones and those open at startup. We explicitly don't
1348 close 0,1,2 in case something went wrong collecting
1350 close_all_fds (3, startup_fd_list);
1352 /* Run the command. */
1353 execvp (argv[0], argv);
1354 log_error ("failed to run the command: %s\n", strerror (errno));
1355 kill (pid, SIGTERM);
1360 /* Print the environment string, so that the caller can use
1361 shell's eval to set it */
1366 *strchr (infostr_ssh_sock, '=') = ' ';
1367 es_printf ("setenv %s;\n", infostr_ssh_sock);
1374 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1380 xfree (infostr_ssh_sock);
1381 xfree (infostr_ssh_valid);
1392 /* Detach from tty and put process into a new session */
1396 unsigned int oldflags;
1398 /* Close stdin, stdout and stderr unless it is the log stream */
1399 for (i=0; i <= 2; i++)
1401 if (!log_test_fd (i) && i != fd )
1404 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1406 log_error ("failed to open '%s': %s\n",
1407 "/dev/null", strerror (errno));
1415 log_error ("setsid() failed: %s\n", strerror(errno) );
1420 log_get_prefix (&oldflags);
1421 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1422 opt.running_detached = 1;
1427 log_error ("chdir to / failed: %s\n", strerror (errno));
1432 struct sigaction sa;
1434 sa.sa_handler = SIG_IGN;
1435 sigemptyset (&sa.sa_mask);
1437 sigaction (SIGPIPE, &sa, NULL);
1439 #endif /*!HAVE_W32_SYSTEM*/
1441 log_info ("%s %s started\n", strusage(11), strusage(13) );
1442 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1443 assuan_sock_close (fd);
1450 /* Exit entry point. This function should be called instead of a
1455 /*FIXME: update_random_seed_file();*/
1457 /* We run our cleanup handler because that may close cipher contexts
1458 stored in secure memory and thus this needs to be done before we
1459 explicitly terminate secure memory. */
1463 /* at this time a bit annoying */
1464 if (opt.debug & DBG_MEMSTAT_VALUE)
1466 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1467 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1470 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1472 gcry_control (GCRYCTL_TERM_SECMEM );
1473 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1478 /* This is our callback function for gcrypt progress messages. It is
1479 set once at startup and dispatches progress messages to the
1480 corresponding threads of the agent. */
1482 agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1483 int current, int total)
1485 struct progress_dispatch_s *dispatch;
1486 npth_t mytid = npth_self ();
1490 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1491 if (dispatch->ctrl && dispatch->tid == mytid)
1493 if (dispatch && dispatch->cb)
1494 dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1498 /* If a progress dispatcher callback has been associated with the
1499 * current connection unregister it. */
1501 unregister_progress_cb (void)
1503 struct progress_dispatch_s *dispatch;
1504 npth_t mytid = npth_self ();
1506 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1507 if (dispatch->ctrl && dispatch->tid == mytid)
1511 dispatch->ctrl = NULL;
1512 dispatch->cb = NULL;
1517 /* Setup a progress callback CB for the current connection. Using a
1518 * CB of NULL disables the callback. */
1520 agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1521 int printchar, int current, int total),
1524 struct progress_dispatch_s *dispatch, *firstfree;
1525 npth_t mytid = npth_self ();
1528 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1530 if (dispatch->ctrl && dispatch->tid == mytid)
1532 if (!dispatch->ctrl && !firstfree)
1533 firstfree = dispatch;
1535 if (!dispatch) /* None allocated: Reuse or allocate a new one. */
1539 dispatch = firstfree;
1541 else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1543 dispatch->next = progress_dispatch_list;
1544 progress_dispatch_list = dispatch;
1548 log_error ("error allocating new progress dispatcher slot: %s\n",
1549 gpg_strerror (gpg_error_from_syserror ()));
1552 dispatch->ctrl = ctrl;
1553 dispatch->tid = mytid;
1560 /* Each thread has its own local variables conveyed by a control
1561 structure usually identified by an argument named CTRL. This
1562 function is called immediately after allocating the control
1563 structure. Its purpose is to setup the default values for that
1564 structure. Note that some values may have already been set. */
1566 agent_init_default_ctrl (ctrl_t ctrl)
1568 assert (ctrl->session_env);
1570 /* Note we ignore malloc errors because we can't do much about it
1571 and the request will fail anyway shortly after this
1573 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1574 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1575 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1576 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1577 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1580 xfree (ctrl->lc_ctype);
1581 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1583 if (ctrl->lc_messages)
1584 xfree (ctrl->lc_messages);
1585 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1587 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1591 /* Release all resources allocated by default in the control
1592 structure. This is the counterpart to agent_init_default_ctrl. */
1594 agent_deinit_default_ctrl (ctrl_t ctrl)
1596 unregister_progress_cb ();
1597 session_env_release (ctrl->session_env);
1600 xfree (ctrl->lc_ctype);
1601 if (ctrl->lc_messages)
1602 xfree (ctrl->lc_messages);
1606 /* Because the ssh protocol does not send us information about the
1607 current TTY setting, we use this function to use those from startup
1608 or those explicitly set. This is also used for the restricted mode
1609 where we ignore requests to change the environment. */
1611 agent_copy_startup_env (ctrl_t ctrl)
1613 static const char *names[] =
1614 {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1615 gpg_error_t err = 0;
1619 for (idx=0; !err && names[idx]; idx++)
1620 if ((value = session_env_getenv (opt.startup_env, names[idx])))
1621 err = session_env_setenv (ctrl->session_env, names[idx], value);
1623 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1624 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1625 err = gpg_error_from_syserror ();
1627 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1628 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1629 err = gpg_error_from_syserror ();
1632 log_error ("error setting default session environment: %s\n",
1633 gpg_strerror (err));
1639 /* Reread parts of the configuration. Note, that this function is
1640 obviously not thread-safe and should only be called from the PTH
1643 Fixme: Due to the way the argument parsing works, we create a
1644 memory leak here for all string type arguments. There is currently
1645 no clean way to tell whether the memory for the argument has been
1646 allocated or points into the process' original arguments. Unless
1647 we have a mechanism to tell this, we need to live on with this. */
1649 reread_configuration (void)
1651 ARGPARSE_ARGS pargs;
1653 unsigned int configlineno = 0;
1656 if (!config_filename)
1657 return; /* No config file. */
1659 fp = fopen (config_filename, "r");
1662 log_info (_("option file '%s': %s\n"),
1663 config_filename, strerror(errno) );
1667 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1669 memset (&pargs, 0, sizeof pargs);
1671 pargs.argc = &dummy;
1672 pargs.flags = 1; /* do not remove the args */
1673 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1675 if (pargs.r_opt < -1)
1676 pargs.err = 1; /* Print a warning. */
1677 else /* Try to parse this option - ignore unchangeable ones. */
1678 parse_rereadable_options (&pargs, 1);
1681 finalize_rereadable_options ();
1686 /* Return the file name of the socket we are using for native
1689 get_agent_socket_name (void)
1691 const char *s = socket_name;
1693 return (s && *s)? s : NULL;
1696 /* Return the file name of the socket we are using for SSH
1699 get_agent_ssh_socket_name (void)
1701 const char *s = socket_name_ssh;
1703 return (s && *s)? s : NULL;
1707 /* Under W32, this function returns the handle of the scdaemon
1708 notification event. Calling it the first time creates that
1710 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1712 get_agent_scd_notify_event (void)
1714 static HANDLE the_event = INVALID_HANDLE_VALUE;
1716 if (the_event == INVALID_HANDLE_VALUE)
1719 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1721 /* We need to use a manual reset event object due to the way our
1722 w32-pth wait function works: If we would use an automatic
1723 reset event we are not able to figure out which handle has
1724 been signaled because at the time we single out the signaled
1725 handles using WFSO the event has already been reset due to
1727 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1729 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1730 else if (!DuplicateHandle (GetCurrentProcess(), h,
1731 GetCurrentProcess(), &h2,
1732 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1734 log_error ("setting syncronize for scd notify event failed: %s\n",
1735 w32_strerror (-1) );
1747 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1751 /* Create a name for the socket in the home directory as using
1752 STANDARD_NAME. We also check for valid characters as well as
1753 against a maximum allowed length for a unix domain socket is done.
1754 The function terminates the process in case of an error. Returns:
1755 Pointer to an allocated string with the absolute name of the socket
1758 create_socket_name (char *standard_name, int with_homedir)
1763 name = make_filename (opt.homedir, standard_name, NULL);
1765 name = make_filename (standard_name, NULL);
1766 if (strchr (name, PATHSEP_C))
1768 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1776 /* Create a Unix domain socket with NAME. Returns the file descriptor
1777 or terminates the process in case of an error. Note that this
1778 function needs to be used for the regular socket first (indicated
1779 by PRIMARY) and only then for the extra and the ssh sockets. If
1780 the socket has been redirected the name of the real socket is
1781 stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
1782 Cygwin compatible socket is created (Windows only). */
1784 create_server_socket (char *name, int primary, int cygwin,
1785 char **r_redir_name, assuan_sock_nonce_t *nonce)
1787 struct sockaddr *addr;
1788 struct sockaddr_un *unaddr;
1793 xfree (*r_redir_name);
1794 *r_redir_name = NULL;
1796 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1797 if (fd == ASSUAN_INVALID_FD)
1799 log_error (_("can't create socket: %s\n"), strerror (errno));
1800 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1805 assuan_sock_set_flag (fd, "cygwin", 1);
1807 unaddr = xmalloc (sizeof *unaddr);
1808 addr = (struct sockaddr*)unaddr;
1813 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1815 if (errno == ENAMETOOLONG)
1816 log_error (_("socket name '%s' is too long\n"), name);
1818 log_error ("error preparing socket '%s': %s\n",
1819 name, gpg_strerror (gpg_error_from_syserror ()));
1820 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1825 *r_redir_name = xstrdup (unaddr->sun_path);
1827 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1831 len = SUN_LEN (unaddr);
1832 rc = assuan_sock_bind (fd, addr, len);
1834 /* Our error code mapping on W32CE returns EEXIST thus we also test
1837 && (errno == EADDRINUSE
1838 #ifdef HAVE_W32_SYSTEM
1843 /* Check whether a gpg-agent is already running. We do this
1844 test only if this is the primary socket. For secondary
1845 sockets we assume that a test for gpg-agent has already been
1846 done and reuse the requested socket. Testing the ssh-socket
1847 is not possible because at this point, though we know the new
1848 Assuan socket, the Assuan server and thus the ssh-agent
1849 server is not yet operational; this would lead to a hang. */
1850 if (primary && !check_for_running_agent (1))
1852 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
1853 log_set_file (NULL);
1854 log_error (_("a gpg-agent is already running - "
1855 "not starting a new one\n"));
1856 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1857 assuan_sock_close (fd);
1860 gnupg_remove (unaddr->sun_path);
1861 rc = assuan_sock_bind (fd, addr, len);
1863 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1864 log_error (_("error getting nonce for the socket\n"));
1867 /* We use gpg_strerror here because it allows us to get strings
1868 for some W32 socket error codes. */
1869 log_error (_("error binding socket to '%s': %s\n"),
1871 gpg_strerror (gpg_error_from_syserror ()));
1873 assuan_sock_close (fd);
1874 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1878 if (listen (FD2INT(fd), 5 ) == -1)
1880 log_error (_("listen() failed: %s\n"), strerror (errno));
1881 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1882 assuan_sock_close (fd);
1887 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1893 /* Check that the directory for storing the private keys exists and
1894 create it if not. This function won't fail as it is only a
1895 convenience function and not strictly necessary. */
1897 create_private_keys_directory (const char *home)
1900 struct stat statbuf;
1902 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1903 if (stat (fname, &statbuf) && errno == ENOENT)
1905 if (gnupg_mkdir (fname, "-rwx"))
1906 log_error (_("can't create directory '%s': %s\n"),
1907 fname, strerror (errno) );
1908 else if (!opt.quiet)
1909 log_info (_("directory '%s' created\n"), fname);
1914 /* Create the directory only if the supplied directory name is the
1915 same as the default one. This way we avoid to create arbitrary
1916 directories when a non-default home directory is used. To cope
1917 with HOME, we compare only the suffix if we see that the default
1918 homedir does start with a tilde. We don't stop here in case of
1919 problems because other functions will throw an error anyway.*/
1921 create_directories (void)
1923 struct stat statbuf;
1924 const char *defhome = standard_homedir ();
1927 home = make_filename (opt.homedir, NULL);
1928 if ( stat (home, &statbuf) )
1930 if (errno == ENOENT)
1933 #ifdef HAVE_W32_SYSTEM
1934 ( !compare_filenames (home, defhome) )
1937 && (strlen (home) >= strlen (defhome+1)
1938 && !strcmp (home + strlen(home)
1939 - strlen (defhome+1), defhome+1)))
1940 || (*defhome != '~' && !strcmp (home, defhome) )
1944 if (gnupg_mkdir (home, "-rwx"))
1945 log_error (_("can't create directory '%s': %s\n"),
1946 home, strerror (errno) );
1950 log_info (_("directory '%s' created\n"), home);
1951 create_private_keys_directory (home);
1956 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1958 else if ( !S_ISDIR(statbuf.st_mode))
1960 log_error (_("can't use '%s' as home directory\n"), home);
1962 else /* exists and is a directory. */
1964 create_private_keys_directory (home);
1971 /* This is the worker for the ticker. It is called every few seconds
1972 and may only do fast operations. */
1976 static time_t last_minute;
1979 last_minute = time (NULL);
1981 /* Check whether the scdaemon has died and cleanup in this case. */
1982 agent_scd_check_aliveness ();
1984 /* If we are running as a child of another process, check whether
1985 the parent is still alive and shutdown if not. */
1986 #ifndef HAVE_W32_SYSTEM
1987 if (parent_pid != (pid_t)(-1))
1989 if (kill (parent_pid, 0))
1991 shutdown_pending = 2;
1992 log_info ("parent process died - shutting down\n");
1993 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1998 #endif /*HAVE_W32_SYSTEM*/
2000 /* Code to be run from time to time. */
2001 #if CHECK_OWN_SOCKET_INTERVAL > 0
2002 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
2004 check_own_socket ();
2005 last_minute = time (NULL);
2012 /* A global function which allows us to call the reload stuff from
2013 other places too. This is only used when build for W32. */
2015 agent_sighup_action (void)
2017 log_info ("SIGHUP received - "
2018 "re-reading configuration and flushing cache\n");
2020 agent_flush_cache ();
2021 reread_configuration ();
2022 agent_reload_trustlist ();
2023 /* We flush the module name cache so that after installing a
2024 "pinentry" binary that one can be used in case the
2025 "pinentry-basic" fallback was in use. */
2026 gnupg_module_name_flush_some ();
2030 /* A helper function to handle SIGUSR2. */
2032 agent_sigusr2_action (void)
2035 log_info ("SIGUSR2 received - updating card event counter\n");
2036 /* Nothing to check right now. We only increment a counter. */
2037 bump_card_eventcounter ();
2041 #ifndef HAVE_W32_SYSTEM
2042 /* The signal handler for this program. It is expected to be run in
2043 its own trhead and not in the context of a signal handler. */
2045 handle_signal (int signo)
2049 #ifndef HAVE_W32_SYSTEM
2051 agent_sighup_action ();
2055 log_info ("SIGUSR1 received - printing internal information:\n");
2056 /* Fixme: We need to see how to integrate pth dumping into our
2058 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2059 agent_query_dump_state ();
2060 agent_scd_dump_state ();
2064 agent_sigusr2_action ();
2068 if (!shutdown_pending)
2069 log_info ("SIGTERM received - shutting down ...\n");
2071 log_info ("SIGTERM received - still %i open connections\n",
2072 active_connections);
2074 if (shutdown_pending > 2)
2076 log_info ("shutdown forced\n");
2077 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2084 log_info ("SIGINT received - immediate shutdown\n");
2085 log_info( "%s %s stopped\n", strusage(11), strusage(13));
2091 log_info ("signal %d received - no action defined\n", signo);
2096 /* Check the nonce on a new connection. This is a NOP unless we we
2097 are using our Unix domain socket emulation under Windows. */
2099 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2101 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2103 log_info (_("error reading nonce on fd %d: %s\n"),
2104 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2105 assuan_sock_close (ctrl->thread_startup.fd);
2114 #ifdef HAVE_W32_SYSTEM
2115 /* The window message processing function for Putty. Warning: This
2116 code runs as a native Windows thread. Use of our own functions
2117 needs to be bracket with pth_leave/pth_enter. */
2118 static LRESULT CALLBACK
2119 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2123 COPYDATASTRUCT *cds;
2124 const char *mapfile;
2129 PSECURITY_DESCRIPTOR psd = NULL;
2132 if (msg != WM_COPYDATA)
2134 return DefWindowProc (hwnd, msg, wparam, lparam);
2137 cds = (COPYDATASTRUCT*)lparam;
2138 if (cds->dwData != PUTTY_IPC_MAGIC)
2139 return 0; /* Ignore data with the wrong magic. */
2140 mapfile = cds->lpData;
2141 if (!cds->cbData || mapfile[cds->cbData - 1])
2142 return 0; /* Ignore empty and non-properly terminated strings. */
2147 log_debug ("ssh map file '%s'", mapfile);
2151 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2155 log_debug ("ssh map handle %p\n", maphd);
2159 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2164 mysid = w32_get_user_sid ();
2167 log_error ("error getting my sid\n");
2171 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2172 OWNER_SECURITY_INFORMATION,
2173 &mapsid, NULL, NULL, NULL,
2177 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2185 if (!ConvertSidToStringSid (mysid, &sidstr))
2187 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2189 if (!ConvertSidToStringSid (mapsid, &sidstr))
2191 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2195 if (!EqualSid (mysid, mapsid))
2197 log_error ("ssh map file has a non-matching sid\n");
2201 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2203 log_debug ("ssh IPC buffer at %p\n", data);
2207 /* log_printhex ("request:", data, 20); */
2209 ctrl = xtrycalloc (1, sizeof *ctrl);
2212 log_error ("error allocating connection control data: %s\n",
2216 ctrl->session_env = session_env_new ();
2217 if (!ctrl->session_env)
2219 log_error ("error allocating session environment block: %s\n",
2224 agent_init_default_ctrl (ctrl);
2225 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2226 ret = 1; /* Valid ssh message has been constructed. */
2227 agent_deinit_default_ctrl (ctrl);
2228 /* log_printhex (" reply:", data, 20); */
2233 UnmapViewOfFile (data);
2238 CloseHandle (maphd);
2244 #endif /*HAVE_W32_SYSTEM*/
2247 #ifdef HAVE_W32_SYSTEM
2248 /* The thread handling Putty's IPC requests. */
2250 putty_message_thread (void *arg)
2252 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2253 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2260 log_info ("putty message loop thread started\n");
2262 /* The message loop runs as thread independent from our nPth system.
2263 This also means that we need to make sure that we switch back to
2264 our system before calling any no-windows function. */
2267 /* First create a window to make sure that a message queue exists
2269 if (!RegisterClass (&wndwclass))
2272 log_error ("error registering Pageant window class");
2275 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2277 HWND_MESSAGE, /* hWndParent */
2278 NULL, /* hWndMenu */
2279 NULL, /* hInstance */
2284 log_error ("error creating Pageant window");
2288 while (GetMessage(&msg, NULL, 0, 0))
2290 TranslateMessage(&msg);
2291 DispatchMessage(&msg);
2298 log_info ("putty message loop thread stopped\n");
2301 #endif /*HAVE_W32_SYSTEM*/
2305 do_start_connection_thread (ctrl_t ctrl)
2307 agent_init_default_ctrl (ctrl);
2309 log_info (_("handler 0x%lx for fd %d started\n"),
2310 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2312 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2314 log_info (_("handler 0x%lx for fd %d terminated\n"),
2315 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2317 agent_deinit_default_ctrl (ctrl);
2323 /* This is the standard connection thread's main function. */
2325 start_connection_thread_std (void *arg)
2329 if (check_nonce (ctrl, &socket_nonce))
2331 log_error ("handler 0x%lx nonce check FAILED\n",
2332 (unsigned long) npth_self());
2336 return do_start_connection_thread (ctrl);
2340 /* This is the extra socket connection thread's main function. */
2342 start_connection_thread_extra (void *arg)
2346 if (check_nonce (ctrl, &socket_nonce_extra))
2348 log_error ("handler 0x%lx nonce check FAILED\n",
2349 (unsigned long) npth_self());
2353 ctrl->restricted = 1;
2354 return do_start_connection_thread (ctrl);
2358 /* This is the browser socket connection thread's main function. */
2360 start_connection_thread_browser (void *arg)
2364 if (check_nonce (ctrl, &socket_nonce_browser))
2366 log_error ("handler 0x%lx nonce check FAILED\n",
2367 (unsigned long) npth_self());
2371 ctrl->restricted = 2;
2372 return do_start_connection_thread (ctrl);
2376 /* This is the ssh connection thread's main function. */
2378 start_connection_thread_ssh (void *arg)
2382 if (check_nonce (ctrl, &socket_nonce_ssh))
2385 agent_init_default_ctrl (ctrl);
2387 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2388 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2390 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2392 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2393 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2395 agent_deinit_default_ctrl (ctrl);
2401 /* Connection handler loop. Wait for connection requests and spawn a
2402 thread after accepting a connection. */
2404 handle_connections (gnupg_fd_t listen_fd,
2405 gnupg_fd_t listen_fd_extra,
2406 gnupg_fd_t listen_fd_browser,
2407 gnupg_fd_t listen_fd_ssh)
2410 struct sockaddr_un paddr;
2412 fd_set fdset, read_fdset;
2417 struct timespec abstime;
2418 struct timespec curtime;
2419 struct timespec timeout;
2420 #ifdef HAVE_W32_SYSTEM
2422 unsigned int events_set;
2426 void *(*func) (void *arg);
2429 { "std", start_connection_thread_std },
2430 { "extra", start_connection_thread_extra },
2431 { "browser", start_connection_thread_browser },
2432 { "ssh", start_connection_thread_ssh }
2436 ret = npth_attr_init(&tattr);
2438 log_fatal ("error allocating thread attributes: %s\n",
2440 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2442 #ifndef HAVE_W32_SYSTEM
2444 npth_sigev_add (SIGHUP);
2445 npth_sigev_add (SIGUSR1);
2446 npth_sigev_add (SIGUSR2);
2447 npth_sigev_add (SIGINT);
2448 npth_sigev_add (SIGTERM);
2451 # ifdef HAVE_W32CE_SYSTEM
2452 /* Use a dummy event. */
2454 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2456 events[0] = get_agent_scd_notify_event ();
2457 events[1] = INVALID_HANDLE_VALUE;
2461 /* On Windows we need to fire up a separate thread to listen for
2462 requests from Putty (an SSH client), so we can replace Putty's
2463 Pageant (its ssh-agent implementation). */
2464 #ifdef HAVE_W32_SYSTEM
2469 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2472 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2475 #endif /*HAVE_W32_SYSTEM*/
2477 /* Set a flag to tell call-scd.c that it may enable event
2479 opt.sigusr2_enabled = 1;
2482 FD_SET (FD2INT (listen_fd), &fdset);
2483 nfd = FD2INT (listen_fd);
2484 if (listen_fd_extra != GNUPG_INVALID_FD)
2486 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2487 if (FD2INT (listen_fd_extra) > nfd)
2488 nfd = FD2INT (listen_fd_extra);
2490 if (listen_fd_browser != GNUPG_INVALID_FD)
2492 FD_SET ( FD2INT(listen_fd_browser), &fdset);
2493 if (FD2INT (listen_fd_browser) > nfd)
2494 nfd = FD2INT (listen_fd_browser);
2496 if (listen_fd_ssh != GNUPG_INVALID_FD)
2498 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2499 if (FD2INT (listen_fd_ssh) > nfd)
2500 nfd = FD2INT (listen_fd_ssh);
2503 listentbl[0].l_fd = listen_fd;
2504 listentbl[1].l_fd = listen_fd_extra;
2505 listentbl[2].l_fd = listen_fd_browser;
2506 listentbl[3].l_fd = listen_fd_ssh;
2508 npth_clock_gettime (&abstime);
2509 abstime.tv_sec += TIMERTICK_INTERVAL;
2513 /* Shutdown test. */
2514 if (shutdown_pending)
2516 if (active_connections == 0)
2519 /* Do not accept new connections but keep on running the
2520 loop to cope with the timer events. */
2524 /* POSIX says that fd_set should be implemented as a structure,
2525 thus a simple assignment is fine to copy the entire set. */
2528 npth_clock_gettime (&curtime);
2529 if (!(npth_timercmp (&curtime, &abstime, <)))
2533 npth_clock_gettime (&abstime);
2534 abstime.tv_sec += TIMERTICK_INTERVAL;
2536 npth_timersub (&abstime, &curtime, &timeout);
2538 #ifndef HAVE_W32_SYSTEM
2539 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2540 npth_sigev_sigmask ());
2541 saved_errno = errno;
2545 while (npth_sigev_get_pending (&signo))
2546 handle_signal (signo);
2549 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2550 events, &events_set);
2551 saved_errno = errno;
2553 /* This is valid even if npth_eselect returns an error. */
2555 agent_sigusr2_action ();
2558 if (ret == -1 && saved_errno != EINTR)
2560 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2561 strerror (saved_errno));
2566 /* Interrupt or timeout. Will be handled when calculating the
2570 if (!shutdown_pending)
2576 for (idx=0; idx < DIM(listentbl); idx++)
2578 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2580 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2583 plen = sizeof paddr;
2584 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2585 (struct sockaddr *)&paddr, &plen));
2586 if (fd == GNUPG_INVALID_FD)
2588 log_error ("accept failed for %s: %s\n",
2589 listentbl[idx].name, strerror (errno));
2591 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2593 log_error ("error allocating connection data for %s: %s\n",
2594 listentbl[idx].name, strerror (errno) );
2595 assuan_sock_close (fd);
2597 else if ( !(ctrl->session_env = session_env_new ()))
2599 log_error ("error allocating session env block for %s: %s\n",
2600 listentbl[idx].name, strerror (errno) );
2602 assuan_sock_close (fd);
2606 ctrl->thread_startup.fd = fd;
2607 ret = npth_create (&thread, &tattr,
2608 listentbl[idx].func, ctrl);
2611 log_error ("error spawning connection handler for %s:"
2612 " %s\n", listentbl[idx].name, strerror (ret));
2613 assuan_sock_close (fd);
2617 fd = GNUPG_INVALID_FD;
2623 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2624 npth_attr_destroy (&tattr);
2629 /* Helper for check_own_socket. */
2631 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2633 membuf_t *mb = opaque;
2634 put_membuf (mb, buffer, length);
2639 /* The thread running the actual check. We need to run this in a
2640 separate thread so that check_own_thread can be called from the
2643 check_own_socket_thread (void *arg)
2646 char *sockname = arg;
2647 assuan_context_t ctx = NULL;
2651 check_own_socket_running++;
2653 rc = assuan_new (&ctx);
2656 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2660 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2663 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2667 init_membuf (&mb, 100);
2668 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2669 NULL, NULL, NULL, NULL);
2670 put_membuf (&mb, "", 1);
2671 buffer = get_membuf (&mb, NULL);
2674 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2675 "GETINFO pid", gpg_strerror (rc));
2678 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2680 log_error ("socket is now serviced by another server\n");
2683 else if (opt.verbose > 1)
2684 log_error ("socket is still served by this server\n");
2691 assuan_release (ctx);
2694 /* We may not remove the socket as it is now in use by another
2695 server. Setting the name to empty does this. */
2698 if (socket_name_ssh)
2699 *socket_name_ssh = 0;
2700 shutdown_pending = 2;
2701 log_info ("this process is useless - shutting down\n");
2703 check_own_socket_running--;
2708 /* Check whether we are still listening on our own socket. In case
2709 another gpg-agent process started after us has taken ownership of
2710 our socket, we would linger around without any real task. Thus we
2711 better check once in a while whether we are really needed. */
2713 check_own_socket (void)
2720 if (disable_check_own_socket)
2723 if (check_own_socket_running || shutdown_pending)
2724 return; /* Still running or already shutting down. */
2726 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2728 return; /* Out of memory. */
2730 err = npth_attr_init (&tattr);
2733 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2734 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2736 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2737 npth_attr_destroy (&tattr);
2742 /* Figure out whether an agent is available and running. Prints an
2743 error if not. If SILENT is true, no messages are printed.
2744 Returns 0 if the agent is running. */
2746 check_for_running_agent (int silent)
2750 assuan_context_t ctx = NULL;
2752 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2754 err = assuan_new (&ctx);
2756 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2761 log_error (_("no gpg-agent running in this session\n"));
2764 assuan_release (ctx);
2768 if (!opt.quiet && !silent)
2769 log_info ("gpg-agent running and available\n");
2771 assuan_release (ctx);