1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000-2020 Free Software Foundation, Inc.
3 * Copyright (C) 2000-2019 Werner Koch
4 * Copyright (C) 2015-2020 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20 * SPDX-License-Identifier: GPL-3.0-or-later
35 #ifdef HAVE_W32_SYSTEM
37 # define WINVER 0x0500 /* Same as in common/sysutils.c */
39 # ifdef HAVE_WINSOCK2_H
40 # include <winsock2.h>
44 #else /*!HAVE_W32_SYSTEM*/
45 # include <sys/socket.h>
47 #endif /*!HAVE_W32_SYSTEM*/
54 #define INCLUDED_BY_MAIN_MODULE 1
55 #define GNUPG_COMMON_NEED_AFLOCAL
57 #include <assuan.h> /* Malloc hooks and socket wrappers. */
59 #include "../common/i18n.h"
60 #include "../common/sysutils.h"
61 #include "../common/gc-opt-flags.h"
62 #include "../common/exechelp.h"
63 #include "../common/asshelp.h"
64 #include "../common/init.h"
67 enum cmd_and_opt_values
99 oPinentryInvisibleChar,
101 oPinentryFormattedPassphrase,
113 oEnforcePassphraseConstraints,
115 oMinPassphraseNonalpha,
116 oCheckPassphrasePattern,
117 oCheckSymPassphrasePattern,
119 oEnablePassphraseHistory,
120 oDisableExtendedKeyFormat,
121 oEnableExtendedKeyFormat,
123 oNoUseStandardSocket,
128 oIgnoreCacheForSigning,
131 oAllowPresetPassphrase,
132 oAllowLoopbackPinentry,
133 oNoAllowLoopbackPinentry,
134 oNoAllowExternalCache,
139 oSSHFingerprintDigest,
142 oDisableCheckOwnSocket,
155 # define ENAMETOOLONG EINVAL
159 static ARGPARSE_OPTS opts[] = {
161 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
162 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
163 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
165 ARGPARSE_group (301, N_("@Options:\n ")),
167 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
168 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
169 #ifndef HAVE_W32_SYSTEM
170 ARGPARSE_s_n (oSupervised, "supervised", N_("run in supervised mode")),
172 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
173 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
174 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
175 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
176 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
178 ARGPARSE_s_s (oDebug, "debug", "@"),
179 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
180 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
181 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
182 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
183 ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
185 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
186 ARGPARSE_s_n (oGrab, "grab", "@"),
187 /* FIXME: Add the below string for 2.3 */
188 /* N_("let PIN-Entry grab keyboard and mouse")), */
189 ARGPARSE_s_n (oNoGrab, "no-grab", "@"),
190 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
191 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
192 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
193 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
194 ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
195 ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
196 ARGPARSE_s_n (oPinentryFormattedPassphrase, "pinentry-formatted-passphrase",
198 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
199 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
200 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
201 /* */ N_("do not use the SCdaemon") ),
202 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
204 ARGPARSE_s_s (oExtraSocket, "extra-socket",
205 /* */ N_("|NAME|accept some commands via NAME")),
207 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
209 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
211 ARGPARSE_s_n (oBatch, "batch", "@"),
212 ARGPARSE_s_s (oHomedir, "homedir", "@"),
214 ARGPARSE_s_s (oDisplay, "display", "@"),
215 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
216 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
217 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
218 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
219 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
220 ARGPARSE_s_n (oKeepTTY, "keep-tty",
221 /* */ N_("ignore requests to change the TTY")),
222 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
223 /* */ N_("ignore requests to change the X display")),
225 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
226 N_("|N|expire cached PINs after N seconds")),
227 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
228 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
229 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
231 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
233 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
234 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
235 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
236 ARGPARSE_s_s (oCheckSymPassphrasePattern, "check-sym-passphrase-pattern",
238 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
239 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
241 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
242 /* */ N_("do not use the PIN cache when signing")),
243 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
244 /* */ N_("disallow the use of an external password cache")),
245 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
246 /* */ N_("disallow clients to mark keys as \"trusted\"")),
247 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
248 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
249 /* */ N_("allow presetting passphrase")),
250 ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
251 N_("disallow caller to override the pinentry")),
252 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
253 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
254 /* */ N_("allow passphrase to be prompted through Emacs")),
256 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
257 ARGPARSE_s_s (oSSHFingerprintDigest, "ssh-fingerprint-digest",
258 N_("|ALGO|use ALGO to show ssh fingerprints")),
259 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
260 #ifdef HAVE_W32_SYSTEM
261 /* */ N_("enable putty support")
266 ARGPARSE_s_n (oDisableExtendedKeyFormat, "disable-extended-key-format", "@"),
267 ARGPARSE_s_n (oEnableExtendedKeyFormat, "enable-extended-key-format", "@"),
269 ARGPARSE_s_u (oS2KCount, "s2k-count", "@"),
270 ARGPARSE_s_u (oS2KCalibration, "s2k-calibration", "@"),
272 ARGPARSE_op_u (oAutoExpandSecmem, "auto-expand-secmem", "@"),
274 ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
275 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
277 /* Dummy options for backward compatibility. */
278 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
279 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
280 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
285 ARGPARSE_end () /* End of list */
289 /* The list of supported debug flags. */
290 static struct debug_flags_s debug_flags [] =
292 { DBG_MPI_VALUE , "mpi" },
293 { DBG_CRYPTO_VALUE , "crypto" },
294 { DBG_MEMORY_VALUE , "memory" },
295 { DBG_CACHE_VALUE , "cache" },
296 { DBG_MEMSTAT_VALUE, "memstat" },
297 { DBG_HASHING_VALUE, "hashing" },
298 { DBG_IPC_VALUE , "ipc" },
299 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
304 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
305 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
306 #define MAX_CACHE_TTL (120*60) /* 2 hours */
307 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
308 #define MIN_PASSPHRASE_LEN (8)
309 #define MIN_PASSPHRASE_NONALPHA (1)
310 #define MAX_PASSPHRASE_DAYS (0)
312 /* The timer tick used for housekeeping stuff. Note that on Windows
313 * we use a SetWaitableTimer seems to signal earlier than about 2
314 * seconds. Thus we use 4 seconds on all platforms except for
315 * Windowsce. CHECK_OWN_SOCKET_INTERVAL defines how often we check
316 * our own socket in standard socket mode. If that value is 0 we
317 * don't check at all. All values are in seconds. */
318 #if defined(HAVE_W32CE_SYSTEM)
319 # define TIMERTICK_INTERVAL (60)
320 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
322 # define TIMERTICK_INTERVAL (4)
323 # define CHECK_OWN_SOCKET_INTERVAL (60)
327 /* Flag indicating that the ssh-agent subsystem has been enabled. */
328 static int ssh_support;
330 #ifdef HAVE_W32_SYSTEM
331 /* Flag indicating that support for Putty has been enabled. */
332 static int putty_support;
333 /* A magic value used with WM_COPYDATA. */
334 #define PUTTY_IPC_MAGIC 0x804e50ba
335 /* To avoid surprises we limit the size of the mapped IPC file to this
336 value. Putty currently (0.62) uses 8k, thus 16k should be enough
337 for the foreseeable future. */
338 #define PUTTY_IPC_MAXLEN 16384
339 #endif /*HAVE_W32_SYSTEM*/
341 /* The list of open file descriptors at startup. Note that this list
342 * has been allocated using the standard malloc. */
343 #ifndef HAVE_W32_SYSTEM
344 static int *startup_fd_list;
347 /* The signal mask at startup and a flag telling whether it is valid. */
348 #ifdef HAVE_SIGPROCMASK
349 static sigset_t startup_signal_mask;
350 static int startup_signal_mask_valid;
353 /* Flag to indicate that a shutdown was requested. */
354 static int shutdown_pending;
356 /* Counter for the currently running own socket checks. */
357 static int check_own_socket_running;
359 /* Flags to indicate that check_own_socket shall not be called. */
360 static int disable_check_own_socket;
362 /* Flag indicating that we are in supervised mode. */
363 static int is_supervised;
365 /* Flag to inhibit socket removal in cleanup. */
366 static int inhibit_socket_removal;
368 /* It is possible that we are currently running under setuid permissions */
369 static int maybe_setuid = 1;
371 /* Name of the communication socket used for native gpg-agent
372 requests. The second variable is either NULL or a malloced string
373 with the real socket name in case it has been redirected. */
374 static char *socket_name;
375 static char *redir_socket_name;
377 /* Name of the optional extra socket used for native gpg-agent requests. */
378 static char *socket_name_extra;
379 static char *redir_socket_name_extra;
381 /* Name of the optional browser socket used for native gpg-agent requests. */
382 static char *socket_name_browser;
383 static char *redir_socket_name_browser;
385 /* Name of the communication socket used for ssh-agent protocol. */
386 static char *socket_name_ssh;
387 static char *redir_socket_name_ssh;
389 /* We need to keep track of the server's nonces (these are dummies for
391 static assuan_sock_nonce_t socket_nonce;
392 static assuan_sock_nonce_t socket_nonce_extra;
393 static assuan_sock_nonce_t socket_nonce_browser;
394 static assuan_sock_nonce_t socket_nonce_ssh;
396 /* Value for the listen() backlog argument. We use the same value for
397 * all sockets - 64 is on current Linux half of the default maximum.
398 * Let's try this as default. Change at runtime with --listen-backlog. */
399 static int listen_backlog = 64;
401 /* Default values for options passed to the pinentry. */
402 static char *default_display;
403 static char *default_ttyname;
404 static char *default_ttytype;
405 static char *default_lc_ctype;
406 static char *default_lc_messages;
407 static char *default_xauthority;
409 /* Name of a config file which was last read on startup or, if missing,
410 * the name of the standard config file. Any value here enables the
411 * rereading of the standard config files on SIGHUP. */
412 static char *config_filename;
414 /* Helper to implement --debug-level */
415 static const char *debug_level;
417 /* Keep track of the current log file so that we can avoid updating
418 the log file after a SIGHUP if it didn't changed. Malloced. */
419 static char *current_logfile;
421 /* The handle_tick() function may test whether a parent is still
422 * running. We record the PID of the parent here or -1 if it should
424 static pid_t parent_pid = (pid_t)(-1);
426 /* This flag is true if the inotify mechanism for detecting the
427 * removal of the homedir is active. This flag is used to disable the
428 * alternative but portable stat based check. */
429 static int have_homedir_inotify;
431 /* Depending on how gpg-agent was started, the homedir inotify watch
432 * may not be reliable. This flag is set if we assume that inotify
434 static int reliable_homedir_inotify;
436 /* Number of active connections. */
437 static int active_connections;
439 /* This object is used to dispatch progress messages from Libgcrypt to
440 * the right thread. Given that we will have at max only a few dozen
441 * connections at a time, using a linked list is the easiest way to
443 struct progress_dispatch_s
445 struct progress_dispatch_s *next;
446 /* The control object of the connection. If this is NULL no
447 * connection is associated with this item and it is free for reuse
448 * by new connections. */
451 /* The thread id of (npth_self) of the connection. */
454 /* The callback set by the connection. This is similar to the
455 * Libgcrypt callback but with the control object passed as the
457 void (*cb)(ctrl_t ctrl,
458 const char *what, int printchar,
459 int current, int total);
461 struct progress_dispatch_s *progress_dispatch_list;
470 static char *create_socket_name (char *standard_name, int with_homedir);
471 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
473 assuan_sock_nonce_t *nonce);
474 static void create_directories (void);
476 static void agent_libgcrypt_progress_cb (void *data, const char *what,
478 int current, int total);
479 static void agent_init_default_ctrl (ctrl_t ctrl);
480 static void agent_deinit_default_ctrl (ctrl_t ctrl);
482 static void handle_connections (gnupg_fd_t listen_fd,
483 gnupg_fd_t listen_fd_extra,
484 gnupg_fd_t listen_fd_browser,
485 gnupg_fd_t listen_fd_ssh);
486 static void check_own_socket (void);
487 static int check_for_running_agent (int silent);
489 /* Pth wrapper function definitions. */
490 ASSUAN_SYSTEM_NPTH_IMPL;
497 /* Allocate a string describing a library version by calling a GETFNC.
498 This function is expected to be called only once. GETFNC is
499 expected to have a semantic like gcry_check_version (). */
501 make_libversion (const char *libname, const char *(*getfnc)(const char*))
508 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
512 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
513 strcpy (stpcpy (stpcpy (result, libname), " "), s);
517 /* Return strings describing this program. The case values are
518 described in common/argparse.c:strusage. The values here override
519 the default values given by strusage. */
521 my_strusage (int level)
523 static char *ver_gcry;
528 case 9: p = "GPL-3.0-or-later"; break;
529 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
531 case 13: p = VERSION; break;
532 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
533 case 17: p = PRINTABLE_OS_NAME; break;
534 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
535 reporting address. This is so that we can change the
536 reporting address without breaking the translations. */
537 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
541 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
546 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
548 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
549 "Secret key management for @GNUPG@\n");
559 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
560 only the active debug flags are propagated to the subsystems. With
561 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
562 all flags already set. Note that we don't fail here, because it is
563 important to keep gpg-agent running even after re-reading the
564 options due to a SIGHUP. */
568 int numok = (debug_level && digitp (debug_level));
569 int numlvl = numok? atoi (debug_level) : 0;
573 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
575 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
576 opt.debug = DBG_IPC_VALUE;
577 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
578 opt.debug = DBG_IPC_VALUE;
579 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
580 opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE);
581 else if (!strcmp (debug_level, "guru") || numok)
584 /* Unless the "guru" string has been used we don't want to allow
585 hashing debugging. The rationale is that people tend to
586 select the highest debug value and would then clutter their
587 disk with debug files which may reveal confidential data. */
589 opt.debug &= ~(DBG_HASHING_VALUE);
593 log_error (_("invalid debug-level '%s' given\n"), debug_level);
594 opt.debug = 0; /* Reset debugging, so that prior debug
595 statements won't have an undesired effect. */
598 if (opt.debug && !opt.verbose)
600 if (opt.debug && opt.quiet)
603 if (opt.debug & DBG_MPI_VALUE)
604 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
605 if (opt.debug & DBG_CRYPTO_VALUE )
606 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
607 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
610 parse_debug_flag (NULL, &opt.debug, debug_flags);
614 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
615 the corresponding real name if the socket has been redirected. */
617 remove_socket (char *name, char *redir_name)
630 /* Discover which inherited file descriptors correspond to which
631 * services/sockets offered by gpg-agent, using the LISTEN_FDS and
632 * LISTEN_FDNAMES convention. The understood labels are "ssh",
633 * "extra", and "browser". "std" or other labels will be interpreted
634 * as the standard socket.
636 * This function is designed to log errors when the expected file
637 * descriptors don't make sense, but to do its best to continue to
638 * work even in the face of minor misconfigurations.
640 * For more information on the LISTEN_FDS convention, see
641 * sd_listen_fds(3) on certain Linux distributions.
643 #ifndef HAVE_W32_SYSTEM
645 map_supervised_sockets (gnupg_fd_t *r_fd,
646 gnupg_fd_t *r_fd_extra,
647 gnupg_fd_t *r_fd_browser,
648 gnupg_fd_t *r_fd_ssh)
655 { "ssh", &r_fd_ssh, &socket_name_ssh },
656 { "browser", &r_fd_browser, &socket_name_browser },
657 { "extra", &r_fd_extra, &socket_name_extra },
658 { "std", &r_fd, &socket_name } /* (Must be the last item.) */
665 *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
667 /* Print a warning if LISTEN_PID does not match outr pid. */
668 envvar = getenv ("LISTEN_PID");
670 log_error ("no LISTEN_PID environment variable found in "
671 "--supervised mode (ignoring)\n");
672 else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
673 log_error ("environment variable LISTEN_PID (%lu) does not match"
674 " our pid (%lu) in --supervised mode (ignoring)\n",
675 (unsigned long)strtoul (envvar, NULL, 10),
676 (unsigned long)getpid ());
678 /* Parse LISTEN_FDNAMES into the array FDNAMES. */
679 envvar = getenv ("LISTEN_FDNAMES");
682 fdnames = strtokenize (envvar, ":");
685 log_error ("strtokenize failed: %s\n",
686 gpg_strerror (gpg_error_from_syserror ()));
689 for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
698 /* Parse LISTEN_FDS into fd_count or provide a replacement. */
699 envvar = getenv ("LISTEN_FDS");
701 fd_count = atoi (envvar);
704 log_error ("no LISTEN_FDS environment variable found in --supervised"
705 " mode (relying on LISTEN_FDNAMES instead)\n");
710 log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
711 "found in --supervised mode"
712 " (assuming 1 active descriptor)\n");
718 log_error ("--supervised mode expects at least one file descriptor"
719 " (was told %d, carrying on as though it were 1)\n",
724 /* Assign the descriptors to the return values. */
730 log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
731 " in --supervised mode."
732 " (ignoring all sockets but the first one)\n",
734 if (fstat (3, &statbuf) == -1 && errno ==EBADF)
735 log_fatal ("file descriptor 3 must be valid in --supervised mode"
736 " if LISTEN_FDNAMES is not set\n");
738 socket_name = gnupg_get_socket_name (3);
740 else if (fd_count != nfdnames)
742 log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
743 "LISTEN_FDS (%d) in --supervised mode\n",
751 for (i = 0; i < nfdnames; i++)
753 for (j = 0; j < DIM (tbl); j++)
755 if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
758 if (**tbl[j].fdaddr == -1)
760 name = gnupg_get_socket_name (fd);
763 **tbl[j].fdaddr = fd;
764 *tbl[j].nameaddr = name;
765 log_info ("using fd %d for %s socket (%s)\n",
766 fd, tbl[j].label, name);
770 log_error ("cannot listen on fd %d for %s socket\n",
777 log_error ("cannot listen on more than one %s socket\n",
789 #endif /*!HAVE_W32_SYSTEM*/
792 /* Cleanup code for this program. This is either called has an atexit
793 handler or directly. */
802 deinitialize_module_cache ();
803 if (!is_supervised && !inhibit_socket_removal)
805 remove_socket (socket_name, redir_socket_name);
806 if (opt.extra_socket > 1)
807 remove_socket (socket_name_extra, redir_socket_name_extra);
808 if (opt.browser_socket > 1)
809 remove_socket (socket_name_browser, redir_socket_name_browser);
810 remove_socket (socket_name_ssh, redir_socket_name_ssh);
816 /* Handle options which are allowed to be reset after program start.
817 Return true when the current option in PARGS could be handled and
818 false if not. As a special feature, passing a value of NULL for
819 PARGS, resets the options to the default. REREAD should be set
820 true if it is not the initial option parsing. */
822 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
832 opt.debug_pinentry = 0;
833 opt.pinentry_program = NULL;
834 opt.pinentry_touch_file = NULL;
835 xfree (opt.pinentry_invisible_char);
836 opt.pinentry_invisible_char = NULL;
837 opt.pinentry_timeout = 0;
838 opt.pinentry_formatted_passphrase = 0;
839 opt.scdaemon_program = NULL;
840 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
841 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
842 opt.max_cache_ttl = MAX_CACHE_TTL;
843 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
844 opt.enforce_passphrase_constraints = 0;
845 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
846 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
847 opt.check_passphrase_pattern = NULL;
848 opt.check_sym_passphrase_pattern = NULL;
849 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
850 opt.enable_passphrase_history = 0;
851 opt.enable_extended_key_format = 1;
852 opt.ignore_cache_for_signing = 0;
853 opt.allow_mark_trusted = 1;
854 opt.allow_external_cache = 1;
855 opt.allow_loopback_pinentry = 1;
856 opt.allow_emacs_pinentry = 0;
857 opt.disable_scdaemon = 0;
858 disable_check_own_socket = 0;
859 /* Note: When changing the next line, change also gpgconf_list. */
860 opt.ssh_fingerprint_digest = GCRY_MD_MD5;
862 set_s2k_calibration_time (0); /* Set to default. */
866 switch (pargs->r_opt)
868 case oQuiet: opt.quiet = 1; break;
869 case oVerbose: opt.verbose++; break;
872 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
874 case oDebugAll: opt.debug = ~0; break;
875 case oDebugLevel: debug_level = pargs->r.ret_str; break;
876 case oDebugPinentry: opt.debug_pinentry = 1; break;
880 return 0; /* not handeld */
881 if (!current_logfile || !pargs->r.ret_str
882 || strcmp (current_logfile, pargs->r.ret_str))
884 log_set_file (pargs->r.ret_str);
885 xfree (current_logfile);
886 current_logfile = xtrystrdup (pargs->r.ret_str);
890 case oNoGrab: opt.no_grab |= 1; break;
891 case oGrab: opt.no_grab |= 2; break;
893 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
894 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
895 case oPinentryInvisibleChar:
896 xfree (opt.pinentry_invisible_char);
897 opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
899 case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
900 case oPinentryFormattedPassphrase:
901 opt.pinentry_formatted_passphrase = 1;
903 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
904 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
905 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
907 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
908 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
909 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
910 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
912 case oEnforcePassphraseConstraints:
913 opt.enforce_passphrase_constraints=1;
915 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
916 case oMinPassphraseNonalpha:
917 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
919 case oCheckPassphrasePattern:
920 opt.check_passphrase_pattern = pargs->r.ret_str;
922 case oCheckSymPassphrasePattern:
923 opt.check_sym_passphrase_pattern = pargs->r.ret_str;
925 case oMaxPassphraseDays:
926 opt.max_passphrase_days = pargs->r.ret_ulong;
928 case oEnablePassphraseHistory:
929 opt.enable_passphrase_history = 1;
932 case oEnableExtendedKeyFormat:
933 opt.enable_extended_key_format = 2;
935 case oDisableExtendedKeyFormat:
936 if (opt.enable_extended_key_format != 2)
937 opt.enable_extended_key_format = 0;
940 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
942 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
943 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
945 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
947 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
948 case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
950 case oNoAllowExternalCache: opt.allow_external_cache = 0;
953 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
956 case oSSHFingerprintDigest:
957 i = gcry_md_map_name (pargs->r.ret_str);
959 log_error (_("selected digest algorithm is invalid\n"));
961 opt.ssh_fingerprint_digest = i;
965 opt.s2k_count = pargs->r.ret_ulong;
968 case oS2KCalibration:
969 set_s2k_calibration_time (pargs->r.ret_ulong);
975 return 0; /* not handled */
978 return 1; /* handled */
982 /* Fixup some options after all have been processed. */
984 finalize_rereadable_options (void)
986 /* Hack to allow --grab to override --no-grab. */
987 if ((opt.no_grab & 2))
993 thread_init_once (void)
995 static int npth_initialized = 0;
997 if (!npth_initialized)
1002 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
1003 /* Now that we have set the syscall clamp we need to tell Libgcrypt
1004 * that it should get them from libgpg-error. Note that Libgcrypt
1005 * has already been initialized but at that point nPth was not
1006 * initialized and thus Libgcrypt could not set its system call
1008 gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
1013 initialize_modules (void)
1015 thread_init_once ();
1016 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
1017 initialize_module_cache ();
1018 initialize_module_call_pinentry ();
1019 initialize_module_call_scd ();
1020 initialize_module_trustlist ();
1024 /* The main entry point. */
1026 main (int argc, char **argv )
1028 ARGPARSE_ARGS pargs;
1031 char *last_configname = NULL;
1032 const char *configname = NULL;
1033 int debug_argparser = 0;
1035 int pipe_server = 0;
1039 char *logfile = NULL;
1041 int gpgconf_list = 0;
1043 struct assuan_malloc_hooks malloc_hooks;
1045 early_system_init ();
1047 /* Before we do anything else we save the list of currently open
1048 file descriptors and the signal mask. This info is required to
1049 do the exec call properly. We don't need it on Windows. */
1050 #ifndef HAVE_W32_SYSTEM
1051 startup_fd_list = get_all_open_fds ();
1052 #endif /*!HAVE_W32_SYSTEM*/
1053 #ifdef HAVE_SIGPROCMASK
1054 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
1055 startup_signal_mask_valid = 1;
1056 #endif /*HAVE_SIGPROCMASK*/
1058 /* Set program name etc. */
1059 set_strusage (my_strusage);
1060 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1061 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1062 when adding any stuff between here and the call to INIT_SECMEM()
1063 somewhere after the option parsing */
1064 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
1066 /* Make sure that our subsystems are ready. */
1068 init_common_subsystems (&argc, &argv);
1070 malloc_hooks.malloc = gcry_malloc;
1071 malloc_hooks.realloc = gcry_realloc;
1072 malloc_hooks.free = gcry_free;
1073 assuan_set_malloc_hooks (&malloc_hooks);
1074 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1075 assuan_sock_init ();
1076 assuan_sock_set_system_hooks (ASSUAN_SYSTEM_NPTH);
1077 setup_libassuan_logging (&opt.debug, NULL);
1079 setup_libgcrypt_logging ();
1080 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1081 gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
1083 disable_core_dumps ();
1085 /* Set default options. */
1086 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
1088 shell = getenv ("SHELL");
1089 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1092 /* Record some of the original environment strings. */
1096 static const char *names[] =
1097 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
1100 opt.startup_env = session_env_new ();
1101 if (!opt.startup_env)
1102 err = gpg_error_from_syserror ();
1103 for (idx=0; !err && names[idx]; idx++)
1105 s = getenv (names[idx]);
1107 err = session_env_setenv (opt.startup_env, names[idx], s);
1111 s = gnupg_ttyname (0);
1113 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
1116 log_fatal ("error recording startup environment: %s\n",
1117 gpg_strerror (err));
1119 /* Fixme: Better use the locale function here. */
1120 opt.startup_lc_ctype = getenv ("LC_CTYPE");
1121 if (opt.startup_lc_ctype)
1122 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
1123 opt.startup_lc_messages = getenv ("LC_MESSAGES");
1124 if (opt.startup_lc_messages)
1125 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
1128 /* Check whether we have a config file on the commandline */
1133 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1134 while (gnupg_argparse (NULL, &pargs, opts))
1136 switch (pargs.r_opt)
1144 gnupg_set_homedir (pargs.r.ret_str);
1147 case oDebugQuickRandom:
1148 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
1152 /* Reset the flags. */
1153 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1155 /* Initialize the secure memory. */
1156 gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0);
1160 * Now we are now working under our real uid
1163 gnupg_set_confdir (GNUPG_CONFDIR_SYS, gnupg_sysconfdir ());
1164 gnupg_set_confdir (GNUPG_CONFDIR_USER, gnupg_homedir ());
1170 /* We are re-using the struct, thus the reset flag. We OR the
1171 * flags so that the internal intialized flag won't be cleared. */
1172 pargs.flags |= (ARGPARSE_FLAG_RESET
1173 | ARGPARSE_FLAG_KEEP
1175 | ARGPARSE_FLAG_USER);
1177 while (gnupg_argparser (&pargs, opts, GPG_AGENT_NAME EXTSEP_S "conf"))
1179 if (pargs.r_opt == ARGPARSE_CONFFILE)
1181 if (debug_argparser)
1182 log_info (_("reading options from '%s'\n"),
1183 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1186 xfree (last_configname);
1187 last_configname = xstrdup (pargs.r.ret_str);
1188 configname = last_configname;
1194 if (parse_rereadable_options (&pargs, 0))
1195 continue; /* Already handled */
1196 switch (pargs.r_opt)
1198 case aGPGConfList: gpgconf_list = 1; break;
1199 case aGPGConfTest: gpgconf_list = 2; break;
1200 case aUseStandardSocketP: gpgconf_list = 3; break;
1201 case oBatch: opt.batch=1; break;
1203 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1205 case oNoGreeting: /* Dummy option. */ break;
1206 case oNoVerbose: opt.verbose = 0; break;
1207 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1208 case oNoDetach: nodetach = 1; break;
1209 case oLogFile: logfile = pargs.r.ret_str; break;
1210 case oCsh: csh_style = 1; break;
1211 case oSh: csh_style = 0; break;
1212 case oServer: pipe_server = 1; break;
1213 case oDaemon: is_daemon = 1; break;
1214 case oSupervised: is_supervised = 1; break;
1216 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
1217 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
1218 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
1219 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
1220 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
1222 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
1225 case oUseStandardSocket:
1226 case oNoUseStandardSocket:
1227 obsolete_option (configname, pargs.lineno, "use-standard-socket");
1230 case oFakedSystemTime:
1232 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1233 if (faked_time == (time_t)(-1))
1234 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1235 gnupg_set_time (faked_time, 0);
1239 case oKeepTTY: opt.keep_tty = 1; break;
1240 case oKeepDISPLAY: opt.keep_display = 1; break;
1247 # ifdef HAVE_W32_SYSTEM
1253 opt.extra_socket = 1; /* (1 = points into argv) */
1254 socket_name_extra = pargs.r.ret_str;
1257 case oBrowserSocket:
1258 opt.browser_socket = 1; /* (1 = points into argv) */
1259 socket_name_browser = pargs.r.ret_str;
1262 case oAutoExpandSecmem:
1263 /* Try to enable this option. It will officially only be
1264 * supported by Libgcrypt 1.9 but 1.8.2 already supports it
1265 * on the quiet and thus we use the numeric value value. */
1266 gcry_control (78 /*GCRYCTL_AUTO_EXPAND_SECMEM*/,
1267 (unsigned int)pargs.r.ret_ulong, 0);
1270 case oListenBacklog:
1271 listen_backlog = pargs.r.ret_int;
1274 case oDebugQuickRandom:
1275 /* Only used by the first stage command line parser. */
1279 obsolete_option (configname, pargs.lineno, "write-env-file");
1284 pargs.err = ARGPARSE_PRINT_WARNING;
1286 pargs.err = ARGPARSE_PRINT_ERROR;
1290 gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */
1292 if (!last_configname)
1293 config_filename = make_filename (gnupg_homedir (),
1294 GPG_AGENT_NAME EXTSEP_S "conf",
1298 config_filename = last_configname;
1299 last_configname = NULL;
1302 if (log_get_errorcount(0))
1305 finalize_rereadable_options ();
1307 /* Print a warning if an argument looks like an option. */
1308 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1312 for (i=0; i < argc; i++)
1313 if (argv[i][0] == '-' && argv[i][1] == '-')
1314 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1318 /* gpg-agent usually does not output any messages because it runs in
1319 the background. For log files it is acceptable to have messages
1320 always encoded in utf-8. We switch here to utf-8, so that
1321 commands like --help still give native messages. It is far
1322 easier to switch only once instead of for every message and it
1323 actually helps when more then one thread is active (avoids an
1324 extra copy step). */
1325 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1328 if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
1330 /* We have been called without any command and thus we merely
1331 check whether an agent is already running. We do this right
1332 here so that we don't clobber a logfile with this check but
1333 print the status directly to stderr. */
1336 check_for_running_agent (0);
1342 else if (!opt.extra_socket)
1343 opt.extra_socket = 1;
1344 else if (socket_name_extra
1345 && (!strcmp (socket_name_extra, "none")
1346 || !strcmp (socket_name_extra, "/dev/null")))
1348 /* User requested not to create this socket. */
1349 opt.extra_socket = 0;
1350 socket_name_extra = NULL;
1355 else if (!opt.browser_socket)
1356 opt.browser_socket = 1;
1357 else if (socket_name_browser
1358 && (!strcmp (socket_name_browser, "none")
1359 || !strcmp (socket_name_browser, "/dev/null")))
1361 /* User requested not to create this socket. */
1362 opt.browser_socket = 0;
1363 socket_name_browser = NULL;
1368 if (atexit (cleanup))
1370 log_error ("atexit failed\n");
1375 /* Try to create missing directories. */
1377 create_directories ();
1379 if (debug_wait && pipe_server)
1381 thread_init_once ();
1382 log_debug ("waiting for debugger - my pid is %u .....\n",
1383 (unsigned int)getpid());
1384 gnupg_sleep (debug_wait);
1385 log_debug ("... okay\n");
1388 if (gpgconf_list == 3)
1390 /* We now use the standard socket always - return true for
1391 backward compatibility. */
1394 else if (gpgconf_list == 2)
1396 else if (gpgconf_list)
1400 /* List options and default values in the GPG Conf format. */
1401 filename_esc = percent_escape (config_filename, NULL);
1402 es_printf ("%s-%s.conf:%lu:\"%s\n",
1403 GPGCONF_NAME, GPG_AGENT_NAME,
1404 GC_OPT_FLAG_DEFAULT, filename_esc);
1405 xfree (filename_esc);
1407 es_printf ("verbose:%lu:\n"
1409 "debug-level:%lu:\"none:\n"
1411 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1412 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1413 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1414 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1415 es_printf ("default-cache-ttl:%lu:%d:\n",
1416 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1417 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1418 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1419 es_printf ("max-cache-ttl:%lu:%d:\n",
1420 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1421 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1422 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1423 es_printf ("enforce-passphrase-constraints:%lu:\n",
1424 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1425 es_printf ("min-passphrase-len:%lu:%d:\n",
1426 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1427 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1428 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1429 MIN_PASSPHRASE_NONALPHA);
1430 es_printf ("check-passphrase-pattern:%lu:\n",
1431 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1432 es_printf ("check-sym-passphrase-pattern:%lu:\n",
1433 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1434 es_printf ("max-passphrase-days:%lu:%d:\n",
1435 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1436 MAX_PASSPHRASE_DAYS);
1437 es_printf ("enable-passphrase-history:%lu:\n",
1438 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1439 es_printf ("no-grab:%lu:\n",
1440 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1441 es_printf ("ignore-cache-for-signing:%lu:\n",
1442 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1443 es_printf ("no-allow-external-cache:%lu:\n",
1444 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1445 es_printf ("no-allow-mark-trusted:%lu:\n",
1446 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1447 es_printf ("disable-scdaemon:%lu:\n",
1448 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1449 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1450 es_printf ("ssh-fingerprint-digest:%lu:\"%s:\n",
1451 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, "md5");
1452 #ifdef HAVE_W32_SYSTEM
1453 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1455 es_printf ("no-allow-loopback-pinentry:%lu:\n",
1456 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1457 es_printf ("allow-emacs-pinentry:%lu:\n",
1458 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1459 es_printf ("pinentry-timeout:%lu:0:\n",
1460 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1461 es_printf ("grab:%lu:\n",
1462 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1467 /* Now start with logging to a file if this is desired. */
1470 log_set_file (logfile);
1471 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1472 | GPGRT_LOG_WITH_TIME
1473 | GPGRT_LOG_WITH_PID));
1474 current_logfile = xstrdup (logfile);
1477 /* Make sure that we have a default ttyname. */
1478 if (!default_ttyname && gnupg_ttyname (1))
1479 default_ttyname = xstrdup (gnupg_ttyname (1));
1480 if (!default_ttytype && getenv ("TERM"))
1481 default_ttytype = xstrdup (getenv ("TERM"));
1486 /* This is the simple pipe based server */
1489 initialize_modules ();
1491 ctrl = xtrycalloc (1, sizeof *ctrl);
1494 log_error ("error allocating connection control data: %s\n",
1498 ctrl->session_env = session_env_new ();
1499 if (!ctrl->session_env)
1501 log_error ("error allocating session environment block: %s\n",
1506 agent_init_default_ctrl (ctrl);
1507 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1508 agent_deinit_default_ctrl (ctrl);
1511 else if (is_supervised)
1513 #ifndef HAVE_W32_SYSTEM
1514 gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
1516 initialize_modules ();
1518 /* when supervised and sending logs to stderr, the process
1519 supervisor should handle log entry metadata (pid, name,
1522 log_set_prefix (NULL, 0);
1524 log_info ("%s %s starting in supervised mode.\n",
1525 strusage(11), strusage(13) );
1527 /* See below in "regular server mode" on why we remove certain
1529 if (!opt.keep_display)
1530 gnupg_unsetenv ("DISPLAY");
1531 gnupg_unsetenv ("INSIDE_EMACS");
1533 /* Virtually create the sockets. Note that we use -1 here
1534 * because the whole thing works only on Unix. */
1535 map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
1537 log_fatal ("no standard socket provided\n");
1539 #ifdef HAVE_SIGPROCMASK
1540 if (startup_signal_mask_valid)
1542 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1543 log_error ("error restoring signal mask: %s\n",
1547 log_info ("no saved signal mask\n");
1548 #endif /*HAVE_SIGPROCMASK*/
1550 log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
1551 fd, fd_extra, fd_browser, fd_ssh);
1552 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1553 #endif /*!HAVE_W32_SYSTEM*/
1555 else if (!is_daemon)
1558 { /* Regular server mode */
1560 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1561 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1562 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1563 #ifndef HAVE_W32_SYSTEM
1567 /* Remove the DISPLAY variable so that a pinentry does not
1568 default to a specific display. There is still a default
1569 display when gpg-agent was started using --display or a
1570 client requested this using an OPTION command. Note, that we
1571 don't do this when running in reverse daemon mode (i.e. when
1572 exec the program given as arguments). */
1573 #ifndef HAVE_W32_SYSTEM
1574 if (!opt.keep_display && !argc)
1575 gnupg_unsetenv ("DISPLAY");
1578 /* Remove the INSIDE_EMACS variable so that a pinentry does not
1579 always try to interact with Emacs. The variable is set when
1580 a client requested this using an OPTION command. */
1581 gnupg_unsetenv ("INSIDE_EMACS");
1583 /* Create the sockets. */
1584 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1585 fd = create_server_socket (socket_name, 1, 0,
1586 &redir_socket_name, &socket_nonce);
1588 if (opt.extra_socket)
1590 if (socket_name_extra)
1591 socket_name_extra = create_socket_name (socket_name_extra, 0);
1593 socket_name_extra = create_socket_name
1594 /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1);
1595 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1596 fd_extra = create_server_socket (socket_name_extra, 0, 0,
1597 &redir_socket_name_extra,
1598 &socket_nonce_extra);
1601 if (opt.browser_socket)
1603 if (socket_name_browser)
1604 socket_name_browser = create_socket_name (socket_name_browser, 0);
1606 socket_name_browser= create_socket_name
1607 /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1);
1608 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1609 fd_browser = create_server_socket (socket_name_browser, 0, 0,
1610 &redir_socket_name_browser,
1611 &socket_nonce_browser);
1614 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1615 fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1616 &redir_socket_name_ssh,
1619 /* If we are going to exec a program in the parent, we record
1620 the PID, so that the child may check whether the program is
1623 parent_pid = getpid ();
1627 #ifdef HAVE_W32_SYSTEM
1631 initialize_modules ();
1633 #else /*!HAVE_W32_SYSTEM*/
1636 if (pid == (pid_t)-1)
1638 log_fatal ("fork failed: %s\n", strerror (errno) );
1642 { /* We are the parent */
1643 char *infostr_ssh_sock, *infostr_ssh_valid;
1645 /* Close the socket FD. */
1648 /* The signal mask might not be correct right now and thus
1649 we restore it. That is not strictly necessary but some
1650 programs falsely assume a cleared signal mask. */
1652 #ifdef HAVE_SIGPROCMASK
1653 if (startup_signal_mask_valid)
1655 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1656 log_error ("error restoring signal mask: %s\n",
1660 log_info ("no saved signal mask\n");
1661 #endif /*HAVE_SIGPROCMASK*/
1663 /* Create the SSH info string if enabled. */
1666 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1667 socket_name_ssh) < 0)
1669 log_error ("out of core\n");
1670 kill (pid, SIGTERM);
1673 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1674 (unsigned long)getpid()) < 0)
1676 log_error ("out of core\n");
1677 kill (pid, SIGTERM);
1682 *socket_name = 0; /* Don't let cleanup() remove the socket -
1683 the child should do this from now on */
1684 if (opt.extra_socket)
1685 *socket_name_extra = 0;
1686 if (opt.browser_socket)
1687 *socket_name_browser = 0;
1688 *socket_name_ssh = 0;
1691 { /* Run the program given on the commandline. */
1692 if (ssh_support && (putenv (infostr_ssh_sock)
1693 || putenv (infostr_ssh_valid)))
1695 log_error ("failed to set environment: %s\n",
1697 kill (pid, SIGTERM );
1701 /* Close all the file descriptors except the standard
1702 ones and those open at startup. We explicitly don't
1703 close 0,1,2 in case something went wrong collecting
1705 close_all_fds (3, startup_fd_list);
1707 /* Run the command. */
1708 execvp (argv[0], argv);
1709 log_error ("failed to run the command: %s\n", strerror (errno));
1710 kill (pid, SIGTERM);
1715 /* Print the environment string, so that the caller can use
1716 shell's eval to set it */
1721 *strchr (infostr_ssh_sock, '=') = ' ';
1722 es_printf ("setenv %s;\n", infostr_ssh_sock);
1729 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1735 xfree (infostr_ssh_sock);
1736 xfree (infostr_ssh_valid);
1747 initialize_modules ();
1749 /* Detach from tty and put process into a new session */
1753 unsigned int oldflags;
1755 /* Close stdin, stdout and stderr unless it is the log stream */
1756 for (i=0; i <= 2; i++)
1758 if (!log_test_fd (i) && i != fd )
1761 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1763 log_error ("failed to open '%s': %s\n",
1764 "/dev/null", strerror (errno));
1772 log_error ("setsid() failed: %s\n", strerror(errno) );
1777 log_get_prefix (&oldflags);
1778 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1779 opt.running_detached = 1;
1781 /* Unless we are running with a program given on the command
1782 * line we can assume that the inotify things works and thus
1783 * we can avoid tye regular stat calls. */
1785 reliable_homedir_inotify = 1;
1789 struct sigaction sa;
1791 sa.sa_handler = SIG_IGN;
1792 sigemptyset (&sa.sa_mask);
1794 sigaction (SIGPIPE, &sa, NULL);
1796 #endif /*!HAVE_W32_SYSTEM*/
1798 if (gnupg_chdir (gnupg_daemon_rootdir ()))
1800 log_error ("chdir to '%s' failed: %s\n",
1801 gnupg_daemon_rootdir (), strerror (errno));
1805 log_info ("%s %s started\n", strusage(11), strusage(13) );
1806 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1807 assuan_sock_close (fd);
1814 /* Exit entry point. This function should be called instead of a
1819 /*FIXME: update_random_seed_file();*/
1821 /* We run our cleanup handler because that may close cipher contexts
1822 stored in secure memory and thus this needs to be done before we
1823 explicitly terminate secure memory. */
1827 /* at this time a bit annoying */
1828 if (opt.debug & DBG_MEMSTAT_VALUE)
1830 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1831 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1834 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1836 gcry_control (GCRYCTL_TERM_SECMEM );
1837 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1842 /* This is our callback function for gcrypt progress messages. It is
1843 set once at startup and dispatches progress messages to the
1844 corresponding threads of the agent. */
1846 agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1847 int current, int total)
1849 struct progress_dispatch_s *dispatch;
1850 npth_t mytid = npth_self ();
1854 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1855 if (dispatch->ctrl && dispatch->tid == mytid)
1857 if (dispatch && dispatch->cb)
1858 dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1862 /* If a progress dispatcher callback has been associated with the
1863 * current connection unregister it. */
1865 unregister_progress_cb (void)
1867 struct progress_dispatch_s *dispatch;
1868 npth_t mytid = npth_self ();
1870 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1871 if (dispatch->ctrl && dispatch->tid == mytid)
1875 dispatch->ctrl = NULL;
1876 dispatch->cb = NULL;
1881 /* Setup a progress callback CB for the current connection. Using a
1882 * CB of NULL disables the callback. */
1884 agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1885 int printchar, int current, int total),
1888 struct progress_dispatch_s *dispatch, *firstfree;
1889 npth_t mytid = npth_self ();
1892 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1894 if (dispatch->ctrl && dispatch->tid == mytid)
1896 if (!dispatch->ctrl && !firstfree)
1897 firstfree = dispatch;
1899 if (!dispatch) /* None allocated: Reuse or allocate a new one. */
1903 dispatch = firstfree;
1905 else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1907 dispatch->next = progress_dispatch_list;
1908 progress_dispatch_list = dispatch;
1912 log_error ("error allocating new progress dispatcher slot: %s\n",
1913 gpg_strerror (gpg_error_from_syserror ()));
1916 dispatch->ctrl = ctrl;
1917 dispatch->tid = mytid;
1924 /* Each thread has its own local variables conveyed by a control
1925 structure usually identified by an argument named CTRL. This
1926 function is called immediately after allocating the control
1927 structure. Its purpose is to setup the default values for that
1928 structure. Note that some values may have already been set. */
1930 agent_init_default_ctrl (ctrl_t ctrl)
1932 assert (ctrl->session_env);
1934 /* Note we ignore malloc errors because we can't do much about it
1935 and the request will fail anyway shortly after this
1937 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1938 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1939 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1940 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1941 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1944 xfree (ctrl->lc_ctype);
1945 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1947 if (ctrl->lc_messages)
1948 xfree (ctrl->lc_messages);
1949 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1951 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1955 /* Release all resources allocated by default in the control
1956 structure. This is the counterpart to agent_init_default_ctrl. */
1958 agent_deinit_default_ctrl (ctrl_t ctrl)
1960 unregister_progress_cb ();
1961 session_env_release (ctrl->session_env);
1964 xfree (ctrl->lc_ctype);
1965 if (ctrl->lc_messages)
1966 xfree (ctrl->lc_messages);
1970 /* Because the ssh protocol does not send us information about the
1971 current TTY setting, we use this function to use those from startup
1972 or those explicitly set. This is also used for the restricted mode
1973 where we ignore requests to change the environment. */
1975 agent_copy_startup_env (ctrl_t ctrl)
1977 gpg_error_t err = 0;
1979 const char *name, *value;
1981 while (!err && (name = session_env_list_stdenvnames (&iterator, NULL)))
1983 if ((value = session_env_getenv (opt.startup_env, name)))
1984 err = session_env_setenv (ctrl->session_env, name, value);
1987 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1988 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1989 err = gpg_error_from_syserror ();
1991 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1992 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1993 err = gpg_error_from_syserror ();
1996 log_error ("error setting default session environment: %s\n",
1997 gpg_strerror (err));
2003 /* Reread parts of the configuration. Note, that this function is
2004 obviously not thread-safe and should only be called from the PTH
2007 Fixme: Due to the way the argument parsing works, we create a
2008 memory leak here for all string type arguments. There is currently
2009 no clean way to tell whether the memory for the argument has been
2010 allocated or points into the process' original arguments. Unless
2011 we have a mechanism to tell this, we need to live on with this. */
2013 reread_configuration (void)
2015 ARGPARSE_ARGS pargs;
2019 if (!config_filename)
2020 return; /* No config file. */
2022 twopart = strconcat (GPG_AGENT_NAME EXTSEP_S "conf" PATHSEP_S,
2023 config_filename, NULL);
2025 return; /* Out of core. */
2027 parse_rereadable_options (NULL, 1); /* Start from the default values. */
2029 memset (&pargs, 0, sizeof pargs);
2031 pargs.argc = &dummy;
2032 pargs.flags = (ARGPARSE_FLAG_KEEP
2034 |ARGPARSE_FLAG_USER);
2035 while (gnupg_argparser (&pargs, opts, twopart))
2037 if (pargs.r_opt == ARGPARSE_CONFFILE)
2039 log_info (_("reading options from '%s'\n"),
2040 pargs.r_type? pargs.r.ret_str: "[cmdline]");
2042 else if (pargs.r_opt < -1)
2043 pargs.err = ARGPARSE_PRINT_WARNING;
2044 else /* Try to parse this option - ignore unchangeable ones. */
2045 parse_rereadable_options (&pargs, 1);
2047 gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */
2049 finalize_rereadable_options ();
2054 /* Return the file name of the socket we are using for native
2057 get_agent_socket_name (void)
2059 const char *s = socket_name;
2061 return (s && *s)? s : NULL;
2064 /* Return the file name of the socket we are using for SSH
2067 get_agent_ssh_socket_name (void)
2069 const char *s = socket_name_ssh;
2071 return (s && *s)? s : NULL;
2075 /* Return the number of active connections. */
2077 get_agent_active_connection_count (void)
2079 return active_connections;
2083 /* Under W32, this function returns the handle of the scdaemon
2084 notification event. Calling it the first time creates that
2086 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
2088 get_agent_scd_notify_event (void)
2090 static HANDLE the_event = INVALID_HANDLE_VALUE;
2092 if (the_event == INVALID_HANDLE_VALUE)
2095 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
2097 /* We need to use a manual reset event object due to the way our
2098 w32-pth wait function works: If we would use an automatic
2099 reset event we are not able to figure out which handle has
2100 been signaled because at the time we single out the signaled
2101 handles using WFSO the event has already been reset due to
2103 h = CreateEvent (&sa, TRUE, FALSE, NULL);
2105 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
2106 else if (!DuplicateHandle (GetCurrentProcess(), h,
2107 GetCurrentProcess(), &h2,
2108 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
2110 log_error ("setting synchronize for scd notify event failed: %s\n",
2111 w32_strerror (-1) );
2123 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
2127 /* Create a name for the socket in the home directory as using
2128 STANDARD_NAME. We also check for valid characters as well as
2129 against a maximum allowed length for a unix domain socket is done.
2130 The function terminates the process in case of an error. Returns:
2131 Pointer to an allocated string with the absolute name of the socket
2134 create_socket_name (char *standard_name, int with_homedir)
2139 name = make_filename (gnupg_socketdir (), standard_name, NULL);
2141 name = make_filename (standard_name, NULL);
2142 if (strchr (name, PATHSEP_C))
2144 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
2152 /* Create a Unix domain socket with NAME. Returns the file descriptor
2153 or terminates the process in case of an error. Note that this
2154 function needs to be used for the regular socket first (indicated
2155 by PRIMARY) and only then for the extra and the ssh sockets. If
2156 the socket has been redirected the name of the real socket is
2157 stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
2158 Cygwin compatible socket is created (Windows only). */
2160 create_server_socket (char *name, int primary, int cygwin,
2161 char **r_redir_name, assuan_sock_nonce_t *nonce)
2163 struct sockaddr *addr;
2164 struct sockaddr_un *unaddr;
2169 xfree (*r_redir_name);
2170 *r_redir_name = NULL;
2172 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
2173 if (fd == ASSUAN_INVALID_FD)
2175 log_error (_("can't create socket: %s\n"), strerror (errno));
2176 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2181 assuan_sock_set_flag (fd, "cygwin", 1);
2183 unaddr = xmalloc (sizeof *unaddr);
2184 addr = (struct sockaddr*)unaddr;
2189 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
2191 if (errno == ENAMETOOLONG)
2192 log_error (_("socket name '%s' is too long\n"), name);
2194 log_error ("error preparing socket '%s': %s\n",
2195 name, gpg_strerror (gpg_error_from_syserror ()));
2196 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2202 *r_redir_name = xstrdup (unaddr->sun_path);
2204 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
2208 len = SUN_LEN (unaddr);
2209 rc = assuan_sock_bind (fd, addr, len);
2211 /* Our error code mapping on W32CE returns EEXIST thus we also test
2214 && (errno == EADDRINUSE
2215 #ifdef HAVE_W32_SYSTEM
2220 /* Check whether a gpg-agent is already running. We do this
2221 test only if this is the primary socket. For secondary
2222 sockets we assume that a test for gpg-agent has already been
2223 done and reuse the requested socket. Testing the ssh-socket
2224 is not possible because at this point, though we know the new
2225 Assuan socket, the Assuan server and thus the ssh-agent
2226 server is not yet operational; this would lead to a hang. */
2227 if (primary && !check_for_running_agent (1))
2229 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
2230 log_set_file (NULL);
2231 log_error (_("a gpg-agent is already running - "
2232 "not starting a new one\n"));
2233 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2234 assuan_sock_close (fd);
2238 gnupg_remove (unaddr->sun_path);
2239 rc = assuan_sock_bind (fd, addr, len);
2241 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
2242 log_error (_("error getting nonce for the socket\n"));
2245 /* We use gpg_strerror here because it allows us to get strings
2246 for some W32 socket error codes. */
2247 log_error (_("error binding socket to '%s': %s\n"),
2249 gpg_strerror (gpg_error_from_syserror ()));
2251 assuan_sock_close (fd);
2252 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2257 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
2258 log_error (_("can't set permissions of '%s': %s\n"),
2259 unaddr->sun_path, strerror (errno));
2261 if (listen (FD2INT(fd), listen_backlog ) == -1)
2263 log_error ("listen(fd,%d) failed: %s\n",
2264 listen_backlog, strerror (errno));
2265 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2266 assuan_sock_close (fd);
2272 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
2279 /* Check that the directory for storing the private keys exists and
2280 create it if not. This function won't fail as it is only a
2281 convenience function and not strictly necessary. */
2283 create_private_keys_directory (const char *home)
2286 struct stat statbuf;
2288 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
2289 if (gnupg_stat (fname, &statbuf) && errno == ENOENT)
2291 if (gnupg_mkdir (fname, "-rwx"))
2292 log_error (_("can't create directory '%s': %s\n"),
2293 fname, strerror (errno) );
2294 else if (!opt.quiet)
2295 log_info (_("directory '%s' created\n"), fname);
2297 if (gnupg_chmod (fname, "-rwx"))
2298 log_error (_("can't set permissions of '%s': %s\n"),
2299 fname, strerror (errno));
2303 /* The file exists or another error. Make sure we have sensible
2304 * permissions. We enforce rwx for user but keep existing group
2305 * permissions. Permissions for other are always cleared. */
2306 if (gnupg_chmod (fname, "-rwx...---"))
2307 log_error (_("can't set permissions of '%s': %s\n"),
2308 fname, strerror (errno));
2314 /* Create the directory only if the supplied directory name is the
2315 same as the default one. This way we avoid to create arbitrary
2316 directories when a non-default home directory is used. To cope
2317 with HOME, we compare only the suffix if we see that the default
2318 homedir does start with a tilde. We don't stop here in case of
2319 problems because other functions will throw an error anyway.*/
2321 create_directories (void)
2323 struct stat statbuf;
2324 const char *defhome = standard_homedir ();
2327 home = make_filename (gnupg_homedir (), NULL);
2328 if (gnupg_stat (home, &statbuf))
2330 if (errno == ENOENT)
2333 #ifdef HAVE_W32_SYSTEM
2334 ( !compare_filenames (home, defhome) )
2337 && (strlen (home) >= strlen (defhome+1)
2338 && !strcmp (home + strlen(home)
2339 - strlen (defhome+1), defhome+1)))
2340 || (*defhome != '~' && !strcmp (home, defhome) )
2344 if (gnupg_mkdir (home, "-rwx"))
2345 log_error (_("can't create directory '%s': %s\n"),
2346 home, strerror (errno) );
2350 log_info (_("directory '%s' created\n"), home);
2351 create_private_keys_directory (home);
2356 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
2358 else if ( !S_ISDIR(statbuf.st_mode))
2360 log_error (_("can't use '%s' as home directory\n"), home);
2362 else /* exists and is a directory. */
2364 create_private_keys_directory (home);
2371 /* This is the worker for the ticker. It is called every few seconds
2372 and may only do fast operations. */
2376 static time_t last_minute;
2377 struct stat statbuf;
2380 last_minute = time (NULL);
2382 /* Check whether the scdaemon has died and cleanup in this case. */
2383 agent_scd_check_aliveness ();
2385 /* If we are running as a child of another process, check whether
2386 the parent is still alive and shutdown if not. */
2387 #ifndef HAVE_W32_SYSTEM
2388 if (parent_pid != (pid_t)(-1))
2390 if (kill (parent_pid, 0))
2392 shutdown_pending = 2;
2393 log_info ("parent process died - shutting down\n");
2394 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2399 #endif /*HAVE_W32_SYSTEM*/
2401 /* Code to be run from time to time. */
2402 #if CHECK_OWN_SOCKET_INTERVAL > 0
2403 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
2405 check_own_socket ();
2406 last_minute = time (NULL);
2410 /* Need to check for expired cache entries. */
2411 agent_cache_housekeeping ();
2413 /* Check whether the homedir is still available. */
2414 if (!shutdown_pending
2415 && (!have_homedir_inotify || !reliable_homedir_inotify)
2416 && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2418 shutdown_pending = 1;
2419 log_info ("homedir has been removed - shutting down\n");
2424 /* A global function which allows us to call the reload stuff from
2425 other places too. This is only used when build for W32. */
2427 agent_sighup_action (void)
2429 log_info ("SIGHUP received - "
2430 "re-reading configuration and flushing cache\n");
2432 agent_flush_cache ();
2433 reread_configuration ();
2434 agent_reload_trustlist ();
2435 /* We flush the module name cache so that after installing a
2436 "pinentry" binary that one can be used in case the
2437 "pinentry-basic" fallback was in use. */
2438 gnupg_module_name_flush_some ();
2440 if (opt.disable_scdaemon)
2441 agent_card_killscd ();
2445 /* A helper function to handle SIGUSR2. */
2447 agent_sigusr2_action (void)
2450 log_info ("SIGUSR2 received - updating card event counter\n");
2451 /* Nothing to check right now. We only increment a counter. */
2452 bump_card_eventcounter ();
2456 #ifndef HAVE_W32_SYSTEM
2457 /* The signal handler for this program. It is expected to be run in
2458 its own thread and not in the context of a signal handler. */
2460 handle_signal (int signo)
2464 #ifndef HAVE_W32_SYSTEM
2466 agent_sighup_action ();
2470 log_info ("SIGUSR1 received - printing internal information:\n");
2471 /* Fixme: We need to see how to integrate pth dumping into our
2473 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2474 agent_query_dump_state ();
2475 agent_scd_dump_state ();
2479 agent_sigusr2_action ();
2483 if (!shutdown_pending)
2484 log_info ("SIGTERM received - shutting down ...\n");
2486 log_info ("SIGTERM received - still %i open connections\n",
2487 active_connections);
2489 if (shutdown_pending > 2)
2491 log_info ("shutdown forced\n");
2492 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2499 log_info ("SIGINT received - immediate shutdown\n");
2500 log_info( "%s %s stopped\n", strusage(11), strusage(13));
2506 log_info ("signal %d received - no action defined\n", signo);
2511 /* Check the nonce on a new connection. This is a NOP unless we
2512 are using our Unix domain socket emulation under Windows. */
2514 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2516 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2518 log_info (_("error reading nonce on fd %d: %s\n"),
2519 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2520 assuan_sock_close (ctrl->thread_startup.fd);
2529 #ifdef HAVE_W32_SYSTEM
2530 /* The window message processing function for Putty. Warning: This
2531 code runs as a native Windows thread. Use of our own functions
2532 needs to be bracket with pth_leave/pth_enter. */
2533 static LRESULT CALLBACK
2534 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2538 COPYDATASTRUCT *cds;
2539 const char *mapfile;
2544 PSECURITY_DESCRIPTOR psd = NULL;
2547 if (msg != WM_COPYDATA)
2549 return DefWindowProc (hwnd, msg, wparam, lparam);
2552 cds = (COPYDATASTRUCT*)lparam;
2553 if (cds->dwData != PUTTY_IPC_MAGIC)
2554 return 0; /* Ignore data with the wrong magic. */
2555 mapfile = cds->lpData;
2556 if (!cds->cbData || mapfile[cds->cbData - 1])
2557 return 0; /* Ignore empty and non-properly terminated strings. */
2562 log_debug ("ssh map file '%s'", mapfile);
2566 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2570 log_debug ("ssh map handle %p\n", maphd);
2574 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2579 mysid = w32_get_user_sid ();
2582 log_error ("error getting my sid\n");
2586 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2587 OWNER_SECURITY_INFORMATION,
2588 &mapsid, NULL, NULL, NULL,
2592 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2600 if (!ConvertSidToStringSid (mysid, &sidstr))
2602 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2604 if (!ConvertSidToStringSid (mapsid, &sidstr))
2606 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2610 if (!EqualSid (mysid, mapsid))
2612 log_error ("ssh map file has a non-matching sid\n");
2616 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2618 log_debug ("ssh IPC buffer at %p\n", data);
2622 /* log_printhex (data, 20, "request:"); */
2624 ctrl = xtrycalloc (1, sizeof *ctrl);
2627 log_error ("error allocating connection control data: %s\n",
2631 ctrl->session_env = session_env_new ();
2632 if (!ctrl->session_env)
2634 log_error ("error allocating session environment block: %s\n",
2639 agent_init_default_ctrl (ctrl);
2640 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2641 ret = 1; /* Valid ssh message has been constructed. */
2642 agent_deinit_default_ctrl (ctrl);
2643 /* log_printhex (data, 20, " reply:"); */
2648 UnmapViewOfFile (data);
2653 CloseHandle (maphd);
2659 #endif /*HAVE_W32_SYSTEM*/
2662 #ifdef HAVE_W32_SYSTEM
2663 /* The thread handling Putty's IPC requests. */
2665 putty_message_thread (void *arg)
2667 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2668 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2675 log_info ("putty message loop thread started\n");
2677 /* The message loop runs as thread independent from our nPth system.
2678 This also means that we need to make sure that we switch back to
2679 our system before calling any no-windows function. */
2682 /* First create a window to make sure that a message queue exists
2684 if (!RegisterClass (&wndwclass))
2687 log_error ("error registering Pageant window class");
2690 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2692 HWND_MESSAGE, /* hWndParent */
2693 NULL, /* hWndMenu */
2694 NULL, /* hInstance */
2699 log_error ("error creating Pageant window");
2703 while (GetMessage(&msg, NULL, 0, 0))
2705 TranslateMessage(&msg);
2706 DispatchMessage(&msg);
2713 log_info ("putty message loop thread stopped\n");
2716 #endif /*HAVE_W32_SYSTEM*/
2720 do_start_connection_thread (ctrl_t ctrl)
2722 active_connections++;
2723 agent_init_default_ctrl (ctrl);
2724 if (opt.verbose && !DBG_IPC)
2725 log_info (_("handler 0x%lx for fd %d started\n"),
2726 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2728 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2729 if (opt.verbose && !DBG_IPC)
2730 log_info (_("handler 0x%lx for fd %d terminated\n"),
2731 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2733 agent_deinit_default_ctrl (ctrl);
2735 active_connections--;
2740 /* This is the standard connection thread's main function. */
2742 start_connection_thread_std (void *arg)
2746 if (check_nonce (ctrl, &socket_nonce))
2748 log_error ("handler 0x%lx nonce check FAILED\n",
2749 (unsigned long) npth_self());
2753 return do_start_connection_thread (ctrl);
2757 /* This is the extra socket connection thread's main function. */
2759 start_connection_thread_extra (void *arg)
2763 if (check_nonce (ctrl, &socket_nonce_extra))
2765 log_error ("handler 0x%lx nonce check FAILED\n",
2766 (unsigned long) npth_self());
2770 ctrl->restricted = 1;
2771 return do_start_connection_thread (ctrl);
2775 /* This is the browser socket connection thread's main function. */
2777 start_connection_thread_browser (void *arg)
2781 if (check_nonce (ctrl, &socket_nonce_browser))
2783 log_error ("handler 0x%lx nonce check FAILED\n",
2784 (unsigned long) npth_self());
2788 ctrl->restricted = 2;
2789 return do_start_connection_thread (ctrl);
2793 /* This is the ssh connection thread's main function. */
2795 start_connection_thread_ssh (void *arg)
2799 if (check_nonce (ctrl, &socket_nonce_ssh))
2802 active_connections++;
2803 agent_init_default_ctrl (ctrl);
2805 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2806 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2808 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2810 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2811 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2813 agent_deinit_default_ctrl (ctrl);
2815 active_connections--;
2820 /* Connection handler loop. Wait for connection requests and spawn a
2821 thread after accepting a connection. */
2823 handle_connections (gnupg_fd_t listen_fd,
2824 gnupg_fd_t listen_fd_extra,
2825 gnupg_fd_t listen_fd_browser,
2826 gnupg_fd_t listen_fd_ssh)
2830 struct sockaddr_un paddr;
2832 fd_set fdset, read_fdset;
2837 struct timespec abstime;
2838 struct timespec curtime;
2839 struct timespec timeout;
2840 #ifdef HAVE_W32_SYSTEM
2842 unsigned int events_set;
2844 int sock_inotify_fd = -1;
2845 int home_inotify_fd = -1;
2848 void *(*func) (void *arg);
2851 { "std", start_connection_thread_std },
2852 { "extra", start_connection_thread_extra },
2853 { "browser", start_connection_thread_browser },
2854 { "ssh", start_connection_thread_ssh }
2858 ret = npth_attr_init(&tattr);
2860 log_fatal ("error allocating thread attributes: %s\n",
2862 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2864 #ifndef HAVE_W32_SYSTEM
2866 npth_sigev_add (SIGHUP);
2867 npth_sigev_add (SIGUSR1);
2868 npth_sigev_add (SIGUSR2);
2869 npth_sigev_add (SIGINT);
2870 npth_sigev_add (SIGTERM);
2873 # ifdef HAVE_W32CE_SYSTEM
2874 /* Use a dummy event. */
2876 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2878 events[0] = get_agent_scd_notify_event ();
2879 events[1] = INVALID_HANDLE_VALUE;
2883 if (disable_check_own_socket)
2884 sock_inotify_fd = -1;
2885 else if ((err = gnupg_inotify_watch_socket (&sock_inotify_fd, socket_name)))
2887 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2888 log_info ("error enabling daemon termination by socket removal: %s\n",
2889 gpg_strerror (err));
2892 if (disable_check_own_socket)
2893 home_inotify_fd = -1;
2894 else if ((err = gnupg_inotify_watch_delete_self (&home_inotify_fd,
2897 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2898 log_info ("error enabling daemon termination by homedir removal: %s\n",
2899 gpg_strerror (err));
2902 have_homedir_inotify = 1;
2904 /* On Windows we need to fire up a separate thread to listen for
2905 requests from Putty (an SSH client), so we can replace Putty's
2906 Pageant (its ssh-agent implementation). */
2907 #ifdef HAVE_W32_SYSTEM
2912 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2915 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2918 #endif /*HAVE_W32_SYSTEM*/
2920 /* Set a flag to tell call-scd.c that it may enable event
2922 opt.sigusr2_enabled = 1;
2925 FD_SET (FD2INT (listen_fd), &fdset);
2926 nfd = FD2INT (listen_fd);
2927 if (listen_fd_extra != GNUPG_INVALID_FD)
2929 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2930 if (FD2INT (listen_fd_extra) > nfd)
2931 nfd = FD2INT (listen_fd_extra);
2933 if (listen_fd_browser != GNUPG_INVALID_FD)
2935 FD_SET ( FD2INT(listen_fd_browser), &fdset);
2936 if (FD2INT (listen_fd_browser) > nfd)
2937 nfd = FD2INT (listen_fd_browser);
2939 if (listen_fd_ssh != GNUPG_INVALID_FD)
2941 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2942 if (FD2INT (listen_fd_ssh) > nfd)
2943 nfd = FD2INT (listen_fd_ssh);
2945 if (sock_inotify_fd != -1)
2947 FD_SET (sock_inotify_fd, &fdset);
2948 if (sock_inotify_fd > nfd)
2949 nfd = sock_inotify_fd;
2951 if (home_inotify_fd != -1)
2953 FD_SET (home_inotify_fd, &fdset);
2954 if (home_inotify_fd > nfd)
2955 nfd = home_inotify_fd;
2958 listentbl[0].l_fd = listen_fd;
2959 listentbl[1].l_fd = listen_fd_extra;
2960 listentbl[2].l_fd = listen_fd_browser;
2961 listentbl[3].l_fd = listen_fd_ssh;
2963 npth_clock_gettime (&abstime);
2964 abstime.tv_sec += TIMERTICK_INTERVAL;
2968 /* Shutdown test. */
2969 if (shutdown_pending)
2971 if (active_connections == 0)
2974 /* Do not accept new connections but keep on running the
2975 * loop to cope with the timer events.
2977 * Note that we do not close the listening socket because a
2978 * client trying to connect to that socket would instead
2979 * restart a new dirmngr instance - which is unlikely the
2980 * intention of a shutdown. */
2983 if (sock_inotify_fd != -1)
2985 FD_SET (sock_inotify_fd, &fdset);
2986 nfd = sock_inotify_fd;
2988 if (home_inotify_fd != -1)
2990 FD_SET (home_inotify_fd, &fdset);
2991 if (home_inotify_fd > nfd)
2992 nfd = home_inotify_fd;
2996 /* POSIX says that fd_set should be implemented as a structure,
2997 thus a simple assignment is fine to copy the entire set. */
3000 npth_clock_gettime (&curtime);
3001 if (!(npth_timercmp (&curtime, &abstime, <)))
3005 npth_clock_gettime (&abstime);
3006 abstime.tv_sec += TIMERTICK_INTERVAL;
3008 npth_timersub (&abstime, &curtime, &timeout);
3010 #ifndef HAVE_W32_SYSTEM
3011 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
3012 npth_sigev_sigmask ());
3013 saved_errno = errno;
3017 while (npth_sigev_get_pending (&signo))
3018 handle_signal (signo);
3021 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
3022 events, &events_set);
3023 saved_errno = errno;
3025 /* This is valid even if npth_eselect returns an error. */
3027 agent_sigusr2_action ();
3030 if (ret == -1 && saved_errno != EINTR)
3032 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
3033 strerror (saved_errno));
3038 /* Interrupt or timeout. Will be handled when calculating the
3042 /* The inotify fds are set even when a shutdown is pending (see
3043 * above). So we must handle them in any case. To avoid that
3044 * they trigger a second time we close them immediately. */
3045 if (sock_inotify_fd != -1
3046 && FD_ISSET (sock_inotify_fd, &read_fdset)
3047 && gnupg_inotify_has_name (sock_inotify_fd, GPG_AGENT_SOCK_NAME))
3049 shutdown_pending = 1;
3050 close (sock_inotify_fd);
3051 sock_inotify_fd = -1;
3052 log_info ("socket file has been removed - shutting down\n");
3055 if (home_inotify_fd != -1
3056 && FD_ISSET (home_inotify_fd, &read_fdset))
3058 shutdown_pending = 1;
3059 close (home_inotify_fd);
3060 home_inotify_fd = -1;
3061 log_info ("homedir has been removed - shutting down\n");
3064 if (!shutdown_pending)
3070 for (idx=0; idx < DIM(listentbl); idx++)
3072 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
3074 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
3077 plen = sizeof paddr;
3078 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
3079 (struct sockaddr *)&paddr, &plen));
3080 if (fd == GNUPG_INVALID_FD)
3082 log_error ("accept failed for %s: %s\n",
3083 listentbl[idx].name, strerror (errno));
3085 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
3087 log_error ("error allocating connection data for %s: %s\n",
3088 listentbl[idx].name, strerror (errno) );
3089 assuan_sock_close (fd);
3091 else if ( !(ctrl->session_env = session_env_new ()))
3093 log_error ("error allocating session env block for %s: %s\n",
3094 listentbl[idx].name, strerror (errno) );
3096 assuan_sock_close (fd);
3100 ctrl->thread_startup.fd = fd;
3101 ret = npth_create (&thread, &tattr,
3102 listentbl[idx].func, ctrl);
3105 log_error ("error spawning connection handler for %s:"
3106 " %s\n", listentbl[idx].name, strerror (ret));
3107 assuan_sock_close (fd);
3115 if (sock_inotify_fd != -1)
3116 close (sock_inotify_fd);
3117 if (home_inotify_fd != -1)
3118 close (home_inotify_fd);
3120 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
3121 npth_attr_destroy (&tattr);
3126 /* Helper for check_own_socket. */
3128 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
3130 membuf_t *mb = opaque;
3131 put_membuf (mb, buffer, length);
3136 /* The thread running the actual check. We need to run this in a
3137 separate thread so that check_own_thread can be called from the
3140 check_own_socket_thread (void *arg)
3143 char *sockname = arg;
3144 assuan_context_t ctx = NULL;
3148 check_own_socket_running++;
3150 rc = assuan_new (&ctx);
3153 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
3156 assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
3158 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3161 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
3165 init_membuf (&mb, 100);
3166 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
3167 NULL, NULL, NULL, NULL);
3168 put_membuf (&mb, "", 1);
3169 buffer = get_membuf (&mb, NULL);
3172 log_error ("sending command \"%s\" to my own socket failed: %s\n",
3173 "GETINFO pid", gpg_strerror (rc));
3176 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
3178 log_error ("socket is now serviced by another server\n");
3181 else if (opt.verbose > 1)
3182 log_error ("socket is still served by this server\n");
3189 assuan_release (ctx);
3192 /* We may not remove the socket as it is now in use by another
3194 inhibit_socket_removal = 1;
3195 shutdown_pending = 2;
3196 log_info ("this process is useless - shutting down\n");
3198 check_own_socket_running--;
3203 /* Check whether we are still listening on our own socket. In case
3204 another gpg-agent process started after us has taken ownership of
3205 our socket, we would linger around without any real task. Thus we
3206 better check once in a while whether we are really needed. */
3208 check_own_socket (void)
3215 if (disable_check_own_socket)
3218 if (check_own_socket_running || shutdown_pending)
3219 return; /* Still running or already shutting down. */
3221 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3223 return; /* Out of memory. */
3225 err = npth_attr_init (&tattr);
3228 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3229 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
3231 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
3232 npth_attr_destroy (&tattr);
3237 /* Figure out whether an agent is available and running. Prints an
3238 error if not. If SILENT is true, no messages are printed.
3239 Returns 0 if the agent is running. */
3241 check_for_running_agent (int silent)
3245 assuan_context_t ctx = NULL;
3247 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3249 return gpg_error_from_syserror ();
3251 err = assuan_new (&ctx);
3253 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3258 log_error (_("no gpg-agent running in this session\n"));
3261 assuan_release (ctx);
3265 if (!opt.quiet && !silent)
3266 log_info ("gpg-agent running and available\n");
3268 assuan_release (ctx);