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 # include <sys/prctl.h>
55 #define GNUPG_COMMON_NEED_AFLOCAL
57 #include <assuan.h> /* Malloc hooks and socket wrappers. */
61 #include "gc-opt-flags.h"
64 #include "../common/init.h"
67 enum cmd_and_opt_values
98 oPinentryInvisibleChar,
111 oEnforcePassphraseConstraints,
113 oMinPassphraseNonalpha,
114 oCheckPassphrasePattern,
116 oEnablePassphraseHistory,
118 oNoUseStandardSocket,
123 oIgnoreCacheForSigning,
126 oAllowPresetPassphrase,
127 oAllowLoopbackPinentry,
128 oNoAllowLoopbackPinentry,
129 oNoAllowExternalCache,
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 (oNoGrab, "no-grab", N_("do not grab keyboard and mouse")),
174 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
175 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
176 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
177 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
178 ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
179 ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
180 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
181 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
182 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
183 /* */ N_("do not use the SCdaemon") ),
184 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
186 ARGPARSE_s_s (oExtraSocket, "extra-socket",
187 /* */ N_("|NAME|accept some commands via NAME")),
189 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
191 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
193 ARGPARSE_s_n (oBatch, "batch", "@"),
194 ARGPARSE_s_s (oHomedir, "homedir", "@"),
196 ARGPARSE_s_s (oDisplay, "display", "@"),
197 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
198 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
199 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
200 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
201 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
202 ARGPARSE_s_n (oKeepTTY, "keep-tty",
203 /* */ N_("ignore requests to change the TTY")),
204 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
205 /* */ N_("ignore requests to change the X display")),
207 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
208 N_("|N|expire cached PINs after N seconds")),
209 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
210 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
211 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
213 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
215 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
216 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
217 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
218 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
219 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
221 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
222 /* */ N_("do not use the PIN cache when signing")),
223 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
224 /* */ N_("disallow the use of an external password cache")),
225 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
226 /* */ N_("disallow clients to mark keys as \"trusted\"")),
227 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
228 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
229 /* */ N_("allow presetting passphrase")),
230 ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
231 N_("disallow caller to override the pinentry")),
232 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
233 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
234 /* */ N_("allow passphrase to be prompted through Emacs")),
236 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
237 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
238 #ifdef HAVE_W32_SYSTEM
239 /* */ N_("enable putty support")
245 /* Dummy options for backward compatibility. */
246 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
247 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
248 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
250 {0} /* End of list */
254 /* The list of supported debug flags. */
255 static struct debug_flags_s debug_flags [] =
257 { DBG_MPI_VALUE , "mpi" },
258 { DBG_CRYPTO_VALUE , "crypto" },
259 { DBG_MEMORY_VALUE , "memory" },
260 { DBG_CACHE_VALUE , "cache" },
261 { DBG_MEMSTAT_VALUE, "memstat" },
262 { DBG_HASHING_VALUE, "hashing" },
263 { DBG_IPC_VALUE , "ipc" },
264 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
269 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
270 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
271 #define MAX_CACHE_TTL (120*60) /* 2 hours */
272 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
273 #define MIN_PASSPHRASE_LEN (8)
274 #define MIN_PASSPHRASE_NONALPHA (1)
275 #define MAX_PASSPHRASE_DAYS (0)
277 /* The timer tick used for housekeeping stuff. For Windows we use a
278 longer period as the SetWaitableTimer seems to signal earlier than
279 the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
280 check our own socket in standard socket mode. If that value is 0
281 we don't check at all. All values are in seconds. */
282 #if defined(HAVE_W32CE_SYSTEM)
283 # define TIMERTICK_INTERVAL (60)
284 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
285 #elif defined(HAVE_W32_SYSTEM)
286 # define TIMERTICK_INTERVAL (4)
287 # define CHECK_OWN_SOCKET_INTERVAL (60)
289 # define TIMERTICK_INTERVAL (2)
290 # define CHECK_OWN_SOCKET_INTERVAL (60)
294 /* Flag indicating that the ssh-agent subsystem has been enabled. */
295 static int ssh_support;
297 #ifdef HAVE_W32_SYSTEM
298 /* Flag indicating that support for Putty has been enabled. */
299 static int putty_support;
300 /* A magic value used with WM_COPYDATA. */
301 #define PUTTY_IPC_MAGIC 0x804e50ba
302 /* To avoid surprises we limit the size of the mapped IPC file to this
303 value. Putty currently (0.62) uses 8k, thus 16k should be enough
304 for the foreseeable future. */
305 #define PUTTY_IPC_MAXLEN 16384
306 #endif /*HAVE_W32_SYSTEM*/
308 /* The list of open file descriptors at startup. Note that this list
309 * has been allocated using the standard malloc. */
310 #ifndef HAVE_W32_SYSTEM
311 static int *startup_fd_list;
314 /* The signal mask at startup and a flag telling whether it is valid. */
315 #ifdef HAVE_SIGPROCMASK
316 static sigset_t startup_signal_mask;
317 static int startup_signal_mask_valid;
320 /* Flag to indicate that a shutdown was requested. */
321 static int shutdown_pending;
323 /* Counter for the currently running own socket checks. */
324 static int check_own_socket_running;
326 /* Flags to indicate that check_own_socket shall not be called. */
327 static int disable_check_own_socket;
329 /* Flag indicating that we are in supervised mode. */
330 static int is_supervised;
332 /* Flag to inhibit socket removal in cleanup. */
333 static int inhibit_socket_removal;
335 /* It is possible that we are currently running under setuid permissions */
336 static int maybe_setuid = 1;
338 /* Name of the communication socket used for native gpg-agent
339 requests. The second variable is either NULL or a malloced string
340 with the real socket name in case it has been redirected. */
341 static char *socket_name;
342 static char *redir_socket_name;
344 /* Name of the optional extra socket used for native gpg-agent requests. */
345 static char *socket_name_extra;
346 static char *redir_socket_name_extra;
348 /* Name of the optional browser socket used for native gpg-agent requests. */
349 static char *socket_name_browser;
350 static char *redir_socket_name_browser;
352 /* Name of the communication socket used for ssh-agent protocol. */
353 static char *socket_name_ssh;
354 static char *redir_socket_name_ssh;
356 /* We need to keep track of the server's nonces (these are dummies for
358 static assuan_sock_nonce_t socket_nonce;
359 static assuan_sock_nonce_t socket_nonce_extra;
360 static assuan_sock_nonce_t socket_nonce_browser;
361 static assuan_sock_nonce_t socket_nonce_ssh;
364 /* Default values for options passed to the pinentry. */
365 static char *default_display;
366 static char *default_ttyname;
367 static char *default_ttytype;
368 static char *default_lc_ctype;
369 static char *default_lc_messages;
370 static char *default_xauthority;
372 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
373 static char *config_filename;
375 /* Helper to implement --debug-level */
376 static const char *debug_level;
378 /* Keep track of the current log file so that we can avoid updating
379 the log file after a SIGHUP if it didn't changed. Malloced. */
380 static char *current_logfile;
382 /* The handle_tick() function may test whether a parent is still
383 running. We record the PID of the parent here or -1 if it should be
385 static pid_t parent_pid = (pid_t)(-1);
387 /* Number of active connections. */
388 static int active_connections;
390 /* This object is used to dispatch progress messages from Libgcrypt to
391 * the right thread. Given that we will have at max only a few dozen
392 * connections at a time, using a linked list is the easiest way to
394 struct progress_dispatch_s
396 struct progress_dispatch_s *next;
397 /* The control object of the connection. If this is NULL no
398 * connection is associated with this item and it is free for reuse
399 * by new connections. */
402 /* The thread id of (npth_self) of the connection. */
405 /* The callback set by the connection. This is similar to the
406 * Libgcrypt callback but with the control object passed as the
408 void (*cb)(ctrl_t ctrl,
409 const char *what, int printchar,
410 int current, int total);
412 struct progress_dispatch_s *progress_dispatch_list;
421 static char *create_socket_name (char *standard_name, int with_homedir);
422 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
424 assuan_sock_nonce_t *nonce);
425 static void create_directories (void);
427 static void agent_libgcrypt_progress_cb (void *data, const char *what,
429 int current, int total);
430 static void agent_init_default_ctrl (ctrl_t ctrl);
431 static void agent_deinit_default_ctrl (ctrl_t ctrl);
433 static void handle_connections (gnupg_fd_t listen_fd,
434 gnupg_fd_t listen_fd_extra,
435 gnupg_fd_t listen_fd_browser,
436 gnupg_fd_t listen_fd_ssh);
437 static void check_own_socket (void);
438 static int check_for_running_agent (int silent);
440 /* Pth wrapper function definitions. */
441 ASSUAN_SYSTEM_NPTH_IMPL;
448 /* Allocate a string describing a library version by calling a GETFNC.
449 This function is expected to be called only once. GETFNC is
450 expected to have a semantic like gcry_check_version (). */
452 make_libversion (const char *libname, const char *(*getfnc)(const char*))
459 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
463 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
464 strcpy (stpcpy (stpcpy (result, libname), " "), s);
468 /* Return strings describing this program. The case values are
469 described in common/argparse.c:strusage. The values here override
470 the default values given by strusage. */
472 my_strusage (int level)
474 static char *ver_gcry;
479 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
481 case 13: p = VERSION; break;
482 case 17: p = PRINTABLE_OS_NAME; break;
483 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
484 reporting address. This is so that we can change the
485 reporting address without breaking the translations. */
486 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
490 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
495 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
497 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
498 "Secret key management for @GNUPG@\n");
508 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
509 only the active debug flags are propagated to the subsystems. With
510 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
511 all flags already set. Note that we don't fail here, because it is
512 important to keep gpg-agent running even after re-reading the
513 options due to a SIGHUP. */
517 int numok = (debug_level && digitp (debug_level));
518 int numlvl = numok? atoi (debug_level) : 0;
522 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
524 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
525 opt.debug = DBG_IPC_VALUE;
526 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
527 opt.debug = DBG_IPC_VALUE;
528 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
529 opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE);
530 else if (!strcmp (debug_level, "guru") || numok)
533 /* Unless the "guru" string has been used we don't want to allow
534 hashing debugging. The rationale is that people tend to
535 select the highest debug value and would then clutter their
536 disk with debug files which may reveal confidential data. */
538 opt.debug &= ~(DBG_HASHING_VALUE);
542 log_error (_("invalid debug-level '%s' given\n"), debug_level);
543 opt.debug = 0; /* Reset debugging, so that prior debug
544 statements won't have an undesired effect. */
547 if (opt.debug && !opt.verbose)
549 if (opt.debug && opt.quiet)
552 if (opt.debug & DBG_MPI_VALUE)
553 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
554 if (opt.debug & DBG_CRYPTO_VALUE )
555 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
556 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
559 parse_debug_flag (NULL, &opt.debug, debug_flags);
563 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
564 the corresponding real name if the socket has been redirected. */
566 remove_socket (char *name, char *redir_name)
579 /* Discover which inherited file descriptors correspond to which
580 * services/sockets offered by gpg-agent, using the LISTEN_FDS and
581 * LISTEN_FDNAMES convention. The understood labels are "ssh",
582 * "extra", and "browser". "std" or other labels will be interpreted
583 * as the standard socket.
585 * This function is designed to log errors when the expected file
586 * descriptors don't make sense, but to do its best to continue to
587 * work even in the face of minor misconfigurations.
589 * For more information on the LISTEN_FDS convention, see
590 * sd_listen_fds(3) on certain Linux distributions.
592 #ifndef HAVE_W32_SYSTEM
594 map_supervised_sockets (gnupg_fd_t *r_fd,
595 gnupg_fd_t *r_fd_extra,
596 gnupg_fd_t *r_fd_browser,
597 gnupg_fd_t *r_fd_ssh)
604 { "ssh", &r_fd_ssh, &socket_name_ssh },
605 { "browser", &r_fd_browser, &socket_name_browser },
606 { "extra", &r_fd_extra, &socket_name_extra },
607 { "std", &r_fd, &socket_name } /* (Must be the last item.) */
614 *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
616 /* Print a warning if LISTEN_PID does not match outr pid. */
617 envvar = getenv ("LISTEN_PID");
619 log_error ("no LISTEN_PID environment variable found in "
620 "--supervised mode (ignoring)\n");
621 else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
622 log_error ("environment variable LISTEN_PID (%lu) does not match"
623 " our pid (%lu) in --supervised mode (ignoring)\n",
624 (unsigned long)strtoul (envvar, NULL, 10),
625 (unsigned long)getpid ());
627 /* Parse LISTEN_FDNAMES into the array FDNAMES. */
628 envvar = getenv ("LISTEN_FDNAMES");
631 fdnames = strtokenize (envvar, ":");
634 log_error ("strtokenize failed: %s\n",
635 gpg_strerror (gpg_error_from_syserror ()));
638 for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
647 /* Parse LISTEN_FDS into fd_count or provide a replacement. */
648 envvar = getenv ("LISTEN_FDS");
650 fd_count = atoi (envvar);
653 log_error ("no LISTEN_FDS environment variable found in --supervised"
654 " mode (relying on LISTEN_FDNAMES instead)\n");
659 log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
660 "found in --supervised mode"
661 " (assuming 1 active descriptor)\n");
667 log_error ("--supervised mode expects at least one file descriptor"
668 " (was told %d, carrying on as though it were 1)\n",
673 /* Assign the descriptors to the return values. */
679 log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
680 " in --supervised mode."
681 " (ignoring all sockets but the first one)\n",
683 if (fstat (3, &statbuf) == -1 && errno ==EBADF)
684 log_fatal ("file descriptor 3 must be valid in --supervised mode"
685 " if LISTEN_FDNAMES is not set\n");
687 socket_name = gnupg_get_socket_name (3);
689 else if (fd_count != nfdnames)
691 log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
692 "LISTEN_FDS (%d) in --supervised mode\n",
700 for (i = 0; i < nfdnames; i++)
702 for (j = 0; j < DIM (tbl); j++)
704 if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
707 if (**tbl[j].fdaddr == -1)
709 name = gnupg_get_socket_name (fd);
712 **tbl[j].fdaddr = fd;
713 *tbl[j].nameaddr = name;
714 log_info ("using fd %d for %s socket (%s)\n",
715 fd, tbl[j].label, name);
719 log_error ("cannot listen on fd %d for %s socket\n",
726 log_error ("cannot listen on more than one %s socket\n",
738 #endif /*!HAVE_W32_SYSTEM*/
741 /* Cleanup code for this program. This is either called has an atexit
742 handler or directly. */
751 deinitialize_module_cache ();
752 if (!is_supervised && !inhibit_socket_removal)
754 remove_socket (socket_name, redir_socket_name);
755 if (opt.extra_socket > 1)
756 remove_socket (socket_name_extra, redir_socket_name_extra);
757 if (opt.browser_socket > 1)
758 remove_socket (socket_name_browser, redir_socket_name_browser);
759 remove_socket (socket_name_ssh, redir_socket_name_ssh);
765 /* Handle options which are allowed to be reset after program start.
766 Return true when the current option in PARGS could be handled and
767 false if not. As a special feature, passing a value of NULL for
768 PARGS, resets the options to the default. REREAD should be set
769 true if it is not the initial option parsing. */
771 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
779 opt.debug_pinentry = 0;
780 opt.pinentry_program = NULL;
781 opt.pinentry_touch_file = NULL;
782 xfree (opt.pinentry_invisible_char);
783 opt.pinentry_invisible_char = NULL;
784 opt.pinentry_timeout = 0;
785 opt.scdaemon_program = NULL;
786 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
787 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
788 opt.max_cache_ttl = MAX_CACHE_TTL;
789 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
790 opt.enforce_passphrase_constraints = 0;
791 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
792 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
793 opt.check_passphrase_pattern = NULL;
794 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
795 opt.enable_passphrase_history = 0;
796 opt.ignore_cache_for_signing = 0;
797 opt.allow_mark_trusted = 1;
798 opt.allow_external_cache = 1;
799 opt.allow_loopback_pinentry = 1;
800 opt.allow_emacs_pinentry = 0;
801 opt.disable_scdaemon = 0;
802 disable_check_own_socket = 0;
806 switch (pargs->r_opt)
808 case oQuiet: opt.quiet = 1; break;
809 case oVerbose: opt.verbose++; break;
812 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
814 case oDebugAll: opt.debug = ~0; break;
815 case oDebugLevel: debug_level = pargs->r.ret_str; break;
816 case oDebugPinentry: opt.debug_pinentry = 1; break;
820 return 0; /* not handeld */
821 if (!current_logfile || !pargs->r.ret_str
822 || strcmp (current_logfile, pargs->r.ret_str))
824 log_set_file (pargs->r.ret_str);
825 xfree (current_logfile);
826 current_logfile = xtrystrdup (pargs->r.ret_str);
830 case oNoGrab: opt.no_grab = 1; break;
832 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
833 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
834 case oPinentryInvisibleChar:
835 xfree (opt.pinentry_invisible_char);
836 opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
838 case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
839 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
840 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
841 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
843 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
844 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
845 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
846 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
848 case oEnforcePassphraseConstraints:
849 opt.enforce_passphrase_constraints=1;
851 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
852 case oMinPassphraseNonalpha:
853 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
855 case oCheckPassphrasePattern:
856 opt.check_passphrase_pattern = pargs->r.ret_str;
858 case oMaxPassphraseDays:
859 opt.max_passphrase_days = pargs->r.ret_ulong;
861 case oEnablePassphraseHistory:
862 opt.enable_passphrase_history = 1;
865 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
867 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
868 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
870 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
872 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
873 case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
875 case oNoAllowExternalCache: opt.allow_external_cache = 0;
878 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
882 return 0; /* not handled */
885 return 1; /* handled */
889 /* Fixup some options after all have been processed. */
891 finalize_rereadable_options (void)
897 thread_init_once (void)
899 static int npth_initialized = 0;
901 if (!npth_initialized)
906 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
907 /* Now that we have set the syscall clamp we need to tell Libgcrypt
908 * that it should get them from libgpg-error. Note that Libgcrypt
909 * has already been initialized but at that point nPth was not
910 * initialized and thus Libgcrypt could not set its system call
912 #if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */
913 gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
919 initialize_modules (void)
922 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
923 initialize_module_cache ();
924 initialize_module_call_pinentry ();
925 initialize_module_call_scd ();
926 initialize_module_trustlist ();
930 /* The main entry point. */
932 main (int argc, char **argv )
937 FILE *configfp = NULL;
938 char *configname = NULL;
940 unsigned configlineno;
942 int default_config =1;
947 char *logfile = NULL;
949 int gpgconf_list = 0;
951 struct assuan_malloc_hooks malloc_hooks;
953 early_system_init ();
955 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
956 /* Disable ptrace on Linux without sgid bit */
957 prctl(PR_SET_DUMPABLE, 0);
960 /* Before we do anything else we save the list of currently open
961 file descriptors and the signal mask. This info is required to
962 do the exec call properly. We don't need it on Windows. */
963 #ifndef HAVE_W32_SYSTEM
964 startup_fd_list = get_all_open_fds ();
965 #endif /*!HAVE_W32_SYSTEM*/
966 #ifdef HAVE_SIGPROCMASK
967 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
968 startup_signal_mask_valid = 1;
969 #endif /*HAVE_SIGPROCMASK*/
971 /* Set program name etc. */
972 set_strusage (my_strusage);
973 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
974 /* Please note that we may running SUID(ROOT), so be very CAREFUL
975 when adding any stuff between here and the call to INIT_SECMEM()
976 somewhere after the option parsing */
977 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
979 /* Make sure that our subsystems are ready. */
981 init_common_subsystems (&argc, &argv);
983 malloc_hooks.malloc = gcry_malloc;
984 malloc_hooks.realloc = gcry_realloc;
985 malloc_hooks.free = gcry_free;
986 assuan_set_malloc_hooks (&malloc_hooks);
987 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
989 setup_libassuan_logging (&opt.debug, NULL);
991 setup_libgcrypt_logging ();
992 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
993 gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
995 disable_core_dumps ();
997 /* Set default options. */
998 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
1000 shell = getenv ("SHELL");
1001 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1004 /* Record some of the original environment strings. */
1008 static const char *names[] =
1009 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
1012 opt.startup_env = session_env_new ();
1013 if (!opt.startup_env)
1014 err = gpg_error_from_syserror ();
1015 for (idx=0; !err && names[idx]; idx++)
1017 s = getenv (names[idx]);
1019 err = session_env_setenv (opt.startup_env, names[idx], s);
1023 s = gnupg_ttyname (0);
1025 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
1028 log_fatal ("error recording startup environment: %s\n",
1029 gpg_strerror (err));
1031 /* Fixme: Better use the locale function here. */
1032 opt.startup_lc_ctype = getenv ("LC_CTYPE");
1033 if (opt.startup_lc_ctype)
1034 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
1035 opt.startup_lc_messages = getenv ("LC_MESSAGES");
1036 if (opt.startup_lc_messages)
1037 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
1040 /* Check whether we have a config file on the commandline */
1045 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1046 while (arg_parse( &pargs, opts))
1048 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
1050 else if (pargs.r_opt == oOptions)
1051 { /* yes there is one, so we do not try the default one, but
1052 read the option file when it is encountered at the
1056 else if (pargs.r_opt == oNoOptions)
1057 default_config = 0; /* --no-options */
1058 else if (pargs.r_opt == oHomedir)
1059 gnupg_set_homedir (pargs.r.ret_str);
1060 else if (pargs.r_opt == oDebugQuickRandom)
1062 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
1067 /* Initialize the secure memory. */
1068 gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0);
1072 Now we are now working under our real uid
1076 configname = make_filename (gnupg_homedir (),
1077 GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1083 pargs.flags= 1; /* do not remove the args */
1088 configfp = fopen (configname, "r");
1094 log_info (_("Note: no default option file '%s'\n"),
1096 /* Save the default conf file name so that
1097 reread_configuration is able to test whether the
1098 config file has been created in the meantime. */
1099 xfree (config_filename);
1100 config_filename = configname;
1105 log_error (_("option file '%s': %s\n"),
1106 configname, strerror(errno) );
1112 if (parse_debug && configname )
1113 log_info (_("reading options from '%s'\n"), configname );
1117 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
1119 if (parse_rereadable_options (&pargs, 0))
1120 continue; /* Already handled */
1121 switch (pargs.r_opt)
1123 case aGPGConfList: gpgconf_list = 1; break;
1124 case aGPGConfTest: gpgconf_list = 2; break;
1125 case aUseStandardSocketP: gpgconf_list = 3; break;
1126 case oBatch: opt.batch=1; break;
1128 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1131 /* config files may not be nested (silently ignore them) */
1135 configname = xstrdup(pargs.r.ret_str);
1139 case oNoGreeting: /* Dummy option. */ break;
1140 case oNoVerbose: opt.verbose = 0; break;
1141 case oNoOptions: break; /* no-options */
1142 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1143 case oNoDetach: nodetach = 1; break;
1144 case oLogFile: logfile = pargs.r.ret_str; break;
1145 case oCsh: csh_style = 1; break;
1146 case oSh: csh_style = 0; break;
1147 case oServer: pipe_server = 1; break;
1148 case oDaemon: is_daemon = 1; break;
1149 case oSupervised: is_supervised = 1; break;
1151 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
1152 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
1153 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
1154 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
1155 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
1157 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
1160 case oUseStandardSocket:
1161 case oNoUseStandardSocket:
1162 obsolete_option (configname, configlineno, "use-standard-socket");
1165 case oFakedSystemTime:
1167 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1168 if (faked_time == (time_t)(-1))
1169 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1170 gnupg_set_time (faked_time, 0);
1174 case oKeepTTY: opt.keep_tty = 1; break;
1175 case oKeepDISPLAY: opt.keep_display = 1; break;
1181 # ifdef HAVE_W32_SYSTEM
1187 opt.extra_socket = 1; /* (1 = points into argv) */
1188 socket_name_extra = pargs.r.ret_str;
1191 case oBrowserSocket:
1192 opt.browser_socket = 1; /* (1 = points into argv) */
1193 socket_name_browser = pargs.r.ret_str;
1196 case oDebugQuickRandom:
1197 /* Only used by the first stage command line parser. */
1201 obsolete_option (configname, configlineno, "write-env-file");
1204 default : pargs.err = configfp? 1:2; break;
1211 /* Keep a copy of the name so that it can be read on SIGHUP. */
1212 if (config_filename != configname)
1214 xfree (config_filename);
1215 config_filename = configname;
1223 if (log_get_errorcount(0))
1226 finalize_rereadable_options ();
1228 /* Print a warning if an argument looks like an option. */
1229 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1233 for (i=0; i < argc; i++)
1234 if (argv[i][0] == '-' && argv[i][1] == '-')
1235 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1239 /* gpg-agent usually does not output any messages because it runs in
1240 the background. For log files it is acceptable to have messages
1241 always encoded in utf-8. We switch here to utf-8, so that
1242 commands like --help still give native messages. It is far
1243 easier to switch only once instead of for every message and it
1244 actually helps when more then one thread is active (avoids an
1245 extra copy step). */
1246 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1249 if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
1251 /* We have been called without any command and thus we merely
1252 check whether an agent is already running. We do this right
1253 here so that we don't clobber a logfile with this check but
1254 print the status directly to stderr. */
1257 check_for_running_agent (0);
1263 else if (!opt.extra_socket)
1264 opt.extra_socket = 1;
1265 else if (socket_name_extra
1266 && (!strcmp (socket_name_extra, "none")
1267 || !strcmp (socket_name_extra, "/dev/null")))
1269 /* User requested not to create this socket. */
1270 opt.extra_socket = 0;
1271 socket_name_extra = NULL;
1276 else if (!opt.browser_socket)
1277 opt.browser_socket = 1;
1278 else if (socket_name_browser
1279 && (!strcmp (socket_name_browser, "none")
1280 || !strcmp (socket_name_browser, "/dev/null")))
1282 /* User requested not to create this socket. */
1283 opt.browser_socket = 0;
1284 socket_name_browser = NULL;
1289 if (atexit (cleanup))
1291 log_error ("atexit failed\n");
1296 /* Try to create missing directories. */
1297 create_directories ();
1299 if (debug_wait && pipe_server)
1301 thread_init_once ();
1302 log_debug ("waiting for debugger - my pid is %u .....\n",
1303 (unsigned int)getpid());
1304 gnupg_sleep (debug_wait);
1305 log_debug ("... okay\n");
1308 if (gpgconf_list == 3)
1310 /* We now use the standard socket always - return true for
1311 backward compatibility. */
1314 else if (gpgconf_list == 2)
1316 else if (gpgconf_list)
1321 /* List options and default values in the GPG Conf format. */
1322 filename = make_filename (gnupg_homedir (),
1323 GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1324 filename_esc = percent_escape (filename, NULL);
1326 es_printf ("%s-%s.conf:%lu:\"%s\n",
1327 GPGCONF_NAME, GPG_AGENT_NAME,
1328 GC_OPT_FLAG_DEFAULT, filename_esc);
1330 xfree (filename_esc);
1332 es_printf ("verbose:%lu:\n"
1334 "debug-level:%lu:\"none:\n"
1336 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1337 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1338 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1339 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1340 es_printf ("default-cache-ttl:%lu:%d:\n",
1341 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1342 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1343 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1344 es_printf ("max-cache-ttl:%lu:%d:\n",
1345 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1346 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1347 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1348 es_printf ("enforce-passphrase-constraints:%lu:\n",
1349 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1350 es_printf ("min-passphrase-len:%lu:%d:\n",
1351 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1352 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1353 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1354 MIN_PASSPHRASE_NONALPHA);
1355 es_printf ("check-passphrase-pattern:%lu:\n",
1356 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1357 es_printf ("max-passphrase-days:%lu:%d:\n",
1358 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1359 MAX_PASSPHRASE_DAYS);
1360 es_printf ("enable-passphrase-history:%lu:\n",
1361 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1362 es_printf ("no-grab:%lu:\n",
1363 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1364 es_printf ("ignore-cache-for-signing:%lu:\n",
1365 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1366 es_printf ("no-allow-external-cache:%lu:\n",
1367 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1368 es_printf ("no-allow-mark-trusted:%lu:\n",
1369 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1370 es_printf ("disable-scdaemon:%lu:\n",
1371 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1372 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1373 #ifdef HAVE_W32_SYSTEM
1374 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1376 es_printf ("no-allow-loopback-pinentry:%lu:\n",
1377 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1378 es_printf ("allow-emacs-pinentry:%lu:\n",
1379 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1380 es_printf ("pinentry-timeout:%lu:0:\n",
1381 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1386 /* Now start with logging to a file if this is desired. */
1389 log_set_file (logfile);
1390 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1391 | GPGRT_LOG_WITH_TIME
1392 | GPGRT_LOG_WITH_PID));
1393 current_logfile = xstrdup (logfile);
1396 /* Make sure that we have a default ttyname. */
1397 if (!default_ttyname && gnupg_ttyname (1))
1398 default_ttyname = xstrdup (gnupg_ttyname (1));
1399 if (!default_ttytype && getenv ("TERM"))
1400 default_ttytype = xstrdup (getenv ("TERM"));
1405 /* This is the simple pipe based server */
1408 initialize_modules ();
1410 ctrl = xtrycalloc (1, sizeof *ctrl);
1413 log_error ("error allocating connection control data: %s\n",
1417 ctrl->session_env = session_env_new ();
1418 if (!ctrl->session_env)
1420 log_error ("error allocating session environment block: %s\n",
1425 agent_init_default_ctrl (ctrl);
1426 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1427 agent_deinit_default_ctrl (ctrl);
1430 else if (is_supervised)
1432 #ifndef HAVE_W32_SYSTEM
1433 gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
1435 initialize_modules ();
1437 /* when supervised and sending logs to stderr, the process
1438 supervisor should handle log entry metadata (pid, name,
1441 log_set_prefix (NULL, 0);
1443 log_info ("%s %s starting in supervised mode.\n",
1444 strusage(11), strusage(13) );
1446 /* See below in "regular server mode" on why we remove certain
1448 if (!opt.keep_display)
1449 gnupg_unsetenv ("DISPLAY");
1450 gnupg_unsetenv ("INSIDE_EMACS");
1452 /* Virtually create the sockets. Note that we use -1 here
1453 * because the whole thing works only on Unix. */
1454 map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
1456 log_fatal ("no standard socket provided\n");
1458 #ifdef HAVE_SIGPROCMASK
1459 if (startup_signal_mask_valid)
1461 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1462 log_error ("error restoring signal mask: %s\n",
1466 log_info ("no saved signal mask\n");
1467 #endif /*HAVE_SIGPROCMASK*/
1469 log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
1470 fd, fd_extra, fd_browser, fd_ssh);
1471 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1472 #endif /*!HAVE_W32_SYSTEM*/
1474 else if (!is_daemon)
1477 { /* Regular server mode */
1479 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1480 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1481 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1482 #ifndef HAVE_W32_SYSTEM
1486 /* Remove the DISPLAY variable so that a pinentry does not
1487 default to a specific display. There is still a default
1488 display when gpg-agent was started using --display or a
1489 client requested this using an OPTION command. Note, that we
1490 don't do this when running in reverse daemon mode (i.e. when
1491 exec the program given as arguments). */
1492 #ifndef HAVE_W32_SYSTEM
1493 if (!opt.keep_display && !argc)
1494 gnupg_unsetenv ("DISPLAY");
1497 /* Remove the INSIDE_EMACS variable so that a pinentry does not
1498 always try to interact with Emacs. The variable is set when
1499 a client requested this using an OPTION command. */
1500 gnupg_unsetenv ("INSIDE_EMACS");
1502 /* Create the sockets. */
1503 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1504 fd = create_server_socket (socket_name, 1, 0,
1505 &redir_socket_name, &socket_nonce);
1507 if (opt.extra_socket)
1509 if (socket_name_extra)
1510 socket_name_extra = create_socket_name (socket_name_extra, 0);
1512 socket_name_extra = create_socket_name
1513 /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1);
1514 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1515 fd_extra = create_server_socket (socket_name_extra, 0, 0,
1516 &redir_socket_name_extra,
1517 &socket_nonce_extra);
1520 if (opt.browser_socket)
1522 if (socket_name_browser)
1523 socket_name_browser = create_socket_name (socket_name_browser, 0);
1525 socket_name_browser= create_socket_name
1526 /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1);
1527 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1528 fd_browser = create_server_socket (socket_name_browser, 0, 0,
1529 &redir_socket_name_browser,
1530 &socket_nonce_browser);
1533 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1534 fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1535 &redir_socket_name_ssh,
1538 /* If we are going to exec a program in the parent, we record
1539 the PID, so that the child may check whether the program is
1542 parent_pid = getpid ();
1546 #ifdef HAVE_W32_SYSTEM
1550 initialize_modules ();
1552 #else /*!HAVE_W32_SYSTEM*/
1555 if (pid == (pid_t)-1)
1557 log_fatal ("fork failed: %s\n", strerror (errno) );
1561 { /* We are the parent */
1562 char *infostr_ssh_sock, *infostr_ssh_valid;
1564 /* Close the socket FD. */
1567 /* The signal mask might not be correct right now and thus
1568 we restore it. That is not strictly necessary but some
1569 programs falsely assume a cleared signal mask. */
1571 #ifdef HAVE_SIGPROCMASK
1572 if (startup_signal_mask_valid)
1574 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1575 log_error ("error restoring signal mask: %s\n",
1579 log_info ("no saved signal mask\n");
1580 #endif /*HAVE_SIGPROCMASK*/
1582 /* Create the SSH info string if enabled. */
1585 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1586 socket_name_ssh) < 0)
1588 log_error ("out of core\n");
1589 kill (pid, SIGTERM);
1592 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1593 (unsigned long)getpid()) < 0)
1595 log_error ("out of core\n");
1596 kill (pid, SIGTERM);
1601 *socket_name = 0; /* Don't let cleanup() remove the socket -
1602 the child should do this from now on */
1603 if (opt.extra_socket)
1604 *socket_name_extra = 0;
1605 if (opt.browser_socket)
1606 *socket_name_browser = 0;
1607 *socket_name_ssh = 0;
1610 { /* Run the program given on the commandline. */
1611 if (ssh_support && (putenv (infostr_ssh_sock)
1612 || putenv (infostr_ssh_valid)))
1614 log_error ("failed to set environment: %s\n",
1616 kill (pid, SIGTERM );
1620 /* Close all the file descriptors except the standard
1621 ones and those open at startup. We explicitly don't
1622 close 0,1,2 in case something went wrong collecting
1624 close_all_fds (3, startup_fd_list);
1626 /* Run the command. */
1627 execvp (argv[0], argv);
1628 log_error ("failed to run the command: %s\n", strerror (errno));
1629 kill (pid, SIGTERM);
1634 /* Print the environment string, so that the caller can use
1635 shell's eval to set it */
1640 *strchr (infostr_ssh_sock, '=') = ' ';
1641 es_printf ("setenv %s;\n", infostr_ssh_sock);
1648 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1654 xfree (infostr_ssh_sock);
1655 xfree (infostr_ssh_valid);
1666 initialize_modules ();
1668 /* Detach from tty and put process into a new session */
1672 unsigned int oldflags;
1674 /* Close stdin, stdout and stderr unless it is the log stream */
1675 for (i=0; i <= 2; i++)
1677 if (!log_test_fd (i) && i != fd )
1680 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1682 log_error ("failed to open '%s': %s\n",
1683 "/dev/null", strerror (errno));
1691 log_error ("setsid() failed: %s\n", strerror(errno) );
1696 log_get_prefix (&oldflags);
1697 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1698 opt.running_detached = 1;
1703 log_error ("chdir to / failed: %s\n", strerror (errno));
1708 struct sigaction sa;
1710 sa.sa_handler = SIG_IGN;
1711 sigemptyset (&sa.sa_mask);
1713 sigaction (SIGPIPE, &sa, NULL);
1715 #endif /*!HAVE_W32_SYSTEM*/
1717 log_info ("%s %s started\n", strusage(11), strusage(13) );
1718 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1719 assuan_sock_close (fd);
1726 /* Exit entry point. This function should be called instead of a
1731 /*FIXME: update_random_seed_file();*/
1733 /* We run our cleanup handler because that may close cipher contexts
1734 stored in secure memory and thus this needs to be done before we
1735 explicitly terminate secure memory. */
1739 /* at this time a bit annoying */
1740 if (opt.debug & DBG_MEMSTAT_VALUE)
1742 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1743 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1746 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1748 gcry_control (GCRYCTL_TERM_SECMEM );
1749 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1754 /* This is our callback function for gcrypt progress messages. It is
1755 set once at startup and dispatches progress messages to the
1756 corresponding threads of the agent. */
1758 agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1759 int current, int total)
1761 struct progress_dispatch_s *dispatch;
1762 npth_t mytid = npth_self ();
1766 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1767 if (dispatch->ctrl && dispatch->tid == mytid)
1769 if (dispatch && dispatch->cb)
1770 dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1772 /* Libgcrypt < 1.8 does not know about nPth and thus when it reads
1773 * from /dev/random this will block the process. To mitigate this
1774 * problem we yield the thread when Libgcrypt tells us that it needs
1775 * more entropy. This way other threads have chance to run. */
1776 #if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */
1777 if (what && !strcmp (what, "need_entropy"))
1779 #if GPGRT_VERSION_NUMBER < 0x011900 /* 1.25 */
1780 /* In older gpg-error versions gpgrt_yield is buggy for use with
1781 * nPth and thus we need to resort to a sleep call. */
1782 npth_usleep (1000); /* 1ms */
1791 /* If a progress dispatcher callback has been associated with the
1792 * current connection unregister it. */
1794 unregister_progress_cb (void)
1796 struct progress_dispatch_s *dispatch;
1797 npth_t mytid = npth_self ();
1799 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1800 if (dispatch->ctrl && dispatch->tid == mytid)
1804 dispatch->ctrl = NULL;
1805 dispatch->cb = NULL;
1810 /* Setup a progress callback CB for the current connection. Using a
1811 * CB of NULL disables the callback. */
1813 agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1814 int printchar, int current, int total),
1817 struct progress_dispatch_s *dispatch, *firstfree;
1818 npth_t mytid = npth_self ();
1821 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1823 if (dispatch->ctrl && dispatch->tid == mytid)
1825 if (!dispatch->ctrl && !firstfree)
1826 firstfree = dispatch;
1828 if (!dispatch) /* None allocated: Reuse or allocate a new one. */
1832 dispatch = firstfree;
1834 else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1836 dispatch->next = progress_dispatch_list;
1837 progress_dispatch_list = dispatch;
1841 log_error ("error allocating new progress dispatcher slot: %s\n",
1842 gpg_strerror (gpg_error_from_syserror ()));
1845 dispatch->ctrl = ctrl;
1846 dispatch->tid = mytid;
1853 /* Each thread has its own local variables conveyed by a control
1854 structure usually identified by an argument named CTRL. This
1855 function is called immediately after allocating the control
1856 structure. Its purpose is to setup the default values for that
1857 structure. Note that some values may have already been set. */
1859 agent_init_default_ctrl (ctrl_t ctrl)
1861 assert (ctrl->session_env);
1863 /* Note we ignore malloc errors because we can't do much about it
1864 and the request will fail anyway shortly after this
1866 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1867 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1868 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1869 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1870 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1873 xfree (ctrl->lc_ctype);
1874 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1876 if (ctrl->lc_messages)
1877 xfree (ctrl->lc_messages);
1878 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1880 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1884 /* Release all resources allocated by default in the control
1885 structure. This is the counterpart to agent_init_default_ctrl. */
1887 agent_deinit_default_ctrl (ctrl_t ctrl)
1889 unregister_progress_cb ();
1890 session_env_release (ctrl->session_env);
1893 xfree (ctrl->lc_ctype);
1894 if (ctrl->lc_messages)
1895 xfree (ctrl->lc_messages);
1899 /* Because the ssh protocol does not send us information about the
1900 current TTY setting, we use this function to use those from startup
1901 or those explicitly set. This is also used for the restricted mode
1902 where we ignore requests to change the environment. */
1904 agent_copy_startup_env (ctrl_t ctrl)
1906 static const char *names[] =
1907 {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1908 gpg_error_t err = 0;
1912 for (idx=0; !err && names[idx]; idx++)
1913 if ((value = session_env_getenv (opt.startup_env, names[idx])))
1914 err = session_env_setenv (ctrl->session_env, names[idx], value);
1916 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1917 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1918 err = gpg_error_from_syserror ();
1920 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1921 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1922 err = gpg_error_from_syserror ();
1925 log_error ("error setting default session environment: %s\n",
1926 gpg_strerror (err));
1932 /* Reread parts of the configuration. Note, that this function is
1933 obviously not thread-safe and should only be called from the PTH
1936 Fixme: Due to the way the argument parsing works, we create a
1937 memory leak here for all string type arguments. There is currently
1938 no clean way to tell whether the memory for the argument has been
1939 allocated or points into the process' original arguments. Unless
1940 we have a mechanism to tell this, we need to live on with this. */
1942 reread_configuration (void)
1944 ARGPARSE_ARGS pargs;
1946 unsigned int configlineno = 0;
1949 if (!config_filename)
1950 return; /* No config file. */
1952 fp = fopen (config_filename, "r");
1955 log_info (_("option file '%s': %s\n"),
1956 config_filename, strerror(errno) );
1960 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1962 memset (&pargs, 0, sizeof pargs);
1964 pargs.argc = &dummy;
1965 pargs.flags = 1; /* do not remove the args */
1966 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1968 if (pargs.r_opt < -1)
1969 pargs.err = 1; /* Print a warning. */
1970 else /* Try to parse this option - ignore unchangeable ones. */
1971 parse_rereadable_options (&pargs, 1);
1974 finalize_rereadable_options ();
1979 /* Return the file name of the socket we are using for native
1982 get_agent_socket_name (void)
1984 const char *s = socket_name;
1986 return (s && *s)? s : NULL;
1989 /* Return the file name of the socket we are using for SSH
1992 get_agent_ssh_socket_name (void)
1994 const char *s = socket_name_ssh;
1996 return (s && *s)? s : NULL;
2000 /* Return the number of active connections. */
2002 get_agent_active_connection_count (void)
2004 return active_connections;
2008 /* Under W32, this function returns the handle of the scdaemon
2009 notification event. Calling it the first time creates that
2011 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
2013 get_agent_scd_notify_event (void)
2015 static HANDLE the_event = INVALID_HANDLE_VALUE;
2017 if (the_event == INVALID_HANDLE_VALUE)
2020 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
2022 /* We need to use a manual reset event object due to the way our
2023 w32-pth wait function works: If we would use an automatic
2024 reset event we are not able to figure out which handle has
2025 been signaled because at the time we single out the signaled
2026 handles using WFSO the event has already been reset due to
2028 h = CreateEvent (&sa, TRUE, FALSE, NULL);
2030 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
2031 else if (!DuplicateHandle (GetCurrentProcess(), h,
2032 GetCurrentProcess(), &h2,
2033 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
2035 log_error ("setting syncronize for scd notify event failed: %s\n",
2036 w32_strerror (-1) );
2048 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
2052 /* Create a name for the socket in the home directory as using
2053 STANDARD_NAME. We also check for valid characters as well as
2054 against a maximum allowed length for a unix domain socket is done.
2055 The function terminates the process in case of an error. Returns:
2056 Pointer to an allocated string with the absolute name of the socket
2059 create_socket_name (char *standard_name, int with_homedir)
2064 name = make_filename (gnupg_socketdir (), standard_name, NULL);
2066 name = make_filename (standard_name, NULL);
2067 if (strchr (name, PATHSEP_C))
2069 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
2077 /* Create a Unix domain socket with NAME. Returns the file descriptor
2078 or terminates the process in case of an error. Note that this
2079 function needs to be used for the regular socket first (indicated
2080 by PRIMARY) and only then for the extra and the ssh sockets. If
2081 the socket has been redirected the name of the real socket is
2082 stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
2083 Cygwin compatible socket is created (Windows only). */
2085 create_server_socket (char *name, int primary, int cygwin,
2086 char **r_redir_name, assuan_sock_nonce_t *nonce)
2088 struct sockaddr *addr;
2089 struct sockaddr_un *unaddr;
2094 xfree (*r_redir_name);
2095 *r_redir_name = NULL;
2097 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
2098 if (fd == ASSUAN_INVALID_FD)
2100 log_error (_("can't create socket: %s\n"), strerror (errno));
2101 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2106 assuan_sock_set_flag (fd, "cygwin", 1);
2108 unaddr = xmalloc (sizeof *unaddr);
2109 addr = (struct sockaddr*)unaddr;
2114 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
2116 if (errno == ENAMETOOLONG)
2117 log_error (_("socket name '%s' is too long\n"), name);
2119 log_error ("error preparing socket '%s': %s\n",
2120 name, gpg_strerror (gpg_error_from_syserror ()));
2121 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2126 *r_redir_name = xstrdup (unaddr->sun_path);
2128 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
2132 len = SUN_LEN (unaddr);
2133 rc = assuan_sock_bind (fd, addr, len);
2135 /* Our error code mapping on W32CE returns EEXIST thus we also test
2138 && (errno == EADDRINUSE
2139 #ifdef HAVE_W32_SYSTEM
2144 /* Check whether a gpg-agent is already running. We do this
2145 test only if this is the primary socket. For secondary
2146 sockets we assume that a test for gpg-agent has already been
2147 done and reuse the requested socket. Testing the ssh-socket
2148 is not possible because at this point, though we know the new
2149 Assuan socket, the Assuan server and thus the ssh-agent
2150 server is not yet operational; this would lead to a hang. */
2151 if (primary && !check_for_running_agent (1))
2153 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
2154 log_set_file (NULL);
2155 log_error (_("a gpg-agent is already running - "
2156 "not starting a new one\n"));
2157 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2158 assuan_sock_close (fd);
2161 gnupg_remove (unaddr->sun_path);
2162 rc = assuan_sock_bind (fd, addr, len);
2164 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
2165 log_error (_("error getting nonce for the socket\n"));
2168 /* We use gpg_strerror here because it allows us to get strings
2169 for some W32 socket error codes. */
2170 log_error (_("error binding socket to '%s': %s\n"),
2172 gpg_strerror (gpg_error_from_syserror ()));
2174 assuan_sock_close (fd);
2175 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2179 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
2180 log_error (_("can't set permissions of '%s': %s\n"),
2181 unaddr->sun_path, strerror (errno));
2183 if (listen (FD2INT(fd), 5 ) == -1)
2185 log_error (_("listen() failed: %s\n"), strerror (errno));
2186 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2187 assuan_sock_close (fd);
2192 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
2198 /* Check that the directory for storing the private keys exists and
2199 create it if not. This function won't fail as it is only a
2200 convenience function and not strictly necessary. */
2202 create_private_keys_directory (const char *home)
2205 struct stat statbuf;
2207 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
2208 if (stat (fname, &statbuf) && errno == ENOENT)
2210 if (gnupg_mkdir (fname, "-rwx"))
2211 log_error (_("can't create directory '%s': %s\n"),
2212 fname, strerror (errno) );
2213 else if (!opt.quiet)
2214 log_info (_("directory '%s' created\n"), fname);
2216 if (gnupg_chmod (fname, "-rwx"))
2217 log_error (_("can't set permissions of '%s': %s\n"),
2218 fname, strerror (errno));
2223 /* Create the directory only if the supplied directory name is the
2224 same as the default one. This way we avoid to create arbitrary
2225 directories when a non-default home directory is used. To cope
2226 with HOME, we compare only the suffix if we see that the default
2227 homedir does start with a tilde. We don't stop here in case of
2228 problems because other functions will throw an error anyway.*/
2230 create_directories (void)
2232 struct stat statbuf;
2233 const char *defhome = standard_homedir ();
2236 home = make_filename (gnupg_homedir (), NULL);
2237 if ( stat (home, &statbuf) )
2239 if (errno == ENOENT)
2242 #ifdef HAVE_W32_SYSTEM
2243 ( !compare_filenames (home, defhome) )
2246 && (strlen (home) >= strlen (defhome+1)
2247 && !strcmp (home + strlen(home)
2248 - strlen (defhome+1), defhome+1)))
2249 || (*defhome != '~' && !strcmp (home, defhome) )
2253 if (gnupg_mkdir (home, "-rwx"))
2254 log_error (_("can't create directory '%s': %s\n"),
2255 home, strerror (errno) );
2259 log_info (_("directory '%s' created\n"), home);
2260 create_private_keys_directory (home);
2265 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
2267 else if ( !S_ISDIR(statbuf.st_mode))
2269 log_error (_("can't use '%s' as home directory\n"), home);
2271 else /* exists and is a directory. */
2273 create_private_keys_directory (home);
2280 /* This is the worker for the ticker. It is called every few seconds
2281 and may only do fast operations. */
2285 static time_t last_minute;
2288 last_minute = time (NULL);
2290 /* Check whether the scdaemon has died and cleanup in this case. */
2291 agent_scd_check_aliveness ();
2293 /* If we are running as a child of another process, check whether
2294 the parent is still alive and shutdown if not. */
2295 #ifndef HAVE_W32_SYSTEM
2296 if (parent_pid != (pid_t)(-1))
2298 if (kill (parent_pid, 0))
2300 shutdown_pending = 2;
2301 log_info ("parent process died - shutting down\n");
2302 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2307 #endif /*HAVE_W32_SYSTEM*/
2309 /* Code to be run from time to time. */
2310 #if CHECK_OWN_SOCKET_INTERVAL > 0
2311 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
2313 check_own_socket ();
2314 last_minute = time (NULL);
2321 /* A global function which allows us to call the reload stuff from
2322 other places too. This is only used when build for W32. */
2324 agent_sighup_action (void)
2326 log_info ("SIGHUP received - "
2327 "re-reading configuration and flushing cache\n");
2329 agent_flush_cache ();
2330 reread_configuration ();
2331 agent_reload_trustlist ();
2332 /* We flush the module name cache so that after installing a
2333 "pinentry" binary that one can be used in case the
2334 "pinentry-basic" fallback was in use. */
2335 gnupg_module_name_flush_some ();
2339 /* A helper function to handle SIGUSR2. */
2341 agent_sigusr2_action (void)
2344 log_info ("SIGUSR2 received - updating card event counter\n");
2345 /* Nothing to check right now. We only increment a counter. */
2346 bump_card_eventcounter ();
2350 #ifndef HAVE_W32_SYSTEM
2351 /* The signal handler for this program. It is expected to be run in
2352 its own trhead and not in the context of a signal handler. */
2354 handle_signal (int signo)
2358 #ifndef HAVE_W32_SYSTEM
2360 agent_sighup_action ();
2364 log_info ("SIGUSR1 received - printing internal information:\n");
2365 /* Fixme: We need to see how to integrate pth dumping into our
2367 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2368 agent_query_dump_state ();
2369 agent_scd_dump_state ();
2373 agent_sigusr2_action ();
2377 if (!shutdown_pending)
2378 log_info ("SIGTERM received - shutting down ...\n");
2380 log_info ("SIGTERM received - still %i open connections\n",
2381 active_connections);
2383 if (shutdown_pending > 2)
2385 log_info ("shutdown forced\n");
2386 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2393 log_info ("SIGINT received - immediate shutdown\n");
2394 log_info( "%s %s stopped\n", strusage(11), strusage(13));
2400 log_info ("signal %d received - no action defined\n", signo);
2405 /* Check the nonce on a new connection. This is a NOP unless we we
2406 are using our Unix domain socket emulation under Windows. */
2408 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2410 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2412 log_info (_("error reading nonce on fd %d: %s\n"),
2413 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2414 assuan_sock_close (ctrl->thread_startup.fd);
2423 #ifdef HAVE_W32_SYSTEM
2424 /* The window message processing function for Putty. Warning: This
2425 code runs as a native Windows thread. Use of our own functions
2426 needs to be bracket with pth_leave/pth_enter. */
2427 static LRESULT CALLBACK
2428 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2432 COPYDATASTRUCT *cds;
2433 const char *mapfile;
2438 PSECURITY_DESCRIPTOR psd = NULL;
2441 if (msg != WM_COPYDATA)
2443 return DefWindowProc (hwnd, msg, wparam, lparam);
2446 cds = (COPYDATASTRUCT*)lparam;
2447 if (cds->dwData != PUTTY_IPC_MAGIC)
2448 return 0; /* Ignore data with the wrong magic. */
2449 mapfile = cds->lpData;
2450 if (!cds->cbData || mapfile[cds->cbData - 1])
2451 return 0; /* Ignore empty and non-properly terminated strings. */
2456 log_debug ("ssh map file '%s'", mapfile);
2460 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2464 log_debug ("ssh map handle %p\n", maphd);
2468 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2473 mysid = w32_get_user_sid ();
2476 log_error ("error getting my sid\n");
2480 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2481 OWNER_SECURITY_INFORMATION,
2482 &mapsid, NULL, NULL, NULL,
2486 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2494 if (!ConvertSidToStringSid (mysid, &sidstr))
2496 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2498 if (!ConvertSidToStringSid (mapsid, &sidstr))
2500 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2504 if (!EqualSid (mysid, mapsid))
2506 log_error ("ssh map file has a non-matching sid\n");
2510 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2512 log_debug ("ssh IPC buffer at %p\n", data);
2516 /* log_printhex ("request:", data, 20); */
2518 ctrl = xtrycalloc (1, sizeof *ctrl);
2521 log_error ("error allocating connection control data: %s\n",
2525 ctrl->session_env = session_env_new ();
2526 if (!ctrl->session_env)
2528 log_error ("error allocating session environment block: %s\n",
2533 agent_init_default_ctrl (ctrl);
2534 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2535 ret = 1; /* Valid ssh message has been constructed. */
2536 agent_deinit_default_ctrl (ctrl);
2537 /* log_printhex (" reply:", data, 20); */
2542 UnmapViewOfFile (data);
2547 CloseHandle (maphd);
2553 #endif /*HAVE_W32_SYSTEM*/
2556 #ifdef HAVE_W32_SYSTEM
2557 /* The thread handling Putty's IPC requests. */
2559 putty_message_thread (void *arg)
2561 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2562 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2569 log_info ("putty message loop thread started\n");
2571 /* The message loop runs as thread independent from our nPth system.
2572 This also means that we need to make sure that we switch back to
2573 our system before calling any no-windows function. */
2576 /* First create a window to make sure that a message queue exists
2578 if (!RegisterClass (&wndwclass))
2581 log_error ("error registering Pageant window class");
2584 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2586 HWND_MESSAGE, /* hWndParent */
2587 NULL, /* hWndMenu */
2588 NULL, /* hInstance */
2593 log_error ("error creating Pageant window");
2597 while (GetMessage(&msg, NULL, 0, 0))
2599 TranslateMessage(&msg);
2600 DispatchMessage(&msg);
2607 log_info ("putty message loop thread stopped\n");
2610 #endif /*HAVE_W32_SYSTEM*/
2614 do_start_connection_thread (ctrl_t ctrl)
2616 active_connections++;
2617 agent_init_default_ctrl (ctrl);
2618 if (opt.verbose && !DBG_IPC)
2619 log_info (_("handler 0x%lx for fd %d started\n"),
2620 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2622 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2623 if (opt.verbose && !DBG_IPC)
2624 log_info (_("handler 0x%lx for fd %d terminated\n"),
2625 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2627 agent_deinit_default_ctrl (ctrl);
2629 active_connections--;
2634 /* This is the standard connection thread's main function. */
2636 start_connection_thread_std (void *arg)
2640 if (check_nonce (ctrl, &socket_nonce))
2642 log_error ("handler 0x%lx nonce check FAILED\n",
2643 (unsigned long) npth_self());
2647 return do_start_connection_thread (ctrl);
2651 /* This is the extra socket connection thread's main function. */
2653 start_connection_thread_extra (void *arg)
2657 if (check_nonce (ctrl, &socket_nonce_extra))
2659 log_error ("handler 0x%lx nonce check FAILED\n",
2660 (unsigned long) npth_self());
2664 ctrl->restricted = 1;
2665 return do_start_connection_thread (ctrl);
2669 /* This is the browser socket connection thread's main function. */
2671 start_connection_thread_browser (void *arg)
2675 if (check_nonce (ctrl, &socket_nonce_browser))
2677 log_error ("handler 0x%lx nonce check FAILED\n",
2678 (unsigned long) npth_self());
2682 ctrl->restricted = 2;
2683 return do_start_connection_thread (ctrl);
2687 /* This is the ssh connection thread's main function. */
2689 start_connection_thread_ssh (void *arg)
2693 if (check_nonce (ctrl, &socket_nonce_ssh))
2696 active_connections++;
2697 agent_init_default_ctrl (ctrl);
2699 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2700 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2702 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2704 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2705 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2707 agent_deinit_default_ctrl (ctrl);
2709 active_connections--;
2714 /* Connection handler loop. Wait for connection requests and spawn a
2715 thread after accepting a connection. */
2717 handle_connections (gnupg_fd_t listen_fd,
2718 gnupg_fd_t listen_fd_extra,
2719 gnupg_fd_t listen_fd_browser,
2720 gnupg_fd_t listen_fd_ssh)
2724 struct sockaddr_un paddr;
2726 fd_set fdset, read_fdset;
2731 struct timespec abstime;
2732 struct timespec curtime;
2733 struct timespec timeout;
2734 #ifdef HAVE_W32_SYSTEM
2736 unsigned int events_set;
2738 int my_inotify_fd = -1;
2741 void *(*func) (void *arg);
2744 { "std", start_connection_thread_std },
2745 { "extra", start_connection_thread_extra },
2746 { "browser", start_connection_thread_browser },
2747 { "ssh", start_connection_thread_ssh }
2751 ret = npth_attr_init(&tattr);
2753 log_fatal ("error allocating thread attributes: %s\n",
2755 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2757 #ifndef HAVE_W32_SYSTEM
2759 npth_sigev_add (SIGHUP);
2760 npth_sigev_add (SIGUSR1);
2761 npth_sigev_add (SIGUSR2);
2762 npth_sigev_add (SIGINT);
2763 npth_sigev_add (SIGTERM);
2766 # ifdef HAVE_W32CE_SYSTEM
2767 /* Use a dummy event. */
2769 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2771 events[0] = get_agent_scd_notify_event ();
2772 events[1] = INVALID_HANDLE_VALUE;
2776 if (disable_check_own_socket)
2778 else if ((err = gnupg_inotify_watch_socket (&my_inotify_fd, socket_name)))
2780 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2781 log_info ("error enabling fast daemon termination: %s\n",
2782 gpg_strerror (err));
2785 /* On Windows we need to fire up a separate thread to listen for
2786 requests from Putty (an SSH client), so we can replace Putty's
2787 Pageant (its ssh-agent implementation). */
2788 #ifdef HAVE_W32_SYSTEM
2793 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2796 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2799 #endif /*HAVE_W32_SYSTEM*/
2801 /* Set a flag to tell call-scd.c that it may enable event
2803 opt.sigusr2_enabled = 1;
2806 FD_SET (FD2INT (listen_fd), &fdset);
2807 nfd = FD2INT (listen_fd);
2808 if (listen_fd_extra != GNUPG_INVALID_FD)
2810 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2811 if (FD2INT (listen_fd_extra) > nfd)
2812 nfd = FD2INT (listen_fd_extra);
2814 if (listen_fd_browser != GNUPG_INVALID_FD)
2816 FD_SET ( FD2INT(listen_fd_browser), &fdset);
2817 if (FD2INT (listen_fd_browser) > nfd)
2818 nfd = FD2INT (listen_fd_browser);
2820 if (listen_fd_ssh != GNUPG_INVALID_FD)
2822 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2823 if (FD2INT (listen_fd_ssh) > nfd)
2824 nfd = FD2INT (listen_fd_ssh);
2826 if (my_inotify_fd != -1)
2828 FD_SET (my_inotify_fd, &fdset);
2829 if (my_inotify_fd > nfd)
2830 nfd = my_inotify_fd;
2833 listentbl[0].l_fd = listen_fd;
2834 listentbl[1].l_fd = listen_fd_extra;
2835 listentbl[2].l_fd = listen_fd_browser;
2836 listentbl[3].l_fd = listen_fd_ssh;
2838 npth_clock_gettime (&abstime);
2839 abstime.tv_sec += TIMERTICK_INTERVAL;
2843 /* Shutdown test. */
2844 if (shutdown_pending)
2846 if (active_connections == 0)
2849 /* Do not accept new connections but keep on running the
2850 * loop to cope with the timer events.
2852 * Note that we do not close the listening socket because a
2853 * client trying to connect to that socket would instead
2854 * restart a new dirmngr instance - which is unlikely the
2855 * intention of a shutdown. */
2858 if (my_inotify_fd != -1)
2860 FD_SET (my_inotify_fd, &fdset);
2861 nfd = my_inotify_fd;
2865 /* POSIX says that fd_set should be implemented as a structure,
2866 thus a simple assignment is fine to copy the entire set. */
2869 npth_clock_gettime (&curtime);
2870 if (!(npth_timercmp (&curtime, &abstime, <)))
2874 npth_clock_gettime (&abstime);
2875 abstime.tv_sec += TIMERTICK_INTERVAL;
2877 npth_timersub (&abstime, &curtime, &timeout);
2879 #ifndef HAVE_W32_SYSTEM
2880 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2881 npth_sigev_sigmask ());
2882 saved_errno = errno;
2886 while (npth_sigev_get_pending (&signo))
2887 handle_signal (signo);
2890 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2891 events, &events_set);
2892 saved_errno = errno;
2894 /* This is valid even if npth_eselect returns an error. */
2896 agent_sigusr2_action ();
2899 if (ret == -1 && saved_errno != EINTR)
2901 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2902 strerror (saved_errno));
2907 /* Interrupt or timeout. Will be handled when calculating the
2911 if (!shutdown_pending)
2917 if (my_inotify_fd != -1
2918 && FD_ISSET (my_inotify_fd, &read_fdset)
2919 && gnupg_inotify_has_name (my_inotify_fd, GPG_AGENT_SOCK_NAME))
2921 shutdown_pending = 1;
2922 log_info ("socket file has been removed - shutting down\n");
2925 for (idx=0; idx < DIM(listentbl); idx++)
2927 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2929 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2932 plen = sizeof paddr;
2933 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2934 (struct sockaddr *)&paddr, &plen));
2935 if (fd == GNUPG_INVALID_FD)
2937 log_error ("accept failed for %s: %s\n",
2938 listentbl[idx].name, strerror (errno));
2940 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2942 log_error ("error allocating connection data for %s: %s\n",
2943 listentbl[idx].name, strerror (errno) );
2944 assuan_sock_close (fd);
2946 else if ( !(ctrl->session_env = session_env_new ()))
2948 log_error ("error allocating session env block for %s: %s\n",
2949 listentbl[idx].name, strerror (errno) );
2951 assuan_sock_close (fd);
2955 ctrl->thread_startup.fd = fd;
2956 ret = npth_create (&thread, &tattr,
2957 listentbl[idx].func, ctrl);
2960 log_error ("error spawning connection handler for %s:"
2961 " %s\n", listentbl[idx].name, strerror (ret));
2962 assuan_sock_close (fd);
2966 fd = GNUPG_INVALID_FD;
2971 if (my_inotify_fd != -1)
2972 close (my_inotify_fd);
2974 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2975 npth_attr_destroy (&tattr);
2980 /* Helper for check_own_socket. */
2982 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2984 membuf_t *mb = opaque;
2985 put_membuf (mb, buffer, length);
2990 /* The thread running the actual check. We need to run this in a
2991 separate thread so that check_own_thread can be called from the
2994 check_own_socket_thread (void *arg)
2997 char *sockname = arg;
2998 assuan_context_t ctx = NULL;
3002 check_own_socket_running++;
3004 rc = assuan_new (&ctx);
3007 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
3010 assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
3012 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3015 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
3019 init_membuf (&mb, 100);
3020 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
3021 NULL, NULL, NULL, NULL);
3022 put_membuf (&mb, "", 1);
3023 buffer = get_membuf (&mb, NULL);
3026 log_error ("sending command \"%s\" to my own socket failed: %s\n",
3027 "GETINFO pid", gpg_strerror (rc));
3030 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
3032 log_error ("socket is now serviced by another server\n");
3035 else if (opt.verbose > 1)
3036 log_error ("socket is still served by this server\n");
3043 assuan_release (ctx);
3046 /* We may not remove the socket as it is now in use by another
3048 inhibit_socket_removal = 1;
3049 shutdown_pending = 2;
3050 log_info ("this process is useless - shutting down\n");
3052 check_own_socket_running--;
3057 /* Check whether we are still listening on our own socket. In case
3058 another gpg-agent process started after us has taken ownership of
3059 our socket, we would linger around without any real task. Thus we
3060 better check once in a while whether we are really needed. */
3062 check_own_socket (void)
3069 if (disable_check_own_socket)
3072 if (check_own_socket_running || shutdown_pending)
3073 return; /* Still running or already shutting down. */
3075 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3077 return; /* Out of memory. */
3079 err = npth_attr_init (&tattr);
3082 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3083 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
3085 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
3086 npth_attr_destroy (&tattr);
3091 /* Figure out whether an agent is available and running. Prints an
3092 error if not. If SILENT is true, no messages are printed.
3093 Returns 0 if the agent is running. */
3095 check_for_running_agent (int silent)
3099 assuan_context_t ctx = NULL;
3101 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3103 return gpg_error_from_syserror ();
3105 err = assuan_new (&ctx);
3107 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3112 log_error (_("no gpg-agent running in this session\n"));
3115 assuan_release (ctx);
3119 if (!opt.quiet && !silent)
3120 log_info ("gpg-agent running and available\n");
3122 assuan_release (ctx);