1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc.
3 * Copyright (C) 2000-2016 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 <https://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. */
56 #include "../common/i18n.h"
57 #include "../common/sysutils.h"
58 #include "../common/gc-opt-flags.h"
59 #include "../common/exechelp.h"
60 #include "../common/asshelp.h"
61 #include "../common/init.h"
64 enum cmd_and_opt_values
96 oPinentryInvisibleChar,
109 oEnforcePassphraseConstraints,
111 oMinPassphraseNonalpha,
112 oCheckPassphrasePattern,
114 oEnablePassphraseHistory,
115 oEnableExtendedKeyFormat,
117 oNoUseStandardSocket,
122 oIgnoreCacheForSigning,
125 oAllowPresetPassphrase,
126 oAllowLoopbackPinentry,
127 oNoAllowLoopbackPinentry,
128 oNoAllowExternalCache,
133 oSSHFingerprintDigest,
136 oDisableCheckOwnSocket,
142 # define ENAMETOOLONG EINVAL
146 static ARGPARSE_OPTS opts[] = {
148 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
149 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
150 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
152 ARGPARSE_group (301, N_("@Options:\n ")),
154 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
155 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
156 #ifndef HAVE_W32_SYSTEM
157 ARGPARSE_s_n (oSupervised, "supervised", N_("run in supervised mode")),
159 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
160 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
161 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
162 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
163 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
165 ARGPARSE_s_s (oDebug, "debug", "@"),
166 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
167 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
168 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
169 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
170 ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
172 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
173 ARGPARSE_s_n (oGrab, "grab", "@"),
174 /* FIXME: Add the below string for 2.3 */
175 /* N_("let PIN-Entry grab keyboard and mouse")), */
176 ARGPARSE_s_n (oNoGrab, "no-grab", "@"),
177 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
178 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
179 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
180 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
181 ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
182 ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
183 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
184 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
185 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
186 /* */ N_("do not use the SCdaemon") ),
187 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
189 ARGPARSE_s_s (oExtraSocket, "extra-socket",
190 /* */ N_("|NAME|accept some commands via NAME")),
192 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
194 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
196 ARGPARSE_s_n (oBatch, "batch", "@"),
197 ARGPARSE_s_s (oHomedir, "homedir", "@"),
199 ARGPARSE_s_s (oDisplay, "display", "@"),
200 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
201 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
202 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
203 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
204 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
205 ARGPARSE_s_n (oKeepTTY, "keep-tty",
206 /* */ N_("ignore requests to change the TTY")),
207 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
208 /* */ N_("ignore requests to change the X display")),
210 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
211 N_("|N|expire cached PINs after N seconds")),
212 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
213 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
214 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
216 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
218 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
219 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
220 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
221 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
222 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
224 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
225 /* */ N_("do not use the PIN cache when signing")),
226 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
227 /* */ N_("disallow the use of an external password cache")),
228 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
229 /* */ N_("disallow clients to mark keys as \"trusted\"")),
230 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
231 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
232 /* */ N_("allow presetting passphrase")),
233 ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
234 N_("disallow caller to override the pinentry")),
235 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
236 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
237 /* */ N_("allow passphrase to be prompted through Emacs")),
239 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
240 ARGPARSE_s_s (oSSHFingerprintDigest, "ssh-fingerprint-digest",
241 N_("|ALGO|use ALGO to show ssh fingerprints")),
242 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
243 #ifdef HAVE_W32_SYSTEM
244 /* */ N_("enable putty support")
249 ARGPARSE_s_n (oEnableExtendedKeyFormat, "enable-extended-key-format", "@"),
251 /* Dummy options for backward compatibility. */
252 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
253 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
254 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
256 ARGPARSE_end () /* End of list */
260 /* The list of supported debug flags. */
261 static struct debug_flags_s debug_flags [] =
263 { DBG_MPI_VALUE , "mpi" },
264 { DBG_CRYPTO_VALUE , "crypto" },
265 { DBG_MEMORY_VALUE , "memory" },
266 { DBG_CACHE_VALUE , "cache" },
267 { DBG_MEMSTAT_VALUE, "memstat" },
268 { DBG_HASHING_VALUE, "hashing" },
269 { DBG_IPC_VALUE , "ipc" },
270 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
275 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
276 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
277 #define MAX_CACHE_TTL (120*60) /* 2 hours */
278 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
279 #define MIN_PASSPHRASE_LEN (8)
280 #define MIN_PASSPHRASE_NONALPHA (1)
281 #define MAX_PASSPHRASE_DAYS (0)
283 /* The timer tick used for housekeeping stuff. Note that on Windows
284 * we use a SetWaitableTimer seems to signal earlier than about 2
285 * seconds. Thus we use 4 seconds on all platforms except for
286 * Windowsce. CHECK_OWN_SOCKET_INTERVAL defines how often we check
287 * our own socket in standard socket mode. If that value is 0 we
288 * don't check at all. All values are in seconds. */
289 #if defined(HAVE_W32CE_SYSTEM)
290 # define TIMERTICK_INTERVAL (60)
291 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
293 # define TIMERTICK_INTERVAL (4)
294 # define CHECK_OWN_SOCKET_INTERVAL (60)
298 /* Flag indicating that the ssh-agent subsystem has been enabled. */
299 static int ssh_support;
301 #ifdef HAVE_W32_SYSTEM
302 /* Flag indicating that support for Putty has been enabled. */
303 static int putty_support;
304 /* A magic value used with WM_COPYDATA. */
305 #define PUTTY_IPC_MAGIC 0x804e50ba
306 /* To avoid surprises we limit the size of the mapped IPC file to this
307 value. Putty currently (0.62) uses 8k, thus 16k should be enough
308 for the foreseeable future. */
309 #define PUTTY_IPC_MAXLEN 16384
310 #endif /*HAVE_W32_SYSTEM*/
312 /* The list of open file descriptors at startup. Note that this list
313 * has been allocated using the standard malloc. */
314 #ifndef HAVE_W32_SYSTEM
315 static int *startup_fd_list;
318 /* The signal mask at startup and a flag telling whether it is valid. */
319 #ifdef HAVE_SIGPROCMASK
320 static sigset_t startup_signal_mask;
321 static int startup_signal_mask_valid;
324 /* Flag to indicate that a shutdown was requested. */
325 static int shutdown_pending;
327 /* Counter for the currently running own socket checks. */
328 static int check_own_socket_running;
330 /* Flags to indicate that check_own_socket shall not be called. */
331 static int disable_check_own_socket;
333 /* Flag indicating that we are in supervised mode. */
334 static int is_supervised;
336 /* Flag to inhibit socket removal in cleanup. */
337 static int inhibit_socket_removal;
339 /* It is possible that we are currently running under setuid permissions */
340 static int maybe_setuid = 1;
342 /* Name of the communication socket used for native gpg-agent
343 requests. The second variable is either NULL or a malloced string
344 with the real socket name in case it has been redirected. */
345 static char *socket_name;
346 static char *redir_socket_name;
348 /* Name of the optional extra socket used for native gpg-agent requests. */
349 static char *socket_name_extra;
350 static char *redir_socket_name_extra;
352 /* Name of the optional browser socket used for native gpg-agent requests. */
353 static char *socket_name_browser;
354 static char *redir_socket_name_browser;
356 /* Name of the communication socket used for ssh-agent protocol. */
357 static char *socket_name_ssh;
358 static char *redir_socket_name_ssh;
360 /* We need to keep track of the server's nonces (these are dummies for
362 static assuan_sock_nonce_t socket_nonce;
363 static assuan_sock_nonce_t socket_nonce_extra;
364 static assuan_sock_nonce_t socket_nonce_browser;
365 static assuan_sock_nonce_t socket_nonce_ssh;
368 /* Default values for options passed to the pinentry. */
369 static char *default_display;
370 static char *default_ttyname;
371 static char *default_ttytype;
372 static char *default_lc_ctype;
373 static char *default_lc_messages;
374 static char *default_xauthority;
376 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
377 static char *config_filename;
379 /* Helper to implement --debug-level */
380 static const char *debug_level;
382 /* Keep track of the current log file so that we can avoid updating
383 the log file after a SIGHUP if it didn't changed. Malloced. */
384 static char *current_logfile;
386 /* The handle_tick() function may test whether a parent is still
387 * running. We record the PID of the parent here or -1 if it should
389 static pid_t parent_pid = (pid_t)(-1);
391 /* This flag is true if the inotify mechanism for detecting the
392 * removal of the homedir is active. This flag is used to disable the
393 * alternative but portable stat based check. */
394 static int have_homedir_inotify;
396 /* Depending on how gpg-agent was started, the homedir inotify watch
397 * may not be reliable. This flag is set if we assume that inotify
399 static int reliable_homedir_inotify;
401 /* Number of active connections. */
402 static int active_connections;
404 /* This object is used to dispatch progress messages from Libgcrypt to
405 * the right thread. Given that we will have at max only a few dozen
406 * connections at a time, using a linked list is the easiest way to
408 struct progress_dispatch_s
410 struct progress_dispatch_s *next;
411 /* The control object of the connection. If this is NULL no
412 * connection is associated with this item and it is free for reuse
413 * by new connections. */
416 /* The thread id of (npth_self) of the connection. */
419 /* The callback set by the connection. This is similar to the
420 * Libgcrypt callback but with the control object passed as the
422 void (*cb)(ctrl_t ctrl,
423 const char *what, int printchar,
424 int current, int total);
426 struct progress_dispatch_s *progress_dispatch_list;
435 static char *create_socket_name (char *standard_name, int with_homedir);
436 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
438 assuan_sock_nonce_t *nonce);
439 static void create_directories (void);
441 static void agent_libgcrypt_progress_cb (void *data, const char *what,
443 int current, int total);
444 static void agent_init_default_ctrl (ctrl_t ctrl);
445 static void agent_deinit_default_ctrl (ctrl_t ctrl);
447 static void handle_connections (gnupg_fd_t listen_fd,
448 gnupg_fd_t listen_fd_extra,
449 gnupg_fd_t listen_fd_browser,
450 gnupg_fd_t listen_fd_ssh);
451 static void check_own_socket (void);
452 static int check_for_running_agent (int silent);
454 /* Pth wrapper function definitions. */
455 ASSUAN_SYSTEM_NPTH_IMPL;
462 /* Allocate a string describing a library version by calling a GETFNC.
463 This function is expected to be called only once. GETFNC is
464 expected to have a semantic like gcry_check_version (). */
466 make_libversion (const char *libname, const char *(*getfnc)(const char*))
473 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
477 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
478 strcpy (stpcpy (stpcpy (result, libname), " "), s);
482 /* Return strings describing this program. The case values are
483 described in common/argparse.c:strusage. The values here override
484 the default values given by strusage. */
486 my_strusage (int level)
488 static char *ver_gcry;
493 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
495 case 13: p = VERSION; break;
496 case 17: p = PRINTABLE_OS_NAME; break;
497 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
498 reporting address. This is so that we can change the
499 reporting address without breaking the translations. */
500 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
504 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
509 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
511 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
512 "Secret key management for @GNUPG@\n");
522 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
523 only the active debug flags are propagated to the subsystems. With
524 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
525 all flags already set. Note that we don't fail here, because it is
526 important to keep gpg-agent running even after re-reading the
527 options due to a SIGHUP. */
531 int numok = (debug_level && digitp (debug_level));
532 int numlvl = numok? atoi (debug_level) : 0;
536 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
538 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
539 opt.debug = DBG_IPC_VALUE;
540 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
541 opt.debug = DBG_IPC_VALUE;
542 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
543 opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE);
544 else if (!strcmp (debug_level, "guru") || numok)
547 /* Unless the "guru" string has been used we don't want to allow
548 hashing debugging. The rationale is that people tend to
549 select the highest debug value and would then clutter their
550 disk with debug files which may reveal confidential data. */
552 opt.debug &= ~(DBG_HASHING_VALUE);
556 log_error (_("invalid debug-level '%s' given\n"), debug_level);
557 opt.debug = 0; /* Reset debugging, so that prior debug
558 statements won't have an undesired effect. */
561 if (opt.debug && !opt.verbose)
563 if (opt.debug && opt.quiet)
566 if (opt.debug & DBG_MPI_VALUE)
567 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
568 if (opt.debug & DBG_CRYPTO_VALUE )
569 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
570 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
573 parse_debug_flag (NULL, &opt.debug, debug_flags);
577 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
578 the corresponding real name if the socket has been redirected. */
580 remove_socket (char *name, char *redir_name)
593 /* Discover which inherited file descriptors correspond to which
594 * services/sockets offered by gpg-agent, using the LISTEN_FDS and
595 * LISTEN_FDNAMES convention. The understood labels are "ssh",
596 * "extra", and "browser". "std" or other labels will be interpreted
597 * as the standard socket.
599 * This function is designed to log errors when the expected file
600 * descriptors don't make sense, but to do its best to continue to
601 * work even in the face of minor misconfigurations.
603 * For more information on the LISTEN_FDS convention, see
604 * sd_listen_fds(3) on certain Linux distributions.
606 #ifndef HAVE_W32_SYSTEM
608 map_supervised_sockets (gnupg_fd_t *r_fd,
609 gnupg_fd_t *r_fd_extra,
610 gnupg_fd_t *r_fd_browser,
611 gnupg_fd_t *r_fd_ssh)
618 { "ssh", &r_fd_ssh, &socket_name_ssh },
619 { "browser", &r_fd_browser, &socket_name_browser },
620 { "extra", &r_fd_extra, &socket_name_extra },
621 { "std", &r_fd, &socket_name } /* (Must be the last item.) */
628 *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
630 /* Print a warning if LISTEN_PID does not match outr pid. */
631 envvar = getenv ("LISTEN_PID");
633 log_error ("no LISTEN_PID environment variable found in "
634 "--supervised mode (ignoring)\n");
635 else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
636 log_error ("environment variable LISTEN_PID (%lu) does not match"
637 " our pid (%lu) in --supervised mode (ignoring)\n",
638 (unsigned long)strtoul (envvar, NULL, 10),
639 (unsigned long)getpid ());
641 /* Parse LISTEN_FDNAMES into the array FDNAMES. */
642 envvar = getenv ("LISTEN_FDNAMES");
645 fdnames = strtokenize (envvar, ":");
648 log_error ("strtokenize failed: %s\n",
649 gpg_strerror (gpg_error_from_syserror ()));
652 for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
661 /* Parse LISTEN_FDS into fd_count or provide a replacement. */
662 envvar = getenv ("LISTEN_FDS");
664 fd_count = atoi (envvar);
667 log_error ("no LISTEN_FDS environment variable found in --supervised"
668 " mode (relying on LISTEN_FDNAMES instead)\n");
673 log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
674 "found in --supervised mode"
675 " (assuming 1 active descriptor)\n");
681 log_error ("--supervised mode expects at least one file descriptor"
682 " (was told %d, carrying on as though it were 1)\n",
687 /* Assign the descriptors to the return values. */
693 log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
694 " in --supervised mode."
695 " (ignoring all sockets but the first one)\n",
697 if (fstat (3, &statbuf) == -1 && errno ==EBADF)
698 log_fatal ("file descriptor 3 must be valid in --supervised mode"
699 " if LISTEN_FDNAMES is not set\n");
701 socket_name = gnupg_get_socket_name (3);
703 else if (fd_count != nfdnames)
705 log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
706 "LISTEN_FDS (%d) in --supervised mode\n",
714 for (i = 0; i < nfdnames; i++)
716 for (j = 0; j < DIM (tbl); j++)
718 if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
721 if (**tbl[j].fdaddr == -1)
723 name = gnupg_get_socket_name (fd);
726 **tbl[j].fdaddr = fd;
727 *tbl[j].nameaddr = name;
728 log_info ("using fd %d for %s socket (%s)\n",
729 fd, tbl[j].label, name);
733 log_error ("cannot listen on fd %d for %s socket\n",
740 log_error ("cannot listen on more than one %s socket\n",
752 #endif /*!HAVE_W32_SYSTEM*/
755 /* Cleanup code for this program. This is either called has an atexit
756 handler or directly. */
765 deinitialize_module_cache ();
766 if (!is_supervised && !inhibit_socket_removal)
768 remove_socket (socket_name, redir_socket_name);
769 if (opt.extra_socket > 1)
770 remove_socket (socket_name_extra, redir_socket_name_extra);
771 if (opt.browser_socket > 1)
772 remove_socket (socket_name_browser, redir_socket_name_browser);
773 remove_socket (socket_name_ssh, redir_socket_name_ssh);
779 /* Handle options which are allowed to be reset after program start.
780 Return true when the current option in PARGS could be handled and
781 false if not. As a special feature, passing a value of NULL for
782 PARGS, resets the options to the default. REREAD should be set
783 true if it is not the initial option parsing. */
785 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
795 opt.debug_pinentry = 0;
796 opt.pinentry_program = NULL;
797 opt.pinentry_touch_file = NULL;
798 xfree (opt.pinentry_invisible_char);
799 opt.pinentry_invisible_char = NULL;
800 opt.pinentry_timeout = 0;
801 opt.scdaemon_program = NULL;
802 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
803 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
804 opt.max_cache_ttl = MAX_CACHE_TTL;
805 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
806 opt.enforce_passphrase_constraints = 0;
807 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
808 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
809 opt.check_passphrase_pattern = NULL;
810 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
811 opt.enable_passphrase_history = 0;
812 opt.enable_extended_key_format = 0;
813 opt.ignore_cache_for_signing = 0;
814 opt.allow_mark_trusted = 1;
815 opt.allow_external_cache = 1;
816 opt.allow_loopback_pinentry = 1;
817 opt.allow_emacs_pinentry = 0;
818 opt.disable_scdaemon = 0;
819 disable_check_own_socket = 0;
820 /* Note: When changing the next line, change also gpgconf_list. */
821 opt.ssh_fingerprint_digest = GCRY_MD_MD5;
825 switch (pargs->r_opt)
827 case oQuiet: opt.quiet = 1; break;
828 case oVerbose: opt.verbose++; break;
831 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
833 case oDebugAll: opt.debug = ~0; break;
834 case oDebugLevel: debug_level = pargs->r.ret_str; break;
835 case oDebugPinentry: opt.debug_pinentry = 1; break;
839 return 0; /* not handeld */
840 if (!current_logfile || !pargs->r.ret_str
841 || strcmp (current_logfile, pargs->r.ret_str))
843 log_set_file (pargs->r.ret_str);
844 xfree (current_logfile);
845 current_logfile = xtrystrdup (pargs->r.ret_str);
849 case oNoGrab: opt.no_grab |= 1; break;
850 case oGrab: opt.no_grab |= 2; break;
852 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
853 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
854 case oPinentryInvisibleChar:
855 xfree (opt.pinentry_invisible_char);
856 opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
858 case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
859 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
860 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
861 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
863 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
864 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
865 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
866 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
868 case oEnforcePassphraseConstraints:
869 opt.enforce_passphrase_constraints=1;
871 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
872 case oMinPassphraseNonalpha:
873 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
875 case oCheckPassphrasePattern:
876 opt.check_passphrase_pattern = pargs->r.ret_str;
878 case oMaxPassphraseDays:
879 opt.max_passphrase_days = pargs->r.ret_ulong;
881 case oEnablePassphraseHistory:
882 opt.enable_passphrase_history = 1;
885 case oEnableExtendedKeyFormat:
886 opt.enable_extended_key_format = 1;
889 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
891 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
892 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
894 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
896 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
897 case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
899 case oNoAllowExternalCache: opt.allow_external_cache = 0;
902 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
905 case oSSHFingerprintDigest:
906 i = gcry_md_map_name (pargs->r.ret_str);
908 log_error (_("selected digest algorithm is invalid\n"));
910 opt.ssh_fingerprint_digest = i;
914 return 0; /* not handled */
917 return 1; /* handled */
921 /* Fixup some options after all have been processed. */
923 finalize_rereadable_options (void)
925 /* Hack to allow --grab to override --no-grab. */
926 if ((opt.no_grab & 2))
932 thread_init_once (void)
934 static int npth_initialized = 0;
936 if (!npth_initialized)
941 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
942 /* Now that we have set the syscall clamp we need to tell Libgcrypt
943 * that it should get them from libgpg-error. Note that Libgcrypt
944 * has already been initialized but at that point nPth was not
945 * initialized and thus Libgcrypt could not set its system call
947 #if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */
948 gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
954 initialize_modules (void)
957 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
958 initialize_module_cache ();
959 initialize_module_call_pinentry ();
960 initialize_module_call_scd ();
961 initialize_module_trustlist ();
965 /* The main entry point. */
967 main (int argc, char **argv )
972 FILE *configfp = NULL;
973 char *configname = NULL;
975 unsigned configlineno;
977 int default_config =1;
982 char *logfile = NULL;
984 int gpgconf_list = 0;
986 struct assuan_malloc_hooks malloc_hooks;
988 early_system_init ();
990 /* Before we do anything else we save the list of currently open
991 file descriptors and the signal mask. This info is required to
992 do the exec call properly. We don't need it on Windows. */
993 #ifndef HAVE_W32_SYSTEM
994 startup_fd_list = get_all_open_fds ();
995 #endif /*!HAVE_W32_SYSTEM*/
996 #ifdef HAVE_SIGPROCMASK
997 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
998 startup_signal_mask_valid = 1;
999 #endif /*HAVE_SIGPROCMASK*/
1001 /* Set program name etc. */
1002 set_strusage (my_strusage);
1003 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1004 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1005 when adding any stuff between here and the call to INIT_SECMEM()
1006 somewhere after the option parsing */
1007 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
1009 /* Make sure that our subsystems are ready. */
1011 init_common_subsystems (&argc, &argv);
1013 malloc_hooks.malloc = gcry_malloc;
1014 malloc_hooks.realloc = gcry_realloc;
1015 malloc_hooks.free = gcry_free;
1016 assuan_set_malloc_hooks (&malloc_hooks);
1017 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1018 assuan_sock_init ();
1019 setup_libassuan_logging (&opt.debug, NULL);
1021 setup_libgcrypt_logging ();
1022 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1023 gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
1025 disable_core_dumps ();
1027 /* Set default options. */
1028 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
1030 shell = getenv ("SHELL");
1031 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1034 /* Record some of the original environment strings. */
1038 static const char *names[] =
1039 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
1042 opt.startup_env = session_env_new ();
1043 if (!opt.startup_env)
1044 err = gpg_error_from_syserror ();
1045 for (idx=0; !err && names[idx]; idx++)
1047 s = getenv (names[idx]);
1049 err = session_env_setenv (opt.startup_env, names[idx], s);
1053 s = gnupg_ttyname (0);
1055 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
1058 log_fatal ("error recording startup environment: %s\n",
1059 gpg_strerror (err));
1061 /* Fixme: Better use the locale function here. */
1062 opt.startup_lc_ctype = getenv ("LC_CTYPE");
1063 if (opt.startup_lc_ctype)
1064 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
1065 opt.startup_lc_messages = getenv ("LC_MESSAGES");
1066 if (opt.startup_lc_messages)
1067 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
1070 /* Check whether we have a config file on the commandline */
1075 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1076 while (arg_parse( &pargs, opts))
1078 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
1080 else if (pargs.r_opt == oOptions)
1081 { /* yes there is one, so we do not try the default one, but
1082 read the option file when it is encountered at the
1086 else if (pargs.r_opt == oNoOptions)
1087 default_config = 0; /* --no-options */
1088 else if (pargs.r_opt == oHomedir)
1089 gnupg_set_homedir (pargs.r.ret_str);
1090 else if (pargs.r_opt == oDebugQuickRandom)
1092 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
1097 /* Initialize the secure memory. */
1098 gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0);
1102 Now we are now working under our real uid
1106 configname = make_filename (gnupg_homedir (),
1107 GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1113 pargs.flags= 1; /* do not remove the args */
1118 configfp = fopen (configname, "r");
1124 log_info (_("Note: no default option file '%s'\n"),
1126 /* Save the default conf file name so that
1127 reread_configuration is able to test whether the
1128 config file has been created in the meantime. */
1129 xfree (config_filename);
1130 config_filename = configname;
1135 log_error (_("option file '%s': %s\n"),
1136 configname, strerror(errno) );
1142 if (parse_debug && configname )
1143 log_info (_("reading options from '%s'\n"), configname );
1147 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
1149 if (parse_rereadable_options (&pargs, 0))
1150 continue; /* Already handled */
1151 switch (pargs.r_opt)
1153 case aGPGConfList: gpgconf_list = 1; break;
1154 case aGPGConfTest: gpgconf_list = 2; break;
1155 case aUseStandardSocketP: gpgconf_list = 3; break;
1156 case oBatch: opt.batch=1; break;
1158 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1161 /* config files may not be nested (silently ignore them) */
1165 configname = xstrdup(pargs.r.ret_str);
1169 case oNoGreeting: /* Dummy option. */ break;
1170 case oNoVerbose: opt.verbose = 0; break;
1171 case oNoOptions: break; /* no-options */
1172 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1173 case oNoDetach: nodetach = 1; break;
1174 case oLogFile: logfile = pargs.r.ret_str; break;
1175 case oCsh: csh_style = 1; break;
1176 case oSh: csh_style = 0; break;
1177 case oServer: pipe_server = 1; break;
1178 case oDaemon: is_daemon = 1; break;
1179 case oSupervised: is_supervised = 1; break;
1181 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
1182 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
1183 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
1184 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
1185 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
1187 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
1190 case oUseStandardSocket:
1191 case oNoUseStandardSocket:
1192 obsolete_option (configname, configlineno, "use-standard-socket");
1195 case oFakedSystemTime:
1197 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1198 if (faked_time == (time_t)(-1))
1199 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1200 gnupg_set_time (faked_time, 0);
1204 case oKeepTTY: opt.keep_tty = 1; break;
1205 case oKeepDISPLAY: opt.keep_display = 1; break;
1212 # ifdef HAVE_W32_SYSTEM
1218 opt.extra_socket = 1; /* (1 = points into argv) */
1219 socket_name_extra = pargs.r.ret_str;
1222 case oBrowserSocket:
1223 opt.browser_socket = 1; /* (1 = points into argv) */
1224 socket_name_browser = pargs.r.ret_str;
1227 case oDebugQuickRandom:
1228 /* Only used by the first stage command line parser. */
1232 obsolete_option (configname, configlineno, "write-env-file");
1235 default : pargs.err = configfp? 1:2; break;
1242 /* Keep a copy of the name so that it can be read on SIGHUP. */
1243 if (config_filename != configname)
1245 xfree (config_filename);
1246 config_filename = configname;
1254 if (log_get_errorcount(0))
1257 finalize_rereadable_options ();
1259 /* Print a warning if an argument looks like an option. */
1260 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1264 for (i=0; i < argc; i++)
1265 if (argv[i][0] == '-' && argv[i][1] == '-')
1266 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1270 /* gpg-agent usually does not output any messages because it runs in
1271 the background. For log files it is acceptable to have messages
1272 always encoded in utf-8. We switch here to utf-8, so that
1273 commands like --help still give native messages. It is far
1274 easier to switch only once instead of for every message and it
1275 actually helps when more then one thread is active (avoids an
1276 extra copy step). */
1277 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1280 if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
1282 /* We have been called without any command and thus we merely
1283 check whether an agent is already running. We do this right
1284 here so that we don't clobber a logfile with this check but
1285 print the status directly to stderr. */
1288 check_for_running_agent (0);
1294 else if (!opt.extra_socket)
1295 opt.extra_socket = 1;
1296 else if (socket_name_extra
1297 && (!strcmp (socket_name_extra, "none")
1298 || !strcmp (socket_name_extra, "/dev/null")))
1300 /* User requested not to create this socket. */
1301 opt.extra_socket = 0;
1302 socket_name_extra = NULL;
1307 else if (!opt.browser_socket)
1308 opt.browser_socket = 1;
1309 else if (socket_name_browser
1310 && (!strcmp (socket_name_browser, "none")
1311 || !strcmp (socket_name_browser, "/dev/null")))
1313 /* User requested not to create this socket. */
1314 opt.browser_socket = 0;
1315 socket_name_browser = NULL;
1320 if (atexit (cleanup))
1322 log_error ("atexit failed\n");
1327 /* Try to create missing directories. */
1328 create_directories ();
1330 if (debug_wait && pipe_server)
1332 thread_init_once ();
1333 log_debug ("waiting for debugger - my pid is %u .....\n",
1334 (unsigned int)getpid());
1335 gnupg_sleep (debug_wait);
1336 log_debug ("... okay\n");
1339 if (gpgconf_list == 3)
1341 /* We now use the standard socket always - return true for
1342 backward compatibility. */
1345 else if (gpgconf_list == 2)
1347 else if (gpgconf_list)
1352 /* List options and default values in the GPG Conf format. */
1353 filename = make_filename (gnupg_homedir (),
1354 GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1355 filename_esc = percent_escape (filename, NULL);
1357 es_printf ("%s-%s.conf:%lu:\"%s\n",
1358 GPGCONF_NAME, GPG_AGENT_NAME,
1359 GC_OPT_FLAG_DEFAULT, filename_esc);
1361 xfree (filename_esc);
1363 es_printf ("verbose:%lu:\n"
1365 "debug-level:%lu:\"none:\n"
1367 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1368 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1369 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1370 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1371 es_printf ("default-cache-ttl:%lu:%d:\n",
1372 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1373 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1374 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1375 es_printf ("max-cache-ttl:%lu:%d:\n",
1376 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1377 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1378 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1379 es_printf ("enforce-passphrase-constraints:%lu:\n",
1380 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1381 es_printf ("min-passphrase-len:%lu:%d:\n",
1382 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1383 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1384 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1385 MIN_PASSPHRASE_NONALPHA);
1386 es_printf ("check-passphrase-pattern:%lu:\n",
1387 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1388 es_printf ("max-passphrase-days:%lu:%d:\n",
1389 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1390 MAX_PASSPHRASE_DAYS);
1391 es_printf ("enable-passphrase-history:%lu:\n",
1392 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1393 es_printf ("no-grab:%lu:\n",
1394 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1395 es_printf ("ignore-cache-for-signing:%lu:\n",
1396 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1397 es_printf ("no-allow-external-cache:%lu:\n",
1398 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1399 es_printf ("no-allow-mark-trusted:%lu:\n",
1400 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1401 es_printf ("disable-scdaemon:%lu:\n",
1402 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1403 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1404 es_printf ("ssh-fingerprint-digest:%lu:\"%s:\n",
1405 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, "md5");
1406 #ifdef HAVE_W32_SYSTEM
1407 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1409 es_printf ("no-allow-loopback-pinentry:%lu:\n",
1410 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1411 es_printf ("allow-emacs-pinentry:%lu:\n",
1412 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1413 es_printf ("pinentry-timeout:%lu:0:\n",
1414 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1415 es_printf ("enable-extended-key-format:%lu:\n",
1416 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1417 es_printf ("grab:%lu:\n",
1418 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1423 /* Now start with logging to a file if this is desired. */
1426 log_set_file (logfile);
1427 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1428 | GPGRT_LOG_WITH_TIME
1429 | GPGRT_LOG_WITH_PID));
1430 current_logfile = xstrdup (logfile);
1433 /* Make sure that we have a default ttyname. */
1434 if (!default_ttyname && gnupg_ttyname (1))
1435 default_ttyname = xstrdup (gnupg_ttyname (1));
1436 if (!default_ttytype && getenv ("TERM"))
1437 default_ttytype = xstrdup (getenv ("TERM"));
1442 /* This is the simple pipe based server */
1445 initialize_modules ();
1447 ctrl = xtrycalloc (1, sizeof *ctrl);
1450 log_error ("error allocating connection control data: %s\n",
1454 ctrl->session_env = session_env_new ();
1455 if (!ctrl->session_env)
1457 log_error ("error allocating session environment block: %s\n",
1462 agent_init_default_ctrl (ctrl);
1463 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1464 agent_deinit_default_ctrl (ctrl);
1467 else if (is_supervised)
1469 #ifndef HAVE_W32_SYSTEM
1470 gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
1472 initialize_modules ();
1474 /* when supervised and sending logs to stderr, the process
1475 supervisor should handle log entry metadata (pid, name,
1478 log_set_prefix (NULL, 0);
1480 log_info ("%s %s starting in supervised mode.\n",
1481 strusage(11), strusage(13) );
1483 /* See below in "regular server mode" on why we remove certain
1485 if (!opt.keep_display)
1486 gnupg_unsetenv ("DISPLAY");
1487 gnupg_unsetenv ("INSIDE_EMACS");
1489 /* Virtually create the sockets. Note that we use -1 here
1490 * because the whole thing works only on Unix. */
1491 map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
1493 log_fatal ("no standard socket provided\n");
1495 #ifdef HAVE_SIGPROCMASK
1496 if (startup_signal_mask_valid)
1498 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1499 log_error ("error restoring signal mask: %s\n",
1503 log_info ("no saved signal mask\n");
1504 #endif /*HAVE_SIGPROCMASK*/
1506 log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
1507 fd, fd_extra, fd_browser, fd_ssh);
1508 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1509 #endif /*!HAVE_W32_SYSTEM*/
1511 else if (!is_daemon)
1514 { /* Regular server mode */
1516 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1517 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1518 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1519 #ifndef HAVE_W32_SYSTEM
1523 /* Remove the DISPLAY variable so that a pinentry does not
1524 default to a specific display. There is still a default
1525 display when gpg-agent was started using --display or a
1526 client requested this using an OPTION command. Note, that we
1527 don't do this when running in reverse daemon mode (i.e. when
1528 exec the program given as arguments). */
1529 #ifndef HAVE_W32_SYSTEM
1530 if (!opt.keep_display && !argc)
1531 gnupg_unsetenv ("DISPLAY");
1534 /* Remove the INSIDE_EMACS variable so that a pinentry does not
1535 always try to interact with Emacs. The variable is set when
1536 a client requested this using an OPTION command. */
1537 gnupg_unsetenv ("INSIDE_EMACS");
1539 /* Create the sockets. */
1540 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1541 fd = create_server_socket (socket_name, 1, 0,
1542 &redir_socket_name, &socket_nonce);
1544 if (opt.extra_socket)
1546 if (socket_name_extra)
1547 socket_name_extra = create_socket_name (socket_name_extra, 0);
1549 socket_name_extra = create_socket_name
1550 /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1);
1551 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1552 fd_extra = create_server_socket (socket_name_extra, 0, 0,
1553 &redir_socket_name_extra,
1554 &socket_nonce_extra);
1557 if (opt.browser_socket)
1559 if (socket_name_browser)
1560 socket_name_browser = create_socket_name (socket_name_browser, 0);
1562 socket_name_browser= create_socket_name
1563 /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1);
1564 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1565 fd_browser = create_server_socket (socket_name_browser, 0, 0,
1566 &redir_socket_name_browser,
1567 &socket_nonce_browser);
1570 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1571 fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1572 &redir_socket_name_ssh,
1575 /* If we are going to exec a program in the parent, we record
1576 the PID, so that the child may check whether the program is
1579 parent_pid = getpid ();
1583 #ifdef HAVE_W32_SYSTEM
1587 initialize_modules ();
1589 #else /*!HAVE_W32_SYSTEM*/
1592 if (pid == (pid_t)-1)
1594 log_fatal ("fork failed: %s\n", strerror (errno) );
1598 { /* We are the parent */
1599 char *infostr_ssh_sock, *infostr_ssh_valid;
1601 /* Close the socket FD. */
1604 /* The signal mask might not be correct right now and thus
1605 we restore it. That is not strictly necessary but some
1606 programs falsely assume a cleared signal mask. */
1608 #ifdef HAVE_SIGPROCMASK
1609 if (startup_signal_mask_valid)
1611 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1612 log_error ("error restoring signal mask: %s\n",
1616 log_info ("no saved signal mask\n");
1617 #endif /*HAVE_SIGPROCMASK*/
1619 /* Create the SSH info string if enabled. */
1622 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1623 socket_name_ssh) < 0)
1625 log_error ("out of core\n");
1626 kill (pid, SIGTERM);
1629 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1630 (unsigned long)getpid()) < 0)
1632 log_error ("out of core\n");
1633 kill (pid, SIGTERM);
1638 *socket_name = 0; /* Don't let cleanup() remove the socket -
1639 the child should do this from now on */
1640 if (opt.extra_socket)
1641 *socket_name_extra = 0;
1642 if (opt.browser_socket)
1643 *socket_name_browser = 0;
1644 *socket_name_ssh = 0;
1647 { /* Run the program given on the commandline. */
1648 if (ssh_support && (putenv (infostr_ssh_sock)
1649 || putenv (infostr_ssh_valid)))
1651 log_error ("failed to set environment: %s\n",
1653 kill (pid, SIGTERM );
1657 /* Close all the file descriptors except the standard
1658 ones and those open at startup. We explicitly don't
1659 close 0,1,2 in case something went wrong collecting
1661 close_all_fds (3, startup_fd_list);
1663 /* Run the command. */
1664 execvp (argv[0], argv);
1665 log_error ("failed to run the command: %s\n", strerror (errno));
1666 kill (pid, SIGTERM);
1671 /* Print the environment string, so that the caller can use
1672 shell's eval to set it */
1677 *strchr (infostr_ssh_sock, '=') = ' ';
1678 es_printf ("setenv %s;\n", infostr_ssh_sock);
1685 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1691 xfree (infostr_ssh_sock);
1692 xfree (infostr_ssh_valid);
1703 initialize_modules ();
1705 /* Detach from tty and put process into a new session */
1709 unsigned int oldflags;
1711 /* Close stdin, stdout and stderr unless it is the log stream */
1712 for (i=0; i <= 2; i++)
1714 if (!log_test_fd (i) && i != fd )
1717 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1719 log_error ("failed to open '%s': %s\n",
1720 "/dev/null", strerror (errno));
1728 log_error ("setsid() failed: %s\n", strerror(errno) );
1733 log_get_prefix (&oldflags);
1734 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1735 opt.running_detached = 1;
1737 /* Unless we are running with a program given on the command
1738 * line we can assume that the inotify things works and thus
1739 * we can avoid tye regular stat calls. */
1741 reliable_homedir_inotify = 1;
1745 struct sigaction sa;
1747 sa.sa_handler = SIG_IGN;
1748 sigemptyset (&sa.sa_mask);
1750 sigaction (SIGPIPE, &sa, NULL);
1752 #endif /*!HAVE_W32_SYSTEM*/
1754 if (gnupg_chdir (gnupg_daemon_rootdir ()))
1756 log_error ("chdir to '%s' failed: %s\n",
1757 gnupg_daemon_rootdir (), strerror (errno));
1761 log_info ("%s %s started\n", strusage(11), strusage(13) );
1762 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1763 assuan_sock_close (fd);
1770 /* Exit entry point. This function should be called instead of a
1775 /*FIXME: update_random_seed_file();*/
1777 /* We run our cleanup handler because that may close cipher contexts
1778 stored in secure memory and thus this needs to be done before we
1779 explicitly terminate secure memory. */
1783 /* at this time a bit annoying */
1784 if (opt.debug & DBG_MEMSTAT_VALUE)
1786 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1787 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1790 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1792 gcry_control (GCRYCTL_TERM_SECMEM );
1793 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1798 /* This is our callback function for gcrypt progress messages. It is
1799 set once at startup and dispatches progress messages to the
1800 corresponding threads of the agent. */
1802 agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1803 int current, int total)
1805 struct progress_dispatch_s *dispatch;
1806 npth_t mytid = npth_self ();
1810 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1811 if (dispatch->ctrl && dispatch->tid == mytid)
1813 if (dispatch && dispatch->cb)
1814 dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1816 /* Libgcrypt < 1.8 does not know about nPth and thus when it reads
1817 * from /dev/random this will block the process. To mitigate this
1818 * problem we yield the thread when Libgcrypt tells us that it needs
1819 * more entropy. This way other threads have chance to run. */
1820 #if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */
1821 if (what && !strcmp (what, "need_entropy"))
1823 #if GPGRT_VERSION_NUMBER < 0x011900 /* 1.25 */
1824 /* In older gpg-error versions gpgrt_yield is buggy for use with
1825 * nPth and thus we need to resort to a sleep call. */
1826 npth_usleep (1000); /* 1ms */
1835 /* If a progress dispatcher callback has been associated with the
1836 * current connection unregister it. */
1838 unregister_progress_cb (void)
1840 struct progress_dispatch_s *dispatch;
1841 npth_t mytid = npth_self ();
1843 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1844 if (dispatch->ctrl && dispatch->tid == mytid)
1848 dispatch->ctrl = NULL;
1849 dispatch->cb = NULL;
1854 /* Setup a progress callback CB for the current connection. Using a
1855 * CB of NULL disables the callback. */
1857 agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1858 int printchar, int current, int total),
1861 struct progress_dispatch_s *dispatch, *firstfree;
1862 npth_t mytid = npth_self ();
1865 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1867 if (dispatch->ctrl && dispatch->tid == mytid)
1869 if (!dispatch->ctrl && !firstfree)
1870 firstfree = dispatch;
1872 if (!dispatch) /* None allocated: Reuse or allocate a new one. */
1876 dispatch = firstfree;
1878 else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1880 dispatch->next = progress_dispatch_list;
1881 progress_dispatch_list = dispatch;
1885 log_error ("error allocating new progress dispatcher slot: %s\n",
1886 gpg_strerror (gpg_error_from_syserror ()));
1889 dispatch->ctrl = ctrl;
1890 dispatch->tid = mytid;
1897 /* Each thread has its own local variables conveyed by a control
1898 structure usually identified by an argument named CTRL. This
1899 function is called immediately after allocating the control
1900 structure. Its purpose is to setup the default values for that
1901 structure. Note that some values may have already been set. */
1903 agent_init_default_ctrl (ctrl_t ctrl)
1905 assert (ctrl->session_env);
1907 /* Note we ignore malloc errors because we can't do much about it
1908 and the request will fail anyway shortly after this
1910 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1911 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1912 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1913 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1914 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1917 xfree (ctrl->lc_ctype);
1918 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1920 if (ctrl->lc_messages)
1921 xfree (ctrl->lc_messages);
1922 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1924 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1928 /* Release all resources allocated by default in the control
1929 structure. This is the counterpart to agent_init_default_ctrl. */
1931 agent_deinit_default_ctrl (ctrl_t ctrl)
1933 unregister_progress_cb ();
1934 session_env_release (ctrl->session_env);
1937 xfree (ctrl->lc_ctype);
1938 if (ctrl->lc_messages)
1939 xfree (ctrl->lc_messages);
1943 /* Because the ssh protocol does not send us information about the
1944 current TTY setting, we use this function to use those from startup
1945 or those explicitly set. This is also used for the restricted mode
1946 where we ignore requests to change the environment. */
1948 agent_copy_startup_env (ctrl_t ctrl)
1950 static const char *names[] =
1951 {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1952 gpg_error_t err = 0;
1956 for (idx=0; !err && names[idx]; idx++)
1957 if ((value = session_env_getenv (opt.startup_env, names[idx])))
1958 err = session_env_setenv (ctrl->session_env, names[idx], value);
1960 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1961 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1962 err = gpg_error_from_syserror ();
1964 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1965 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1966 err = gpg_error_from_syserror ();
1969 log_error ("error setting default session environment: %s\n",
1970 gpg_strerror (err));
1976 /* Reread parts of the configuration. Note, that this function is
1977 obviously not thread-safe and should only be called from the PTH
1980 Fixme: Due to the way the argument parsing works, we create a
1981 memory leak here for all string type arguments. There is currently
1982 no clean way to tell whether the memory for the argument has been
1983 allocated or points into the process' original arguments. Unless
1984 we have a mechanism to tell this, we need to live on with this. */
1986 reread_configuration (void)
1988 ARGPARSE_ARGS pargs;
1990 unsigned int configlineno = 0;
1993 if (!config_filename)
1994 return; /* No config file. */
1996 fp = fopen (config_filename, "r");
1999 log_info (_("option file '%s': %s\n"),
2000 config_filename, strerror(errno) );
2004 parse_rereadable_options (NULL, 1); /* Start from the default values. */
2006 memset (&pargs, 0, sizeof pargs);
2008 pargs.argc = &dummy;
2009 pargs.flags = 1; /* do not remove the args */
2010 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
2012 if (pargs.r_opt < -1)
2013 pargs.err = 1; /* Print a warning. */
2014 else /* Try to parse this option - ignore unchangeable ones. */
2015 parse_rereadable_options (&pargs, 1);
2018 finalize_rereadable_options ();
2023 /* Return the file name of the socket we are using for native
2026 get_agent_socket_name (void)
2028 const char *s = socket_name;
2030 return (s && *s)? s : NULL;
2033 /* Return the file name of the socket we are using for SSH
2036 get_agent_ssh_socket_name (void)
2038 const char *s = socket_name_ssh;
2040 return (s && *s)? s : NULL;
2044 /* Return the number of active connections. */
2046 get_agent_active_connection_count (void)
2048 return active_connections;
2052 /* Under W32, this function returns the handle of the scdaemon
2053 notification event. Calling it the first time creates that
2055 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
2057 get_agent_scd_notify_event (void)
2059 static HANDLE the_event = INVALID_HANDLE_VALUE;
2061 if (the_event == INVALID_HANDLE_VALUE)
2064 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
2066 /* We need to use a manual reset event object due to the way our
2067 w32-pth wait function works: If we would use an automatic
2068 reset event we are not able to figure out which handle has
2069 been signaled because at the time we single out the signaled
2070 handles using WFSO the event has already been reset due to
2072 h = CreateEvent (&sa, TRUE, FALSE, NULL);
2074 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
2075 else if (!DuplicateHandle (GetCurrentProcess(), h,
2076 GetCurrentProcess(), &h2,
2077 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
2079 log_error ("setting syncronize for scd notify event failed: %s\n",
2080 w32_strerror (-1) );
2092 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
2096 /* Create a name for the socket in the home directory as using
2097 STANDARD_NAME. We also check for valid characters as well as
2098 against a maximum allowed length for a unix domain socket is done.
2099 The function terminates the process in case of an error. Returns:
2100 Pointer to an allocated string with the absolute name of the socket
2103 create_socket_name (char *standard_name, int with_homedir)
2108 name = make_filename (gnupg_socketdir (), standard_name, NULL);
2110 name = make_filename (standard_name, NULL);
2111 if (strchr (name, PATHSEP_C))
2113 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
2121 /* Create a Unix domain socket with NAME. Returns the file descriptor
2122 or terminates the process in case of an error. Note that this
2123 function needs to be used for the regular socket first (indicated
2124 by PRIMARY) and only then for the extra and the ssh sockets. If
2125 the socket has been redirected the name of the real socket is
2126 stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
2127 Cygwin compatible socket is created (Windows only). */
2129 create_server_socket (char *name, int primary, int cygwin,
2130 char **r_redir_name, assuan_sock_nonce_t *nonce)
2132 struct sockaddr *addr;
2133 struct sockaddr_un *unaddr;
2138 xfree (*r_redir_name);
2139 *r_redir_name = NULL;
2141 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
2142 if (fd == ASSUAN_INVALID_FD)
2144 log_error (_("can't create socket: %s\n"), strerror (errno));
2145 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2150 assuan_sock_set_flag (fd, "cygwin", 1);
2152 unaddr = xmalloc (sizeof *unaddr);
2153 addr = (struct sockaddr*)unaddr;
2158 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
2160 if (errno == ENAMETOOLONG)
2161 log_error (_("socket name '%s' is too long\n"), name);
2163 log_error ("error preparing socket '%s': %s\n",
2164 name, gpg_strerror (gpg_error_from_syserror ()));
2165 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2171 *r_redir_name = xstrdup (unaddr->sun_path);
2173 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
2177 len = SUN_LEN (unaddr);
2178 rc = assuan_sock_bind (fd, addr, len);
2180 /* Our error code mapping on W32CE returns EEXIST thus we also test
2183 && (errno == EADDRINUSE
2184 #ifdef HAVE_W32_SYSTEM
2189 /* Check whether a gpg-agent is already running. We do this
2190 test only if this is the primary socket. For secondary
2191 sockets we assume that a test for gpg-agent has already been
2192 done and reuse the requested socket. Testing the ssh-socket
2193 is not possible because at this point, though we know the new
2194 Assuan socket, the Assuan server and thus the ssh-agent
2195 server is not yet operational; this would lead to a hang. */
2196 if (primary && !check_for_running_agent (1))
2198 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
2199 log_set_file (NULL);
2200 log_error (_("a gpg-agent is already running - "
2201 "not starting a new one\n"));
2202 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2203 assuan_sock_close (fd);
2207 gnupg_remove (unaddr->sun_path);
2208 rc = assuan_sock_bind (fd, addr, len);
2210 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
2211 log_error (_("error getting nonce for the socket\n"));
2214 /* We use gpg_strerror here because it allows us to get strings
2215 for some W32 socket error codes. */
2216 log_error (_("error binding socket to '%s': %s\n"),
2218 gpg_strerror (gpg_error_from_syserror ()));
2220 assuan_sock_close (fd);
2221 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2226 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
2227 log_error (_("can't set permissions of '%s': %s\n"),
2228 unaddr->sun_path, strerror (errno));
2230 if (listen (FD2INT(fd), 5 ) == -1)
2232 log_error (_("listen() failed: %s\n"), strerror (errno));
2233 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2234 assuan_sock_close (fd);
2240 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
2247 /* Check that the directory for storing the private keys exists and
2248 create it if not. This function won't fail as it is only a
2249 convenience function and not strictly necessary. */
2251 create_private_keys_directory (const char *home)
2254 struct stat statbuf;
2256 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
2257 if (stat (fname, &statbuf) && errno == ENOENT)
2259 if (gnupg_mkdir (fname, "-rwx"))
2260 log_error (_("can't create directory '%s': %s\n"),
2261 fname, strerror (errno) );
2262 else if (!opt.quiet)
2263 log_info (_("directory '%s' created\n"), fname);
2265 if (gnupg_chmod (fname, "-rwx"))
2266 log_error (_("can't set permissions of '%s': %s\n"),
2267 fname, strerror (errno));
2272 /* Create the directory only if the supplied directory name is the
2273 same as the default one. This way we avoid to create arbitrary
2274 directories when a non-default home directory is used. To cope
2275 with HOME, we compare only the suffix if we see that the default
2276 homedir does start with a tilde. We don't stop here in case of
2277 problems because other functions will throw an error anyway.*/
2279 create_directories (void)
2281 struct stat statbuf;
2282 const char *defhome = standard_homedir ();
2285 home = make_filename (gnupg_homedir (), NULL);
2286 if ( stat (home, &statbuf) )
2288 if (errno == ENOENT)
2291 #ifdef HAVE_W32_SYSTEM
2292 ( !compare_filenames (home, defhome) )
2295 && (strlen (home) >= strlen (defhome+1)
2296 && !strcmp (home + strlen(home)
2297 - strlen (defhome+1), defhome+1)))
2298 || (*defhome != '~' && !strcmp (home, defhome) )
2302 if (gnupg_mkdir (home, "-rwx"))
2303 log_error (_("can't create directory '%s': %s\n"),
2304 home, strerror (errno) );
2308 log_info (_("directory '%s' created\n"), home);
2309 create_private_keys_directory (home);
2314 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
2316 else if ( !S_ISDIR(statbuf.st_mode))
2318 log_error (_("can't use '%s' as home directory\n"), home);
2320 else /* exists and is a directory. */
2322 create_private_keys_directory (home);
2329 /* This is the worker for the ticker. It is called every few seconds
2330 and may only do fast operations. */
2334 static time_t last_minute;
2335 struct stat statbuf;
2338 last_minute = time (NULL);
2340 /* Check whether the scdaemon has died and cleanup in this case. */
2341 agent_scd_check_aliveness ();
2343 /* If we are running as a child of another process, check whether
2344 the parent is still alive and shutdown if not. */
2345 #ifndef HAVE_W32_SYSTEM
2346 if (parent_pid != (pid_t)(-1))
2348 if (kill (parent_pid, 0))
2350 shutdown_pending = 2;
2351 log_info ("parent process died - shutting down\n");
2352 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2357 #endif /*HAVE_W32_SYSTEM*/
2359 /* Code to be run from time to time. */
2360 #if CHECK_OWN_SOCKET_INTERVAL > 0
2361 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
2363 check_own_socket ();
2364 last_minute = time (NULL);
2368 /* Check whether the homedir is still available. */
2369 if (!shutdown_pending
2370 && (!have_homedir_inotify || !reliable_homedir_inotify)
2371 && stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2373 shutdown_pending = 1;
2374 log_info ("homedir has been removed - shutting down\n");
2379 /* A global function which allows us to call the reload stuff from
2380 other places too. This is only used when build for W32. */
2382 agent_sighup_action (void)
2384 log_info ("SIGHUP received - "
2385 "re-reading configuration and flushing cache\n");
2387 agent_flush_cache ();
2388 reread_configuration ();
2389 agent_reload_trustlist ();
2390 /* We flush the module name cache so that after installing a
2391 "pinentry" binary that one can be used in case the
2392 "pinentry-basic" fallback was in use. */
2393 gnupg_module_name_flush_some ();
2397 /* A helper function to handle SIGUSR2. */
2399 agent_sigusr2_action (void)
2402 log_info ("SIGUSR2 received - updating card event counter\n");
2403 /* Nothing to check right now. We only increment a counter. */
2404 bump_card_eventcounter ();
2408 #ifndef HAVE_W32_SYSTEM
2409 /* The signal handler for this program. It is expected to be run in
2410 its own trhead and not in the context of a signal handler. */
2412 handle_signal (int signo)
2416 #ifndef HAVE_W32_SYSTEM
2418 agent_sighup_action ();
2422 log_info ("SIGUSR1 received - printing internal information:\n");
2423 /* Fixme: We need to see how to integrate pth dumping into our
2425 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2426 agent_query_dump_state ();
2427 agent_scd_dump_state ();
2431 agent_sigusr2_action ();
2435 if (!shutdown_pending)
2436 log_info ("SIGTERM received - shutting down ...\n");
2438 log_info ("SIGTERM received - still %i open connections\n",
2439 active_connections);
2441 if (shutdown_pending > 2)
2443 log_info ("shutdown forced\n");
2444 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2451 log_info ("SIGINT received - immediate shutdown\n");
2452 log_info( "%s %s stopped\n", strusage(11), strusage(13));
2458 log_info ("signal %d received - no action defined\n", signo);
2463 /* Check the nonce on a new connection. This is a NOP unless we
2464 are using our Unix domain socket emulation under Windows. */
2466 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2468 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2470 log_info (_("error reading nonce on fd %d: %s\n"),
2471 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2472 assuan_sock_close (ctrl->thread_startup.fd);
2481 #ifdef HAVE_W32_SYSTEM
2482 /* The window message processing function for Putty. Warning: This
2483 code runs as a native Windows thread. Use of our own functions
2484 needs to be bracket with pth_leave/pth_enter. */
2485 static LRESULT CALLBACK
2486 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2490 COPYDATASTRUCT *cds;
2491 const char *mapfile;
2496 PSECURITY_DESCRIPTOR psd = NULL;
2499 if (msg != WM_COPYDATA)
2501 return DefWindowProc (hwnd, msg, wparam, lparam);
2504 cds = (COPYDATASTRUCT*)lparam;
2505 if (cds->dwData != PUTTY_IPC_MAGIC)
2506 return 0; /* Ignore data with the wrong magic. */
2507 mapfile = cds->lpData;
2508 if (!cds->cbData || mapfile[cds->cbData - 1])
2509 return 0; /* Ignore empty and non-properly terminated strings. */
2514 log_debug ("ssh map file '%s'", mapfile);
2518 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2522 log_debug ("ssh map handle %p\n", maphd);
2526 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2531 mysid = w32_get_user_sid ();
2534 log_error ("error getting my sid\n");
2538 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2539 OWNER_SECURITY_INFORMATION,
2540 &mapsid, NULL, NULL, NULL,
2544 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2552 if (!ConvertSidToStringSid (mysid, &sidstr))
2554 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2556 if (!ConvertSidToStringSid (mapsid, &sidstr))
2558 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2562 if (!EqualSid (mysid, mapsid))
2564 log_error ("ssh map file has a non-matching sid\n");
2568 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2570 log_debug ("ssh IPC buffer at %p\n", data);
2574 /* log_printhex ("request:", data, 20); */
2576 ctrl = xtrycalloc (1, sizeof *ctrl);
2579 log_error ("error allocating connection control data: %s\n",
2583 ctrl->session_env = session_env_new ();
2584 if (!ctrl->session_env)
2586 log_error ("error allocating session environment block: %s\n",
2591 agent_init_default_ctrl (ctrl);
2592 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2593 ret = 1; /* Valid ssh message has been constructed. */
2594 agent_deinit_default_ctrl (ctrl);
2595 /* log_printhex (" reply:", data, 20); */
2600 UnmapViewOfFile (data);
2605 CloseHandle (maphd);
2611 #endif /*HAVE_W32_SYSTEM*/
2614 #ifdef HAVE_W32_SYSTEM
2615 /* The thread handling Putty's IPC requests. */
2617 putty_message_thread (void *arg)
2619 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2620 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2627 log_info ("putty message loop thread started\n");
2629 /* The message loop runs as thread independent from our nPth system.
2630 This also means that we need to make sure that we switch back to
2631 our system before calling any no-windows function. */
2634 /* First create a window to make sure that a message queue exists
2636 if (!RegisterClass (&wndwclass))
2639 log_error ("error registering Pageant window class");
2642 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2644 HWND_MESSAGE, /* hWndParent */
2645 NULL, /* hWndMenu */
2646 NULL, /* hInstance */
2651 log_error ("error creating Pageant window");
2655 while (GetMessage(&msg, NULL, 0, 0))
2657 TranslateMessage(&msg);
2658 DispatchMessage(&msg);
2665 log_info ("putty message loop thread stopped\n");
2668 #endif /*HAVE_W32_SYSTEM*/
2672 do_start_connection_thread (ctrl_t ctrl)
2674 active_connections++;
2675 agent_init_default_ctrl (ctrl);
2676 if (opt.verbose && !DBG_IPC)
2677 log_info (_("handler 0x%lx for fd %d started\n"),
2678 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2680 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2681 if (opt.verbose && !DBG_IPC)
2682 log_info (_("handler 0x%lx for fd %d terminated\n"),
2683 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2685 agent_deinit_default_ctrl (ctrl);
2687 active_connections--;
2692 /* This is the standard connection thread's main function. */
2694 start_connection_thread_std (void *arg)
2698 if (check_nonce (ctrl, &socket_nonce))
2700 log_error ("handler 0x%lx nonce check FAILED\n",
2701 (unsigned long) npth_self());
2705 return do_start_connection_thread (ctrl);
2709 /* This is the extra socket connection thread's main function. */
2711 start_connection_thread_extra (void *arg)
2715 if (check_nonce (ctrl, &socket_nonce_extra))
2717 log_error ("handler 0x%lx nonce check FAILED\n",
2718 (unsigned long) npth_self());
2722 ctrl->restricted = 1;
2723 return do_start_connection_thread (ctrl);
2727 /* This is the browser socket connection thread's main function. */
2729 start_connection_thread_browser (void *arg)
2733 if (check_nonce (ctrl, &socket_nonce_browser))
2735 log_error ("handler 0x%lx nonce check FAILED\n",
2736 (unsigned long) npth_self());
2740 ctrl->restricted = 2;
2741 return do_start_connection_thread (ctrl);
2745 /* This is the ssh connection thread's main function. */
2747 start_connection_thread_ssh (void *arg)
2751 if (check_nonce (ctrl, &socket_nonce_ssh))
2754 active_connections++;
2755 agent_init_default_ctrl (ctrl);
2757 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2758 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2760 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2762 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2763 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2765 agent_deinit_default_ctrl (ctrl);
2767 active_connections--;
2772 /* Connection handler loop. Wait for connection requests and spawn a
2773 thread after accepting a connection. */
2775 handle_connections (gnupg_fd_t listen_fd,
2776 gnupg_fd_t listen_fd_extra,
2777 gnupg_fd_t listen_fd_browser,
2778 gnupg_fd_t listen_fd_ssh)
2782 struct sockaddr_un paddr;
2784 fd_set fdset, read_fdset;
2789 struct timespec abstime;
2790 struct timespec curtime;
2791 struct timespec timeout;
2792 #ifdef HAVE_W32_SYSTEM
2794 unsigned int events_set;
2796 int sock_inotify_fd = -1;
2797 int home_inotify_fd = -1;
2800 void *(*func) (void *arg);
2803 { "std", start_connection_thread_std },
2804 { "extra", start_connection_thread_extra },
2805 { "browser", start_connection_thread_browser },
2806 { "ssh", start_connection_thread_ssh }
2810 ret = npth_attr_init(&tattr);
2812 log_fatal ("error allocating thread attributes: %s\n",
2814 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2816 #ifndef HAVE_W32_SYSTEM
2818 npth_sigev_add (SIGHUP);
2819 npth_sigev_add (SIGUSR1);
2820 npth_sigev_add (SIGUSR2);
2821 npth_sigev_add (SIGINT);
2822 npth_sigev_add (SIGTERM);
2825 # ifdef HAVE_W32CE_SYSTEM
2826 /* Use a dummy event. */
2828 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2830 events[0] = get_agent_scd_notify_event ();
2831 events[1] = INVALID_HANDLE_VALUE;
2835 if (disable_check_own_socket)
2836 sock_inotify_fd = -1;
2837 else if ((err = gnupg_inotify_watch_socket (&sock_inotify_fd, socket_name)))
2839 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2840 log_info ("error enabling daemon termination by socket removal: %s\n",
2841 gpg_strerror (err));
2844 if (disable_check_own_socket)
2845 home_inotify_fd = -1;
2846 else if ((err = gnupg_inotify_watch_delete_self (&home_inotify_fd,
2849 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2850 log_info ("error enabling daemon termination by homedir removal: %s\n",
2851 gpg_strerror (err));
2854 have_homedir_inotify = 1;
2856 /* On Windows we need to fire up a separate thread to listen for
2857 requests from Putty (an SSH client), so we can replace Putty's
2858 Pageant (its ssh-agent implementation). */
2859 #ifdef HAVE_W32_SYSTEM
2864 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2867 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2870 #endif /*HAVE_W32_SYSTEM*/
2872 /* Set a flag to tell call-scd.c that it may enable event
2874 opt.sigusr2_enabled = 1;
2877 FD_SET (FD2INT (listen_fd), &fdset);
2878 nfd = FD2INT (listen_fd);
2879 if (listen_fd_extra != GNUPG_INVALID_FD)
2881 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2882 if (FD2INT (listen_fd_extra) > nfd)
2883 nfd = FD2INT (listen_fd_extra);
2885 if (listen_fd_browser != GNUPG_INVALID_FD)
2887 FD_SET ( FD2INT(listen_fd_browser), &fdset);
2888 if (FD2INT (listen_fd_browser) > nfd)
2889 nfd = FD2INT (listen_fd_browser);
2891 if (listen_fd_ssh != GNUPG_INVALID_FD)
2893 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2894 if (FD2INT (listen_fd_ssh) > nfd)
2895 nfd = FD2INT (listen_fd_ssh);
2897 if (sock_inotify_fd != -1)
2899 FD_SET (sock_inotify_fd, &fdset);
2900 if (sock_inotify_fd > nfd)
2901 nfd = sock_inotify_fd;
2903 if (home_inotify_fd != -1)
2905 FD_SET (home_inotify_fd, &fdset);
2906 if (home_inotify_fd > nfd)
2907 nfd = home_inotify_fd;
2910 listentbl[0].l_fd = listen_fd;
2911 listentbl[1].l_fd = listen_fd_extra;
2912 listentbl[2].l_fd = listen_fd_browser;
2913 listentbl[3].l_fd = listen_fd_ssh;
2915 npth_clock_gettime (&abstime);
2916 abstime.tv_sec += TIMERTICK_INTERVAL;
2920 /* Shutdown test. */
2921 if (shutdown_pending)
2923 if (active_connections == 0)
2926 /* Do not accept new connections but keep on running the
2927 * loop to cope with the timer events.
2929 * Note that we do not close the listening socket because a
2930 * client trying to connect to that socket would instead
2931 * restart a new dirmngr instance - which is unlikely the
2932 * intention of a shutdown. */
2935 if (sock_inotify_fd != -1)
2937 FD_SET (sock_inotify_fd, &fdset);
2938 nfd = sock_inotify_fd;
2940 if (home_inotify_fd != -1)
2942 FD_SET (home_inotify_fd, &fdset);
2943 if (home_inotify_fd > nfd)
2944 nfd = home_inotify_fd;
2948 /* POSIX says that fd_set should be implemented as a structure,
2949 thus a simple assignment is fine to copy the entire set. */
2952 npth_clock_gettime (&curtime);
2953 if (!(npth_timercmp (&curtime, &abstime, <)))
2957 npth_clock_gettime (&abstime);
2958 abstime.tv_sec += TIMERTICK_INTERVAL;
2960 npth_timersub (&abstime, &curtime, &timeout);
2962 #ifndef HAVE_W32_SYSTEM
2963 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2964 npth_sigev_sigmask ());
2965 saved_errno = errno;
2969 while (npth_sigev_get_pending (&signo))
2970 handle_signal (signo);
2973 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2974 events, &events_set);
2975 saved_errno = errno;
2977 /* This is valid even if npth_eselect returns an error. */
2979 agent_sigusr2_action ();
2982 if (ret == -1 && saved_errno != EINTR)
2984 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2985 strerror (saved_errno));
2990 /* Interrupt or timeout. Will be handled when calculating the
2994 if (!shutdown_pending)
3000 if (sock_inotify_fd != -1
3001 && FD_ISSET (sock_inotify_fd, &read_fdset)
3002 && gnupg_inotify_has_name (sock_inotify_fd, GPG_AGENT_SOCK_NAME))
3004 shutdown_pending = 1;
3005 log_info ("socket file has been removed - shutting down\n");
3008 if (home_inotify_fd != -1
3009 && FD_ISSET (home_inotify_fd, &read_fdset))
3011 shutdown_pending = 1;
3012 log_info ("homedir has been removed - shutting down\n");
3015 for (idx=0; idx < DIM(listentbl); idx++)
3017 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
3019 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
3022 plen = sizeof paddr;
3023 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
3024 (struct sockaddr *)&paddr, &plen));
3025 if (fd == GNUPG_INVALID_FD)
3027 log_error ("accept failed for %s: %s\n",
3028 listentbl[idx].name, strerror (errno));
3030 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
3032 log_error ("error allocating connection data for %s: %s\n",
3033 listentbl[idx].name, strerror (errno) );
3034 assuan_sock_close (fd);
3036 else if ( !(ctrl->session_env = session_env_new ()))
3038 log_error ("error allocating session env block for %s: %s\n",
3039 listentbl[idx].name, strerror (errno) );
3041 assuan_sock_close (fd);
3045 ctrl->thread_startup.fd = fd;
3046 ret = npth_create (&thread, &tattr,
3047 listentbl[idx].func, ctrl);
3050 log_error ("error spawning connection handler for %s:"
3051 " %s\n", listentbl[idx].name, strerror (ret));
3052 assuan_sock_close (fd);
3060 if (sock_inotify_fd != -1)
3061 close (sock_inotify_fd);
3062 if (home_inotify_fd != -1)
3063 close (home_inotify_fd);
3065 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
3066 npth_attr_destroy (&tattr);
3071 /* Helper for check_own_socket. */
3073 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
3075 membuf_t *mb = opaque;
3076 put_membuf (mb, buffer, length);
3081 /* The thread running the actual check. We need to run this in a
3082 separate thread so that check_own_thread can be called from the
3085 check_own_socket_thread (void *arg)
3088 char *sockname = arg;
3089 assuan_context_t ctx = NULL;
3093 check_own_socket_running++;
3095 rc = assuan_new (&ctx);
3098 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
3101 assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
3103 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3106 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
3110 init_membuf (&mb, 100);
3111 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
3112 NULL, NULL, NULL, NULL);
3113 put_membuf (&mb, "", 1);
3114 buffer = get_membuf (&mb, NULL);
3117 log_error ("sending command \"%s\" to my own socket failed: %s\n",
3118 "GETINFO pid", gpg_strerror (rc));
3121 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
3123 log_error ("socket is now serviced by another server\n");
3126 else if (opt.verbose > 1)
3127 log_error ("socket is still served by this server\n");
3134 assuan_release (ctx);
3137 /* We may not remove the socket as it is now in use by another
3139 inhibit_socket_removal = 1;
3140 shutdown_pending = 2;
3141 log_info ("this process is useless - shutting down\n");
3143 check_own_socket_running--;
3148 /* Check whether we are still listening on our own socket. In case
3149 another gpg-agent process started after us has taken ownership of
3150 our socket, we would linger around without any real task. Thus we
3151 better check once in a while whether we are really needed. */
3153 check_own_socket (void)
3160 if (disable_check_own_socket)
3163 if (check_own_socket_running || shutdown_pending)
3164 return; /* Still running or already shutting down. */
3166 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3168 return; /* Out of memory. */
3170 err = npth_attr_init (&tattr);
3173 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3174 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
3176 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
3177 npth_attr_destroy (&tattr);
3182 /* Figure out whether an agent is available and running. Prints an
3183 error if not. If SILENT is true, no messages are printed.
3184 Returns 0 if the agent is running. */
3186 check_for_running_agent (int silent)
3190 assuan_context_t ctx = NULL;
3192 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3194 return gpg_error_from_syserror ();
3196 err = assuan_new (&ctx);
3198 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3203 log_error (_("no gpg-agent running in this session\n"));
3206 assuan_release (ctx);
3210 if (!opt.quiet && !silent)
3211 log_info ("gpg-agent running and available\n");
3213 assuan_release (ctx);