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
33 #ifdef HAVE_W32_SYSTEM
35 # define WINVER 0x0500 /* Same as in common/sysutils.c */
37 # ifdef HAVE_WINSOCK2_H
38 # include <winsock2.h>
42 #else /*!HAVE_W32_SYSTEM*/
43 # include <sys/socket.h>
45 #endif /*!HAVE_W32_SYSTEM*/
52 #define INCLUDED_BY_MAIN_MODULE 1
53 #define GNUPG_COMMON_NEED_AFLOCAL
55 #include <assuan.h> /* Malloc hooks and socket wrappers. */
57 #include "../common/i18n.h"
58 #include "../common/sysutils.h"
59 #include "../common/gc-opt-flags.h"
60 #include "../common/exechelp.h"
61 #include "../common/asshelp.h"
62 #include "../common/comopt.h"
63 #include "../common/init.h"
66 enum cmd_and_opt_values
97 oPinentryInvisibleChar,
99 oPinentryFormattedPassphrase,
112 oEnforcePassphraseConstraints,
114 oMinPassphraseNonalpha,
115 oCheckPassphrasePattern,
116 oCheckSymPassphrasePattern,
118 oEnablePassphraseHistory,
121 oNoUseStandardSocket,
126 oIgnoreCacheForSigning,
131 oAllowPresetPassphrase,
132 oAllowLoopbackPinentry,
133 oNoAllowLoopbackPinentry,
134 oNoAllowExternalCache,
139 oSSHFingerprintDigest,
141 oWin32OpenSSHSupport,
143 oDisableCheckOwnSocket,
157 # define ENAMETOOLONG EINVAL
160 static gpgrt_opt_t opts[] = {
162 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
163 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
164 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
167 ARGPARSE_header (NULL, N_("Options used for startup")),
169 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
170 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
171 #ifndef HAVE_W32_SYSTEM
172 ARGPARSE_s_n (oSupervised, "supervised", "@"),
174 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
175 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
176 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
177 ARGPARSE_s_n (oStealSocket, "steal-socket", "@"),
178 ARGPARSE_s_s (oDisplay, "display", "@"),
179 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
180 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
181 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
182 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
183 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
184 ARGPARSE_s_s (oHomedir, "homedir", "@"),
185 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
186 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
187 ARGPARSE_s_i (oInactivityTimeout, "inactivity-timeout", "@"),
189 ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
191 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
192 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
193 ARGPARSE_s_s (oDebug, "debug", "@"),
194 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
195 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
196 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
197 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
198 ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
199 ARGPARSE_s_s (oLogFile, "log-file",
200 /* */ N_("|FILE|write server mode logs to FILE")),
203 ARGPARSE_header ("Configuration",
204 N_("Options controlling the configuration")),
206 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
207 /* */ N_("do not use the SCdaemon") ),
208 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
209 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
210 ARGPARSE_s_s (oTpm2daemonProgram, "tpm2daemon-program",
211 /* */ N_("|PGM|use PGM as the tpm2daemon program") ),
212 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
214 ARGPARSE_s_s (oExtraSocket, "extra-socket",
215 /* */ N_("|NAME|accept some commands via NAME")),
217 ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
218 ARGPARSE_s_n (oKeepTTY, "keep-tty",
219 /* */ N_("ignore requests to change the TTY")),
220 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
221 /* */ N_("ignore requests to change the X display")),
222 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
223 ARGPARSE_s_s (oSSHFingerprintDigest, "ssh-fingerprint-digest",
224 N_("|ALGO|use ALGO to show ssh fingerprints")),
225 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
226 #ifdef HAVE_W32_SYSTEM
227 /* */ N_("enable putty support")
232 ARGPARSE_o_s (oWin32OpenSSHSupport, "enable-win32-openssh-support",
233 #ifdef HAVE_W32_SYSTEM
234 /* */ N_("enable Win32-OpenSSH support")
239 ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
240 ARGPARSE_op_u (oAutoExpandSecmem, "auto-expand-secmem", "@"),
241 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
244 ARGPARSE_header ("Security", N_("Options controlling the security")),
246 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
247 N_("|N|expire cached PINs after N seconds")),
248 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh",
249 /* */ N_("|N|expire SSH keys after N seconds")),
250 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl",
251 /* */ N_("|N|set maximum PIN cache lifetime to N seconds")),
252 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh",
253 /* */ N_("|N|set maximum SSH key lifetime to N seconds")),
254 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
255 /* */ N_("do not use the PIN cache when signing")),
256 ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
257 /* */ N_("disallow the use of an external password cache")),
258 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
259 /* */ N_("disallow clients to mark keys as \"trusted\"")),
260 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
261 ARGPARSE_s_n (oNoUserTrustlist, "no-user-trustlist", "@"),
262 ARGPARSE_s_s (oSysTrustlistName, "sys-trustlist-name", "@"),
263 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
264 /* */ N_("allow presetting passphrase")),
265 ARGPARSE_s_u (oS2KCount, "s2k-count", "@"),
266 ARGPARSE_s_u (oS2KCalibration, "s2k-calibration", "@"),
268 ARGPARSE_header ("Passphrase policy",
269 N_("Options enforcing a passphrase policy")),
271 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
272 N_("do not allow bypassing the passphrase policy")),
273 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len",
274 N_("|N|set minimal required length for new passphrases to N")),
275 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha",
276 N_("|N|require at least N non-alpha"
277 " characters for a new passphrase")),
278 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern",
279 N_("|FILE|check new passphrases against pattern in FILE")),
280 ARGPARSE_s_s (oCheckSymPassphrasePattern, "check-sym-passphrase-pattern",
282 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days",
283 N_("|N|expire the passphrase after N days")),
284 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history",
285 N_("do not allow the reuse of old passphrases")),
288 ARGPARSE_header ("Pinentry", N_("Options controlling the PIN-Entry")),
290 ARGPARSE_s_n (oBatch, "batch", N_("never use the PIN-entry")),
291 ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
292 N_("disallow caller to override the pinentry")),
293 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
294 ARGPARSE_s_n (oGrab, "grab", N_("let PIN-Entry grab keyboard and mouse")),
295 ARGPARSE_s_n (oNoGrab, "no-grab", "@"),
296 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
297 N_("|PGM|use PGM as the PIN-Entry program")),
298 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
299 ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
300 ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout",
301 N_("|N|set the Pinentry timeout to N seconds")),
302 ARGPARSE_s_n (oPinentryFormattedPassphrase, "pinentry-formatted-passphrase",
304 ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
305 N_("allow passphrase to be prompted through Emacs")),
308 /* Dummy options for backward compatibility. */
309 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
310 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
311 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
314 ARGPARSE_s_n (oNoop, "disable-extended-key-format", "@"),
315 ARGPARSE_s_n (oNoop, "enable-extended-key-format", "@"),
317 ARGPARSE_end () /* End of list */
321 /* The list of supported debug flags. */
322 static struct debug_flags_s debug_flags [] =
324 { DBG_MPI_VALUE , "mpi" },
325 { DBG_CRYPTO_VALUE , "crypto" },
326 { DBG_MEMORY_VALUE , "memory" },
327 { DBG_CACHE_VALUE , "cache" },
328 { DBG_MEMSTAT_VALUE, "memstat" },
329 { DBG_HASHING_VALUE, "hashing" },
330 { DBG_IPC_VALUE , "ipc" },
331 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
336 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
337 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
338 #define MAX_CACHE_TTL (120*60) /* 2 hours */
339 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
340 #define MIN_PASSPHRASE_LEN (8)
341 #define MIN_PASSPHRASE_NONALPHA (1)
342 #define MAX_PASSPHRASE_DAYS (0)
344 /* The timer tick used for housekeeping stuff. Note that on Windows
345 * we use a SetWaitableTimer seems to signal earlier than about 2
346 * seconds. Thus we use 4 seconds on all platforms.
347 * CHECK_OWN_SOCKET_INTERVAL defines how often we check
348 * our own socket in standard socket mode. If that value is 0 we
349 * don't check at all. All values are in seconds. */
350 #define TIMERTICK_INTERVAL (4)
351 #define CHECK_OWN_SOCKET_INTERVAL (60)
354 /* Flag indicating that the ssh-agent subsystem has been enabled. */
355 static int ssh_support;
357 #ifdef HAVE_W32_SYSTEM
358 /* Flag indicating that support for Putty has been enabled. */
359 static int putty_support;
360 /* A magic value used with WM_COPYDATA. */
361 #define PUTTY_IPC_MAGIC 0x804e50ba
362 /* To avoid surprises we limit the size of the mapped IPC file to this
363 value. Putty currently (0.62) uses 8k, thus 16k should be enough
364 for the foreseeable future. */
365 #define PUTTY_IPC_MAXLEN 16384
367 /* Path to the pipe, which handles requests from Win32-OpenSSH. */
368 static const char *win32_openssh_support;
369 #define W32_DEFAILT_AGENT_PIPE_NAME "\\\\.\\pipe\\openssh-ssh-agent"
370 #endif /*HAVE_W32_SYSTEM*/
372 /* The list of open file descriptors at startup. Note that this list
373 * has been allocated using the standard malloc. */
374 #ifndef HAVE_W32_SYSTEM
375 static int *startup_fd_list;
378 /* The signal mask at startup and a flag telling whether it is valid. */
379 #ifdef HAVE_SIGPROCMASK
380 static sigset_t startup_signal_mask;
381 static int startup_signal_mask_valid;
384 /* Flag to indicate that a shutdown was requested. */
385 static int shutdown_pending;
387 /* Counter for the currently running own socket checks. */
388 static int check_own_socket_running;
390 /* Flags to indicate that check_own_socket shall not be called. */
391 static int disable_check_own_socket;
393 /* Flag indicating that we are in supervised mode. */
394 static int is_supervised;
396 /* Flag indicating to start the daemon even if one already runs. */
397 static int steal_socket;
399 /* Flag to inhibit socket removal in cleanup. */
400 static int inhibit_socket_removal;
402 /* It is possible that we are currently running under setuid permissions */
403 static int maybe_setuid = 1;
405 /* Name of the communication socket used for native gpg-agent
406 requests. The second variable is either NULL or a malloced string
407 with the real socket name in case it has been redirected. */
408 static char *socket_name;
409 static char *redir_socket_name;
411 /* Name of the optional extra socket used for native gpg-agent requests. */
412 static char *socket_name_extra;
413 static char *redir_socket_name_extra;
415 /* Name of the optional browser socket used for native gpg-agent requests. */
416 static char *socket_name_browser;
417 static char *redir_socket_name_browser;
419 /* Name of the communication socket used for ssh-agent protocol. */
420 static char *socket_name_ssh;
421 static char *redir_socket_name_ssh;
423 /* We need to keep track of the server's nonces (these are dummies for
425 static assuan_sock_nonce_t socket_nonce;
426 static assuan_sock_nonce_t socket_nonce_extra;
427 static assuan_sock_nonce_t socket_nonce_browser;
428 static assuan_sock_nonce_t socket_nonce_ssh;
430 /* Value for the listen() backlog argument. We use the same value for
431 * all sockets - 64 is on current Linux half of the default maximum.
432 * Let's try this as default. Change at runtime with --listen-backlog. */
433 static int listen_backlog = 64;
435 /* Default values for options passed to the pinentry. */
436 static char *default_display;
437 static char *default_ttyname;
438 static char *default_ttytype;
439 static char *default_lc_ctype;
440 static char *default_lc_messages;
441 static char *default_xauthority;
443 /* Name of a config file which was last read on startup or if missing
444 * the name of the standard config file. Any value here enabled the
445 * rereading of the standard config files on SIGHUP. */
446 static char *config_filename;
448 /* Helper to implement --debug-level */
449 static const char *debug_level;
451 /* Keep track of the current log file so that we can avoid updating
452 the log file after a SIGHUP if it didn't changed. Malloced. */
453 static char *current_logfile;
455 /* The handle_tick() function may test whether a parent is still
456 * running. We record the PID of the parent here or -1 if it should
458 static pid_t parent_pid = (pid_t)(-1);
460 /* This flag is true if the inotify mechanism for detecting the
461 * removal of the homedir is active. This flag is used to disable the
462 * alternative but portable stat based check. */
463 static int have_homedir_inotify;
465 /* Depending on how gpg-agent was started, the homedir inotify watch
466 * may not be reliable. This flag is set if we assume that inotify
468 static int reliable_homedir_inotify;
470 /* Number of active connections. */
471 static int active_connections;
473 /* This object is used to dispatch progress messages from Libgcrypt to
474 * the right thread. Given that we will have at max only a few dozen
475 * connections at a time, using a linked list is the easiest way to
477 struct progress_dispatch_s
479 struct progress_dispatch_s *next;
480 /* The control object of the connection. If this is NULL no
481 * connection is associated with this item and it is free for reuse
482 * by new connections. */
485 /* The thread id of (npth_self) of the connection. */
488 /* The callback set by the connection. This is similar to the
489 * Libgcrypt callback but with the control object passed as the
491 void (*cb)(ctrl_t ctrl,
492 const char *what, int printchar,
493 int current, int total);
495 struct progress_dispatch_s *progress_dispatch_list;
504 static char *create_socket_name (char *standard_name, int with_homedir);
505 static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
507 assuan_sock_nonce_t *nonce);
508 static void create_directories (void);
510 static void agent_libgcrypt_progress_cb (void *data, const char *what,
512 int current, int total);
513 static void agent_init_default_ctrl (ctrl_t ctrl);
514 static void agent_deinit_default_ctrl (ctrl_t ctrl);
516 static void handle_connections (gnupg_fd_t listen_fd,
517 gnupg_fd_t listen_fd_extra,
518 gnupg_fd_t listen_fd_browser,
519 gnupg_fd_t listen_fd_ssh);
520 static void check_own_socket (void);
521 static int check_for_running_agent (int silent);
523 /* Pth wrapper function definitions. */
524 ASSUAN_SYSTEM_NPTH_IMPL;
531 /* Allocate a string describing a library version by calling a GETFNC.
532 This function is expected to be called only once. GETFNC is
533 expected to have a semantic like gcry_check_version (). */
535 make_libversion (const char *libname, const char *(*getfnc)(const char*))
542 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
546 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
547 strcpy (stpcpy (stpcpy (result, libname), " "), s);
551 /* Return strings describing this program. The case values are
552 described in common/argparse.c:strusage. The values here override
553 the default values given by strusage. */
555 my_strusage (int level)
557 static char *ver_gcry;
562 case 9: p = "GPL-3.0-or-later"; break;
563 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
565 case 13: p = VERSION; break;
566 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
567 case 17: p = PRINTABLE_OS_NAME; break;
568 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
569 reporting address. This is so that we can change the
570 reporting address without breaking the translations. */
571 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
575 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
580 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
582 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
583 "Secret key management for @GNUPG@\n");
593 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
594 only the active debug flags are propagated to the subsystems. With
595 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
596 all flags already set. Note that we don't fail here, because it is
597 important to keep gpg-agent running even after re-reading the
598 options due to a SIGHUP. */
602 int numok = (debug_level && digitp (debug_level));
603 int numlvl = numok? atoi (debug_level) : 0;
607 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
609 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
610 opt.debug = DBG_IPC_VALUE;
611 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
612 opt.debug = DBG_IPC_VALUE;
613 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
614 opt.debug = (DBG_IPC_VALUE | DBG_CACHE_VALUE);
615 else if (!strcmp (debug_level, "guru") || numok)
618 /* Unless the "guru" string has been used we don't want to allow
619 hashing debugging. The rationale is that people tend to
620 select the highest debug value and would then clutter their
621 disk with debug files which may reveal confidential data. */
623 opt.debug &= ~(DBG_HASHING_VALUE);
627 log_error (_("invalid debug-level '%s' given\n"), debug_level);
628 opt.debug = 0; /* Reset debugging, so that prior debug
629 statements won't have an undesired effect. */
632 if (opt.debug && !opt.verbose)
634 if (opt.debug && opt.quiet)
637 if (opt.debug & DBG_MPI_VALUE)
638 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
639 if (opt.debug & DBG_CRYPTO_VALUE )
640 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
641 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
644 parse_debug_flag (NULL, &opt.debug, debug_flags);
648 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
649 the corresponding real name if the socket has been redirected. */
651 remove_socket (char *name, char *redir_name)
664 /* Discover which inherited file descriptors correspond to which
665 * services/sockets offered by gpg-agent, using the LISTEN_FDS and
666 * LISTEN_FDNAMES convention. The understood labels are "ssh",
667 * "extra", and "browser". "std" or other labels will be interpreted
668 * as the standard socket.
670 * This function is designed to log errors when the expected file
671 * descriptors don't make sense, but to do its best to continue to
672 * work even in the face of minor misconfigurations.
674 * For more information on the LISTEN_FDS convention, see
675 * sd_listen_fds(3) on certain Linux distributions.
677 #ifndef HAVE_W32_SYSTEM
679 map_supervised_sockets (gnupg_fd_t *r_fd,
680 gnupg_fd_t *r_fd_extra,
681 gnupg_fd_t *r_fd_browser,
682 gnupg_fd_t *r_fd_ssh)
689 { "ssh", &r_fd_ssh, &socket_name_ssh },
690 { "browser", &r_fd_browser, &socket_name_browser },
691 { "extra", &r_fd_extra, &socket_name_extra },
692 { "std", &r_fd, &socket_name } /* (Must be the last item.) */
699 *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
701 /* Print a warning if LISTEN_PID does not match outr pid. */
702 envvar = getenv ("LISTEN_PID");
704 log_error ("no LISTEN_PID environment variable found in "
705 "--supervised mode (ignoring)\n");
706 else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
707 log_error ("environment variable LISTEN_PID (%lu) does not match"
708 " our pid (%lu) in --supervised mode (ignoring)\n",
709 (unsigned long)strtoul (envvar, NULL, 10),
710 (unsigned long)getpid ());
712 /* Parse LISTEN_FDNAMES into the array FDNAMES. */
713 envvar = getenv ("LISTEN_FDNAMES");
716 fdnames = strtokenize (envvar, ":");
719 log_error ("strtokenize failed: %s\n",
720 gpg_strerror (gpg_error_from_syserror ()));
723 for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
732 /* Parse LISTEN_FDS into fd_count or provide a replacement. */
733 envvar = getenv ("LISTEN_FDS");
735 fd_count = atoi (envvar);
738 log_error ("no LISTEN_FDS environment variable found in --supervised"
739 " mode (relying on LISTEN_FDNAMES instead)\n");
744 log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
745 "found in --supervised mode"
746 " (assuming 1 active descriptor)\n");
752 log_error ("--supervised mode expects at least one file descriptor"
753 " (was told %d, carrying on as though it were 1)\n",
758 /* Assign the descriptors to the return values. */
764 log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
765 " in --supervised mode."
766 " (ignoring all sockets but the first one)\n",
768 if (fstat (3, &statbuf) == -1 && errno ==EBADF)
769 log_fatal ("file descriptor 3 must be valid in --supervised mode"
770 " if LISTEN_FDNAMES is not set\n");
772 socket_name = gnupg_get_socket_name (3);
774 else if (fd_count != nfdnames)
776 log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
777 "LISTEN_FDS (%d) in --supervised mode\n",
785 for (i = 0; i < nfdnames; i++)
787 for (j = 0; j < DIM (tbl); j++)
789 if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
792 if (**tbl[j].fdaddr == -1)
794 name = gnupg_get_socket_name (fd);
797 **tbl[j].fdaddr = fd;
798 *tbl[j].nameaddr = name;
799 log_info ("using fd %d for %s socket (%s)\n",
800 fd, tbl[j].label, name);
804 log_error ("cannot listen on fd %d for %s socket\n",
811 log_error ("cannot listen on more than one %s socket\n",
823 #endif /*!HAVE_W32_SYSTEM*/
826 /* Cleanup code for this program. This is either called has an atexit
827 handler or directly. */
836 deinitialize_module_cache ();
837 if (!is_supervised && !inhibit_socket_removal)
839 remove_socket (socket_name, redir_socket_name);
840 if (opt.extra_socket > 1)
841 remove_socket (socket_name_extra, redir_socket_name_extra);
842 if (opt.browser_socket > 1)
843 remove_socket (socket_name_browser, redir_socket_name_browser);
844 remove_socket (socket_name_ssh, redir_socket_name_ssh);
850 /* Handle options which are allowed to be reset after program start.
851 Return true when the current option in PARGS could be handled and
852 false if not. As a special feature, passing a value of NULL for
853 PARGS, resets the options to the default. REREAD should be set
854 true if it is not the initial option parsing. */
856 parse_rereadable_options (gpgrt_argparse_t *pargs, int reread)
866 opt.debug_pinentry = 0;
867 opt.pinentry_program = NULL;
868 opt.pinentry_touch_file = NULL;
869 xfree (opt.pinentry_invisible_char);
870 opt.pinentry_invisible_char = NULL;
871 opt.pinentry_timeout = 0;
872 opt.pinentry_formatted_passphrase = 0;
873 memset (opt.daemon_program, 0, sizeof opt.daemon_program);
874 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
875 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
876 opt.max_cache_ttl = MAX_CACHE_TTL;
877 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
878 opt.enforce_passphrase_constraints = 0;
879 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
880 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
881 opt.check_passphrase_pattern = NULL;
882 opt.check_sym_passphrase_pattern = NULL;
883 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
884 opt.enable_passphrase_history = 0;
885 opt.ignore_cache_for_signing = 0;
886 opt.allow_mark_trusted = 1;
887 opt.sys_trustlist_name = NULL;
888 opt.allow_external_cache = 1;
889 opt.allow_loopback_pinentry = 1;
890 opt.allow_emacs_pinentry = 0;
891 memset (opt.disable_daemon, 0, sizeof opt.disable_daemon);
892 disable_check_own_socket = 0;
893 /* Note: When changing the next line, change also gpgconf_list. */
894 opt.ssh_fingerprint_digest = GCRY_MD_SHA256;
896 set_s2k_calibration_time (0); /* Set to default. */
900 switch (pargs->r_opt)
902 case oQuiet: opt.quiet = 1; break;
903 case oVerbose: opt.verbose++; break;
906 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
908 case oDebugAll: opt.debug = ~0; break;
909 case oDebugLevel: debug_level = pargs->r.ret_str; break;
910 case oDebugPinentry: opt.debug_pinentry = 1; break;
914 return 0; /* not handled */
915 if (!current_logfile || !pargs->r.ret_str
916 || strcmp (current_logfile, pargs->r.ret_str))
918 log_set_file (pargs->r.ret_str);
919 xfree (current_logfile);
920 current_logfile = xtrystrdup (pargs->r.ret_str);
924 case oNoGrab: opt.no_grab |= 1; break;
925 case oGrab: opt.no_grab |= 2; break;
927 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
928 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
929 case oPinentryInvisibleChar:
930 xfree (opt.pinentry_invisible_char);
931 opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
933 case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
934 case oPinentryFormattedPassphrase:
935 opt.pinentry_formatted_passphrase = 1;
938 case oTpm2daemonProgram:
939 opt.daemon_program[DAEMON_TPM2D] = pargs->r.ret_str;
942 case oScdaemonProgram:
943 opt.daemon_program[DAEMON_SCD] = pargs->r.ret_str;
945 case oDisableScdaemon: opt.disable_daemon[DAEMON_SCD] = 1; break;
946 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
948 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
949 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
950 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
951 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
953 case oEnforcePassphraseConstraints:
954 opt.enforce_passphrase_constraints=1;
956 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
957 case oMinPassphraseNonalpha:
958 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
960 case oCheckPassphrasePattern:
961 opt.check_passphrase_pattern = pargs->r.ret_str;
963 case oCheckSymPassphrasePattern:
964 opt.check_sym_passphrase_pattern = pargs->r.ret_str;
966 case oMaxPassphraseDays:
967 opt.max_passphrase_days = pargs->r.ret_ulong;
969 case oEnablePassphraseHistory:
970 opt.enable_passphrase_history = 1;
973 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
975 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
976 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
977 case oNoUserTrustlist: opt.no_user_trustlist = 1; break;
978 case oSysTrustlistName: opt.sys_trustlist_name = pargs->r.ret_str; break;
980 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
982 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
983 case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
985 case oNoAllowExternalCache: opt.allow_external_cache = 0;
988 case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
991 case oSSHFingerprintDigest:
992 i = gcry_md_map_name (pargs->r.ret_str);
994 log_error (_("selected digest algorithm is invalid\n"));
996 opt.ssh_fingerprint_digest = i;
1000 opt.s2k_count = pargs->r.ret_ulong;
1003 case oS2KCalibration:
1004 set_s2k_calibration_time (pargs->r.ret_ulong);
1010 return 0; /* not handled */
1013 return 1; /* handled */
1017 /* Fixup some options after all have been processed. */
1019 finalize_rereadable_options (void)
1021 /* Hack to allow --grab to override --no-grab. */
1022 if ((opt.no_grab & 2))
1025 /* With --no-user-trustlist it does not make sense to allow the mark
1026 * trusted feature. */
1027 if (opt.no_user_trustlist)
1028 opt.allow_mark_trusted = 0;
1033 thread_init_once (void)
1035 static int npth_initialized = 0;
1037 if (!npth_initialized)
1042 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
1043 /* Now that we have set the syscall clamp we need to tell Libgcrypt
1044 * that it should get them from libgpg-error. Note that Libgcrypt
1045 * has already been initialized but at that point nPth was not
1046 * initialized and thus Libgcrypt could not set its system call
1048 gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
1053 initialize_modules (void)
1055 thread_init_once ();
1056 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
1057 initialize_module_cache ();
1058 initialize_module_call_pinentry ();
1059 initialize_module_daemon ();
1060 initialize_module_trustlist ();
1064 /* The main entry point. */
1066 main (int argc, char **argv)
1068 gpgrt_argparse_t pargs;
1071 char *last_configname = NULL;
1072 const char *configname = NULL;
1073 int debug_argparser = 0;
1075 int pipe_server = 0;
1079 char *logfile = NULL;
1081 int gpgconf_list = 0;
1083 struct assuan_malloc_hooks malloc_hooks;
1085 early_system_init ();
1087 /* Before we do anything else we save the list of currently open
1088 file descriptors and the signal mask. This info is required to
1089 do the exec call properly. We don't need it on Windows. */
1090 #ifndef HAVE_W32_SYSTEM
1091 startup_fd_list = get_all_open_fds ();
1092 #endif /*!HAVE_W32_SYSTEM*/
1093 #ifdef HAVE_SIGPROCMASK
1094 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
1095 startup_signal_mask_valid = 1;
1096 #endif /*HAVE_SIGPROCMASK*/
1098 /* Set program name etc. */
1099 gpgrt_set_strusage (my_strusage);
1100 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1101 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1102 when adding any stuff between here and the call to INIT_SECMEM()
1103 somewhere after the option parsing */
1104 log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
1106 /* Make sure that our subsystems are ready. */
1108 init_common_subsystems (&argc, &argv);
1110 malloc_hooks.malloc = gcry_malloc;
1111 malloc_hooks.realloc = gcry_realloc;
1112 malloc_hooks.free = gcry_free;
1113 assuan_set_malloc_hooks (&malloc_hooks);
1114 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1115 assuan_sock_init ();
1116 assuan_sock_set_system_hooks (ASSUAN_SYSTEM_NPTH);
1117 setup_libassuan_logging (&opt.debug, NULL);
1119 setup_libgcrypt_logging ();
1120 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1121 gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
1123 disable_core_dumps ();
1125 /* Set default options. */
1126 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
1128 shell = getenv ("SHELL");
1129 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1132 /* Record some of the original environment strings. */
1136 static const char *names[] =
1137 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
1140 opt.startup_env = session_env_new ();
1141 if (!opt.startup_env)
1142 err = gpg_error_from_syserror ();
1143 for (idx=0; !err && names[idx]; idx++)
1145 s = getenv (names[idx]);
1147 err = session_env_setenv (opt.startup_env, names[idx], s);
1151 s = gnupg_ttyname (0);
1153 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
1156 log_fatal ("error recording startup environment: %s\n",
1157 gpg_strerror (err));
1159 /* Fixme: Better use the locale function here. */
1160 opt.startup_lc_ctype = getenv ("LC_CTYPE");
1161 if (opt.startup_lc_ctype)
1162 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
1163 opt.startup_lc_messages = getenv ("LC_MESSAGES");
1164 if (opt.startup_lc_messages)
1165 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
1168 /* Check whether we have a config file on the commandline */
1173 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1174 while (gpgrt_argparse (NULL, &pargs, opts))
1176 switch (pargs.r_opt)
1184 gnupg_set_homedir (pargs.r.ret_str);
1187 case oDebugQuickRandom:
1188 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
1192 /* Reset the flags. */
1193 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1195 /* Initialize the secure memory. */
1196 gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0);
1200 * Now we are now working under our real uid
1203 /* The configuraton directories for use by gpgrt_argparser. */
1204 gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
1205 gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
1211 /* We are re-using the struct, thus the reset flag. We OR the
1212 * flags so that the internal intialized flag won't be cleared. */
1213 pargs.flags |= (ARGPARSE_FLAG_RESET
1214 | ARGPARSE_FLAG_KEEP
1216 | ARGPARSE_FLAG_USER);
1218 while (gpgrt_argparser (&pargs, opts, GPG_AGENT_NAME EXTSEP_S "conf"))
1220 if (pargs.r_opt == ARGPARSE_CONFFILE)
1222 if (debug_argparser)
1223 log_info (_("reading options from '%s'\n"),
1224 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1227 xfree (last_configname);
1228 last_configname = xstrdup (pargs.r.ret_str);
1229 configname = last_configname;
1235 if (parse_rereadable_options (&pargs, 0))
1236 continue; /* Already handled */
1237 switch (pargs.r_opt)
1239 case aGPGConfList: gpgconf_list = 1; break;
1240 case aGPGConfTest: gpgconf_list = 2; break;
1241 case aUseStandardSocketP: gpgconf_list = 3; break;
1242 case oBatch: opt.batch=1; break;
1244 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1246 case oNoVerbose: opt.verbose = 0; break;
1247 case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1248 case oNoDetach: nodetach = 1; break;
1249 case oLogFile: logfile = pargs.r.ret_str; break;
1250 case oCsh: csh_style = 1; break;
1251 case oSh: csh_style = 0; break;
1252 case oServer: pipe_server = 1; break;
1253 case oDaemon: is_daemon = 1; break;
1254 case oStealSocket: steal_socket = 1; break;
1255 case oSupervised: is_supervised = 1; break;
1257 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
1258 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
1259 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
1260 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
1261 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
1263 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
1266 case oUseStandardSocket:
1267 case oNoUseStandardSocket:
1268 obsolete_option (configname, pargs.lineno, "use-standard-socket");
1271 case oFakedSystemTime:
1273 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1274 if (faked_time == (time_t)(-1))
1275 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1276 gnupg_set_time (faked_time, 0);
1280 case oKeepTTY: opt.keep_tty = 1; break;
1281 case oKeepDISPLAY: opt.keep_display = 1; break;
1288 # ifdef HAVE_W32_SYSTEM
1293 case oWin32OpenSSHSupport:
1294 # ifdef HAVE_W32_SYSTEM
1296 win32_openssh_support = pargs.r.ret_str;
1298 win32_openssh_support = W32_DEFAILT_AGENT_PIPE_NAME;
1303 opt.extra_socket = 1; /* (1 = points into argv) */
1304 socket_name_extra = pargs.r.ret_str;
1307 case oBrowserSocket:
1308 opt.browser_socket = 1; /* (1 = points into argv) */
1309 socket_name_browser = pargs.r.ret_str;
1312 case oAutoExpandSecmem:
1313 /* Try to enable this option. It will officially only be
1314 * supported by Libgcrypt 1.9 but 1.8.2 already supports it
1315 * on the quiet and thus we use the numeric value value. */
1316 gcry_control (78 /*GCRYCTL_AUTO_EXPAND_SECMEM*/,
1317 (unsigned int)pargs.r.ret_ulong, 0);
1320 case oListenBacklog:
1321 listen_backlog = pargs.r.ret_int;
1324 case oDebugQuickRandom:
1325 /* Only used by the first stage command line parser. */
1329 obsolete_option (configname, pargs.lineno, "write-env-file");
1334 pargs.err = ARGPARSE_PRINT_WARNING;
1336 pargs.err = ARGPARSE_PRINT_ERROR;
1341 /* Print a warning if an argument looks like an option. */
1342 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1346 for (i=0; i < argc; i++)
1347 if (argv[i][0] == '-' && argv[i][1] == '-')
1348 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1351 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
1353 if (!last_configname)
1354 config_filename = gpgrt_fnameconcat (gnupg_homedir (),
1355 GPG_AGENT_NAME EXTSEP_S "conf",
1359 config_filename = last_configname;
1360 last_configname = NULL;
1363 if (log_get_errorcount(0))
1366 finalize_rereadable_options ();
1368 /* Get a default log file from common.conf. */
1369 if (!logfile && !parse_comopt (GNUPG_MODULE_NAME_AGENT, debug_argparser))
1371 logfile = comopt.logfile;
1372 comopt.logfile = NULL;
1376 /* gpg-agent usually does not output any messages because it runs in
1377 the background. For log files it is acceptable to have messages
1378 always encoded in utf-8. We switch here to utf-8, so that
1379 commands like --help still give native messages. It is far
1380 easier to switch only once instead of for every message and it
1381 actually helps when more then one thread is active (avoids an
1382 extra copy step). */
1383 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1386 if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
1388 /* We have been called without any command and thus we merely
1389 check whether an agent is already running. We do this right
1390 here so that we don't clobber a logfile with this check but
1391 print the status directly to stderr. */
1394 check_for_running_agent (0);
1398 if (is_supervised && !opt.quiet)
1399 log_info(_("WARNING: \"%s\" is a deprecated option\n"), "--supervised");
1403 else if (!opt.extra_socket)
1404 opt.extra_socket = 1;
1405 else if (socket_name_extra
1406 && (!strcmp (socket_name_extra, "none")
1407 || !strcmp (socket_name_extra, "/dev/null")))
1409 /* User requested not to create this socket. */
1410 opt.extra_socket = 0;
1411 socket_name_extra = NULL;
1416 else if (!opt.browser_socket)
1417 opt.browser_socket = 1;
1418 else if (socket_name_browser
1419 && (!strcmp (socket_name_browser, "none")
1420 || !strcmp (socket_name_browser, "/dev/null")))
1422 /* User requested not to create this socket. */
1423 opt.browser_socket = 0;
1424 socket_name_browser = NULL;
1429 if (atexit (cleanup))
1431 log_error ("atexit failed\n");
1436 /* Try to create missing directories. */
1438 create_directories ();
1440 if (debug_wait && pipe_server)
1442 thread_init_once ();
1443 log_debug ("waiting for debugger - my pid is %u .....\n",
1444 (unsigned int)getpid());
1445 gnupg_sleep (debug_wait);
1446 log_debug ("... okay\n");
1449 if (gpgconf_list == 3)
1451 /* We now use the standard socket always - return true for
1452 backward compatibility. */
1455 else if (gpgconf_list == 2)
1457 else if (gpgconf_list)
1459 /* Note: If an option is runtime changeable, please set the
1460 * respective flag in the gpgconf-comp.c table. */
1461 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1462 es_printf ("default-cache-ttl:%lu:%d:\n",
1463 GC_OPT_FLAG_DEFAULT, DEFAULT_CACHE_TTL );
1464 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1465 GC_OPT_FLAG_DEFAULT, DEFAULT_CACHE_TTL_SSH );
1466 es_printf ("max-cache-ttl:%lu:%d:\n",
1467 GC_OPT_FLAG_DEFAULT, MAX_CACHE_TTL );
1468 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1469 GC_OPT_FLAG_DEFAULT, MAX_CACHE_TTL_SSH );
1470 es_printf ("min-passphrase-len:%lu:%d:\n",
1471 GC_OPT_FLAG_DEFAULT, MIN_PASSPHRASE_LEN );
1472 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1473 GC_OPT_FLAG_DEFAULT, MIN_PASSPHRASE_NONALPHA);
1474 es_printf ("check-passphrase-pattern:%lu:\n",
1475 GC_OPT_FLAG_DEFAULT);
1476 es_printf ("check-sym-passphrase-pattern:%lu:\n",
1477 GC_OPT_FLAG_DEFAULT);
1478 es_printf ("max-passphrase-days:%lu:%d:\n",
1479 GC_OPT_FLAG_DEFAULT, MAX_PASSPHRASE_DAYS);
1480 es_printf ("ssh-fingerprint-digest:%lu:\"%s:\n",
1481 GC_OPT_FLAG_DEFAULT, "sha256");
1486 /* Now start with logging to a file if this is desired. */
1489 log_set_file (logfile);
1490 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1491 | GPGRT_LOG_WITH_TIME
1492 | GPGRT_LOG_WITH_PID));
1493 current_logfile = xstrdup (logfile);
1496 /* Make sure that we have a default ttyname. */
1497 if (!default_ttyname && gnupg_ttyname (1))
1498 default_ttyname = xstrdup (gnupg_ttyname (1));
1499 if (!default_ttytype && getenv ("TERM"))
1500 default_ttytype = xstrdup (getenv ("TERM"));
1505 /* This is the simple pipe based server */
1508 initialize_modules ();
1510 ctrl = xtrycalloc (1, sizeof *ctrl);
1513 log_error ("error allocating connection control data: %s\n",
1517 ctrl->session_env = session_env_new ();
1518 if (!ctrl->session_env)
1520 log_error ("error allocating session environment block: %s\n",
1525 agent_init_default_ctrl (ctrl);
1526 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1527 agent_deinit_default_ctrl (ctrl);
1530 else if (is_supervised && comopt.no_autostart)
1532 /* If we are running on a server and the user has set
1533 * no-autostart for gpg or gpgsm. gpg-agent would anyway be
1534 * started by the supervisor which has the bad effect that it
1535 * will steal the socket from a remote server. Note that
1536 * systemd has no knowledge about the lock files we take during
1537 * the start operation. */
1538 log_info ("%s %s not starting in supervised mode due to no-autostart.\n",
1539 gpgrt_strusage(11), gpgrt_strusage(13) );
1541 else if (is_supervised)
1543 #ifndef HAVE_W32_SYSTEM
1544 gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
1546 initialize_modules ();
1548 /* when supervised and sending logs to stderr, the process
1549 supervisor should handle log entry metadata (pid, name,
1552 log_set_prefix (NULL, 0);
1554 log_info ("%s %s starting in supervised mode.\n",
1555 gpgrt_strusage(11), gpgrt_strusage(13) );
1557 /* See below in "regular server mode" on why we remove certain
1559 if (!opt.keep_display)
1560 gnupg_unsetenv ("DISPLAY");
1561 gnupg_unsetenv ("INSIDE_EMACS");
1563 /* Virtually create the sockets. Note that we use -1 here
1564 * because the whole thing works only on Unix. */
1565 map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
1567 log_fatal ("no standard socket provided\n");
1569 #ifdef HAVE_SIGPROCMASK
1570 if (startup_signal_mask_valid)
1572 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1573 log_error ("error restoring signal mask: %s\n",
1577 log_info ("no saved signal mask\n");
1578 #endif /*HAVE_SIGPROCMASK*/
1580 log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
1581 fd, fd_extra, fd_browser, fd_ssh);
1582 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1583 #endif /*!HAVE_W32_SYSTEM*/
1585 else if (!is_daemon)
1588 { /* Regular server mode */
1590 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1591 gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1592 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1593 #ifndef HAVE_W32_SYSTEM
1597 /* Remove the DISPLAY variable so that a pinentry does not
1598 default to a specific display. There is still a default
1599 display when gpg-agent was started using --display or a
1600 client requested this using an OPTION command. Note, that we
1601 don't do this when running in reverse daemon mode (i.e. when
1602 exec the program given as arguments). */
1603 #ifndef HAVE_W32_SYSTEM
1604 if (!opt.keep_display && !argc)
1605 gnupg_unsetenv ("DISPLAY");
1608 /* Remove the INSIDE_EMACS variable so that a pinentry does not
1609 always try to interact with Emacs. The variable is set when
1610 a client requested this using an OPTION command. */
1611 gnupg_unsetenv ("INSIDE_EMACS");
1613 /* Create the sockets. */
1614 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1615 fd = create_server_socket (socket_name, 1, 0,
1616 &redir_socket_name, &socket_nonce);
1618 if (opt.extra_socket)
1620 if (socket_name_extra)
1621 socket_name_extra = create_socket_name (socket_name_extra, 0);
1623 socket_name_extra = create_socket_name
1624 /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1);
1625 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1626 fd_extra = create_server_socket (socket_name_extra, 0, 0,
1627 &redir_socket_name_extra,
1628 &socket_nonce_extra);
1631 if (opt.browser_socket)
1633 if (socket_name_browser)
1634 socket_name_browser = create_socket_name (socket_name_browser, 0);
1636 socket_name_browser= create_socket_name
1637 /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1);
1638 opt.browser_socket = 2; /* Indicate that it has been malloced. */
1639 fd_browser = create_server_socket (socket_name_browser, 0, 0,
1640 &redir_socket_name_browser,
1641 &socket_nonce_browser);
1644 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1645 fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1646 &redir_socket_name_ssh,
1649 /* If we are going to exec a program in the parent, we record
1650 the PID, so that the child may check whether the program is
1653 parent_pid = getpid ();
1657 #ifdef HAVE_W32_SYSTEM
1661 initialize_modules ();
1663 #else /*!HAVE_W32_SYSTEM*/
1666 if (pid == (pid_t)-1)
1668 log_fatal ("fork failed: %s\n", strerror (errno) );
1672 { /* We are the parent */
1673 char *infostr_ssh_sock, *infostr_ssh_valid;
1675 /* Close the socket FD. */
1678 /* The signal mask might not be correct right now and thus
1679 we restore it. That is not strictly necessary but some
1680 programs falsely assume a cleared signal mask. */
1682 #ifdef HAVE_SIGPROCMASK
1683 if (startup_signal_mask_valid)
1685 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1686 log_error ("error restoring signal mask: %s\n",
1690 log_info ("no saved signal mask\n");
1691 #endif /*HAVE_SIGPROCMASK*/
1693 /* Create the SSH info string if enabled. */
1696 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1697 socket_name_ssh) < 0)
1699 log_error ("out of core\n");
1700 kill (pid, SIGTERM);
1703 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1704 (unsigned long)getpid()) < 0)
1706 log_error ("out of core\n");
1707 kill (pid, SIGTERM);
1712 *socket_name = 0; /* Don't let cleanup() remove the socket -
1713 the child should do this from now on */
1714 if (opt.extra_socket)
1715 *socket_name_extra = 0;
1716 if (opt.browser_socket)
1717 *socket_name_browser = 0;
1718 *socket_name_ssh = 0;
1721 { /* Run the program given on the commandline. */
1722 if (ssh_support && (putenv (infostr_ssh_sock)
1723 || putenv (infostr_ssh_valid)))
1725 log_error ("failed to set environment: %s\n",
1727 kill (pid, SIGTERM );
1731 /* Close all the file descriptors except the standard
1732 ones and those open at startup. We explicitly don't
1733 close 0,1,2 in case something went wrong collecting
1735 close_all_fds (3, startup_fd_list);
1737 /* Run the command. */
1738 execvp (argv[0], argv);
1739 log_error ("failed to run the command: %s\n", strerror (errno));
1740 kill (pid, SIGTERM);
1745 /* Print the environment string, so that the caller can use
1746 shell's eval to set it */
1751 *strchr (infostr_ssh_sock, '=') = ' ';
1752 es_printf ("setenv %s;\n", infostr_ssh_sock);
1759 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1765 xfree (infostr_ssh_sock);
1766 xfree (infostr_ssh_valid);
1777 initialize_modules ();
1779 /* Detach from tty and put process into a new session */
1783 unsigned int oldflags;
1785 /* Close stdin, stdout and stderr unless it is the log stream */
1786 for (i=0; i <= 2; i++)
1788 if (!log_test_fd (i) && i != fd )
1791 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1793 log_error ("failed to open '%s': %s\n",
1794 "/dev/null", strerror (errno));
1802 log_error ("setsid() failed: %s\n", strerror(errno) );
1807 log_get_prefix (&oldflags);
1808 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1809 opt.running_detached = 1;
1811 /* Unless we are running with a program given on the command
1812 * line we can assume that the inotify things works and thus
1813 * we can avoid the regular stat calls. */
1815 reliable_homedir_inotify = 1;
1819 struct sigaction sa;
1821 sa.sa_handler = SIG_IGN;
1822 sigemptyset (&sa.sa_mask);
1824 sigaction (SIGPIPE, &sa, NULL);
1826 #endif /*!HAVE_W32_SYSTEM*/
1828 if (gnupg_chdir (gnupg_daemon_rootdir ()))
1830 log_error ("chdir to '%s' failed: %s\n",
1831 gnupg_daemon_rootdir (), strerror (errno));
1835 log_info ("%s %s started\n", gpgrt_strusage(11), gpgrt_strusage(13) );
1836 handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1837 assuan_sock_close (fd);
1844 /* Exit entry point. This function should be called instead of a
1849 /*FIXME: update_random_seed_file();*/
1851 /* We run our cleanup handler because that may close cipher contexts
1852 stored in secure memory and thus this needs to be done before we
1853 explicitly terminate secure memory. */
1857 /* at this time a bit annoying */
1858 if (opt.debug & DBG_MEMSTAT_VALUE)
1860 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1861 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1864 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1866 gcry_control (GCRYCTL_TERM_SECMEM );
1867 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1872 /* This is our callback function for gcrypt progress messages. It is
1873 set once at startup and dispatches progress messages to the
1874 corresponding threads of the agent. */
1876 agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1877 int current, int total)
1879 struct progress_dispatch_s *dispatch;
1880 npth_t mytid = npth_self ();
1884 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1885 if (dispatch->ctrl && dispatch->tid == mytid)
1887 if (dispatch && dispatch->cb)
1888 dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1892 /* If a progress dispatcher callback has been associated with the
1893 * current connection unregister it. */
1895 unregister_progress_cb (void)
1897 struct progress_dispatch_s *dispatch;
1898 npth_t mytid = npth_self ();
1900 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1901 if (dispatch->ctrl && dispatch->tid == mytid)
1905 dispatch->ctrl = NULL;
1906 dispatch->cb = NULL;
1911 /* Setup a progress callback CB for the current connection. Using a
1912 * CB of NULL disables the callback. */
1914 agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1915 int printchar, int current, int total),
1918 struct progress_dispatch_s *dispatch, *firstfree;
1919 npth_t mytid = npth_self ();
1922 for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1924 if (dispatch->ctrl && dispatch->tid == mytid)
1926 if (!dispatch->ctrl && !firstfree)
1927 firstfree = dispatch;
1929 if (!dispatch) /* None allocated: Reuse or allocate a new one. */
1933 dispatch = firstfree;
1935 else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1937 dispatch->next = progress_dispatch_list;
1938 progress_dispatch_list = dispatch;
1942 log_error ("error allocating new progress dispatcher slot: %s\n",
1943 gpg_strerror (gpg_error_from_syserror ()));
1946 dispatch->ctrl = ctrl;
1947 dispatch->tid = mytid;
1954 /* Each thread has its own local variables conveyed by a control
1955 structure usually identified by an argument named CTRL. This
1956 function is called immediately after allocating the control
1957 structure. Its purpose is to setup the default values for that
1958 structure. Note that some values may have already been set. */
1960 agent_init_default_ctrl (ctrl_t ctrl)
1962 log_assert (ctrl->session_env);
1964 /* Note we ignore malloc errors because we can't do much about it
1965 and the request will fail anyway shortly after this
1967 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1968 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1969 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1970 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1971 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1974 xfree (ctrl->lc_ctype);
1975 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1977 if (ctrl->lc_messages)
1978 xfree (ctrl->lc_messages);
1979 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1981 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1985 /* Release all resources allocated by default in the control
1986 structure. This is the counterpart to agent_init_default_ctrl. */
1988 agent_deinit_default_ctrl (ctrl_t ctrl)
1990 unregister_progress_cb ();
1991 session_env_release (ctrl->session_env);
1993 xfree (ctrl->digest.data);
1994 ctrl->digest.data = NULL;
1996 xfree (ctrl->lc_ctype);
1997 if (ctrl->lc_messages)
1998 xfree (ctrl->lc_messages);
2002 /* Because the ssh protocol does not send us information about the
2003 current TTY setting, we use this function to use those from startup
2004 or those explicitly set. This is also used for the restricted mode
2005 where we ignore requests to change the environment. */
2007 agent_copy_startup_env (ctrl_t ctrl)
2009 gpg_error_t err = 0;
2011 const char *name, *value;
2013 while (!err && (name = session_env_list_stdenvnames (&iterator, NULL)))
2015 if ((value = session_env_getenv (opt.startup_env, name)))
2016 err = session_env_setenv (ctrl->session_env, name, value);
2019 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
2020 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
2021 err = gpg_error_from_syserror ();
2023 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
2024 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
2025 err = gpg_error_from_syserror ();
2028 log_error ("error setting default session environment: %s\n",
2029 gpg_strerror (err));
2035 /* Reread parts of the configuration. Note, that this function is
2036 obviously not thread-safe and should only be called from the PTH
2039 Fixme: Due to the way the argument parsing works, we create a
2040 memory leak here for all string type arguments. There is currently
2041 no clean way to tell whether the memory for the argument has been
2042 allocated or points into the process's original arguments. Unless
2043 we have a mechanism to tell this, we need to live on with this. */
2045 reread_configuration (void)
2047 gpgrt_argparse_t pargs;
2050 int logfile_seen = 0;
2052 if (!config_filename)
2053 return; /* No config file. */
2055 twopart = strconcat (GPG_AGENT_NAME EXTSEP_S "conf" PATHSEP_S,
2056 config_filename, NULL);
2058 return; /* Out of core. */
2060 parse_rereadable_options (NULL, 1); /* Start from the default values. */
2062 memset (&pargs, 0, sizeof pargs);
2064 pargs.argc = &dummy;
2065 pargs.flags = (ARGPARSE_FLAG_KEEP
2067 |ARGPARSE_FLAG_USER);
2068 while (gpgrt_argparser (&pargs, opts, twopart) )
2070 if (pargs.r_opt == ARGPARSE_CONFFILE)
2072 log_info (_("reading options from '%s'\n"),
2073 pargs.r_type? pargs.r.ret_str: "[cmdline]");
2075 else if (pargs.r_opt < -1)
2076 pargs.err = ARGPARSE_PRINT_WARNING;
2077 else /* Try to parse this option - ignore unchangeable ones. */
2079 if (pargs.r_opt == oLogFile)
2081 parse_rereadable_options (&pargs, 1);
2084 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
2087 finalize_rereadable_options ();
2090 /* Get a default log file from common.conf. */
2091 if (!logfile_seen && !parse_comopt (GNUPG_MODULE_NAME_AGENT, !!opt.debug))
2093 if (!current_logfile || !comopt.logfile
2094 || strcmp (current_logfile, comopt.logfile))
2096 log_set_file (comopt.logfile);
2097 xfree (current_logfile);
2098 current_logfile = comopt.logfile? xtrystrdup (comopt.logfile) : NULL;
2104 /* Return the file name of the socket we are using for native
2107 get_agent_socket_name (void)
2109 const char *s = socket_name;
2111 return (s && *s)? s : NULL;
2114 /* Return the file name of the socket we are using for SSH
2117 get_agent_ssh_socket_name (void)
2119 const char *s = socket_name_ssh;
2121 return (s && *s)? s : NULL;
2125 /* Return the number of active connections. */
2127 get_agent_active_connection_count (void)
2129 return active_connections;
2133 /* Under W32, this function returns the handle of the scdaemon
2134 notification event. Calling it the first time creates that
2136 #if defined(HAVE_W32_SYSTEM)
2138 get_agent_daemon_notify_event (void)
2140 static HANDLE the_event = INVALID_HANDLE_VALUE;
2142 if (the_event == INVALID_HANDLE_VALUE)
2145 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
2147 /* We need to use a manual reset event object due to the way our
2148 w32-pth wait function works: If we would use an automatic
2149 reset event we are not able to figure out which handle has
2150 been signaled because at the time we single out the signaled
2151 handles using WFSO the event has already been reset due to
2153 h = CreateEvent (&sa, TRUE, FALSE, NULL);
2155 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
2156 else if (!DuplicateHandle (GetCurrentProcess(), h,
2157 GetCurrentProcess(), &h2,
2158 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
2160 log_error ("setting synchronize for scd notify event failed: %s\n",
2161 w32_strerror (-1) );
2173 #endif /*HAVE_W32_SYSTEM*/
2177 /* Create a name for the socket in the home directory as using
2178 STANDARD_NAME. We also check for valid characters as well as
2179 against a maximum allowed length for a unix domain socket is done.
2180 The function terminates the process in case of an error. Returns:
2181 Pointer to an allocated string with the absolute name of the socket
2184 create_socket_name (char *standard_name, int with_homedir)
2189 name = make_filename (gnupg_socketdir (), standard_name, NULL);
2191 name = make_filename (standard_name, NULL);
2192 if (strchr (name, PATHSEP_C))
2194 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
2202 /* Create a Unix domain socket with NAME. Returns the file descriptor
2203 or terminates the process in case of an error. Note that this
2204 function needs to be used for the regular socket first (indicated
2205 by PRIMARY) and only then for the extra and the ssh sockets. If
2206 the socket has been redirected the name of the real socket is
2207 stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
2208 Cygwin compatible socket is created (Windows only). */
2210 create_server_socket (char *name, int primary, int cygwin,
2211 char **r_redir_name, assuan_sock_nonce_t *nonce)
2213 struct sockaddr *addr;
2214 struct sockaddr_un *unaddr;
2219 xfree (*r_redir_name);
2220 *r_redir_name = NULL;
2222 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
2223 if (fd == ASSUAN_INVALID_FD)
2225 log_error (_("can't create socket: %s\n"), strerror (errno));
2226 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2231 assuan_sock_set_flag (fd, "cygwin", 1);
2233 unaddr = xmalloc (sizeof *unaddr);
2234 addr = (struct sockaddr*)unaddr;
2239 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
2241 if (errno == ENAMETOOLONG)
2242 log_error (_("socket name '%s' is too long\n"), name);
2244 log_error ("error preparing socket '%s': %s\n",
2245 name, gpg_strerror (gpg_error_from_syserror ()));
2246 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2252 *r_redir_name = xstrdup (unaddr->sun_path);
2254 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
2258 len = SUN_LEN (unaddr);
2259 rc = assuan_sock_bind (fd, addr, len);
2261 /* At least our error code mapping on Windows-CE used to return
2262 * EEXIST thus we better test for this on Windows . */
2264 && (errno == EADDRINUSE
2265 #ifdef HAVE_W32_SYSTEM
2270 /* Check whether a gpg-agent is already running. We do this
2271 test only if this is the primary socket. For secondary
2272 sockets we assume that a test for gpg-agent has already been
2273 done and reuse the requested socket. Testing the ssh-socket
2274 is not possible because at this point, though we know the new
2275 Assuan socket, the Assuan server and thus the ssh-agent
2276 server is not yet operational; this would lead to a hang. */
2277 if (primary && !check_for_running_agent (1))
2280 log_info (N_("trying to steal socket from running %s\n"),
2284 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
2285 log_set_file (NULL);
2286 log_error (_("a gpg-agent is already running - "
2287 "not starting a new one\n"));
2288 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2289 assuan_sock_close (fd);
2294 gnupg_remove (unaddr->sun_path);
2295 rc = assuan_sock_bind (fd, addr, len);
2297 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
2298 log_error (_("error getting nonce for the socket\n"));
2301 /* We use gpg_strerror here because it allows us to get strings
2302 for some W32 socket error codes. */
2303 log_error (_("error binding socket to '%s': %s\n"),
2305 gpg_strerror (gpg_error_from_syserror ()));
2307 assuan_sock_close (fd);
2308 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2313 if (gnupg_chmod (unaddr->sun_path, "-rwx"))
2314 log_error (_("can't set permissions of '%s': %s\n"),
2315 unaddr->sun_path, strerror (errno));
2317 if (listen (FD2INT(fd), listen_backlog ) == -1)
2319 log_error ("listen(fd,%d) failed: %s\n",
2320 listen_backlog, strerror (errno));
2321 *name = 0; /* Inhibit removal of the socket by cleanup(). */
2322 assuan_sock_close (fd);
2328 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
2335 /* Check that the directory for storing the private keys exists and
2336 create it if not. This function won't fail as it is only a
2337 convenience function and not strictly necessary. */
2339 create_private_keys_directory (const char *home)
2342 struct stat statbuf;
2344 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
2345 if (gnupg_stat (fname, &statbuf) && errno == ENOENT)
2347 if (gnupg_mkdir (fname, "-rwx"))
2348 log_error (_("can't create directory '%s': %s\n"),
2349 fname, strerror (errno) );
2350 else if (!opt.quiet)
2351 log_info (_("directory '%s' created\n"), fname);
2353 if (gnupg_chmod (fname, "-rwx"))
2354 log_error (_("can't set permissions of '%s': %s\n"),
2355 fname, strerror (errno));
2359 /* The file exists or another error. Make sure we have sensible
2360 * permissions. We enforce rwx for user but keep existing group
2361 * permissions. Permissions for other are always cleared. */
2362 if (gnupg_chmod (fname, "-rwx...---"))
2363 log_error (_("can't set permissions of '%s': %s\n"),
2364 fname, strerror (errno));
2370 /* Create the directory only if the supplied directory name is the
2371 same as the default one. This way we avoid to create arbitrary
2372 directories when a non-default home directory is used. To cope
2373 with HOME, we compare only the suffix if we see that the default
2374 homedir does start with a tilde. We don't stop here in case of
2375 problems because other functions will throw an error anyway.*/
2377 create_directories (void)
2379 struct stat statbuf;
2380 const char *defhome = standard_homedir ();
2383 home = make_filename (gnupg_homedir (), NULL);
2384 if (gnupg_stat (home, &statbuf))
2386 if (errno == ENOENT)
2389 #ifdef HAVE_W32_SYSTEM
2390 ( !compare_filenames (home, defhome) )
2393 && (strlen (home) >= strlen (defhome+1)
2394 && !strcmp (home + strlen(home)
2395 - strlen (defhome+1), defhome+1)))
2396 || (*defhome != '~' && !strcmp (home, defhome) )
2400 if (gnupg_mkdir (home, "-rwx"))
2401 log_error (_("can't create directory '%s': %s\n"),
2402 home, strerror (errno) );
2406 log_info (_("directory '%s' created\n"), home);
2407 create_private_keys_directory (home);
2412 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
2414 else if ( !S_ISDIR(statbuf.st_mode))
2416 log_error (_("can't use '%s' as home directory\n"), home);
2418 else /* exists and is a directory. */
2420 create_private_keys_directory (home);
2427 /* This is the worker for the ticker. It is called every few seconds
2428 and may only do fast operations. */
2432 static time_t last_minute;
2433 struct stat statbuf;
2436 last_minute = time (NULL);
2438 /* If we are running as a child of another process, check whether
2439 the parent is still alive and shutdown if not. */
2440 #ifndef HAVE_W32_SYSTEM
2441 if (parent_pid != (pid_t)(-1))
2443 if (kill (parent_pid, 0))
2445 shutdown_pending = 2;
2446 log_info ("parent process died - shutting down\n");
2447 log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2452 #endif /*HAVE_W32_SYSTEM*/
2454 /* Code to be run from time to time. */
2455 #if CHECK_OWN_SOCKET_INTERVAL > 0
2456 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
2458 check_own_socket ();
2459 last_minute = time (NULL);
2463 /* Need to check for expired cache entries. */
2464 agent_cache_housekeeping ();
2466 /* Check whether the homedir is still available. */
2467 if (!shutdown_pending
2468 && (!have_homedir_inotify || !reliable_homedir_inotify)
2469 && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2471 shutdown_pending = 1;
2472 log_info ("homedir has been removed - shutting down\n");
2477 /* A global function which allows us to call the reload stuff from
2478 other places too. This is only used when build for W32. */
2480 agent_sighup_action (void)
2482 log_info ("SIGHUP received - "
2483 "re-reading configuration and flushing cache\n");
2485 agent_flush_cache (0);
2486 reread_configuration ();
2487 agent_reload_trustlist ();
2488 /* We flush the module name cache so that after installing a
2489 "pinentry" binary that one can be used in case the
2490 "pinentry-basic" fallback was in use. */
2491 gnupg_module_name_flush_some ();
2493 if (opt.disable_daemon[DAEMON_SCD])
2494 agent_kill_daemon (DAEMON_SCD);
2498 /* A helper function to handle SIGUSR2. */
2500 agent_sigusr2_action (void)
2503 log_info ("SIGUSR2 received - updating card event counter\n");
2504 /* Nothing to check right now. We only increment a counter. */
2505 bump_card_eventcounter ();
2509 #ifndef HAVE_W32_SYSTEM
2510 /* The signal handler for this program. It is expected to be run in
2511 its own thread and not in the context of a signal handler. */
2513 handle_signal (int signo)
2517 #ifndef HAVE_W32_SYSTEM
2519 agent_sighup_action ();
2523 log_info ("SIGUSR1 received - printing internal information:\n");
2524 /* Fixme: We need to see how to integrate pth dumping into our
2526 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2527 agent_query_dump_state ();
2528 agent_daemon_dump_state ();
2532 agent_sigusr2_action ();
2536 if (!shutdown_pending)
2537 log_info ("SIGTERM received - shutting down ...\n");
2539 log_info ("SIGTERM received - still %i open connections\n",
2540 active_connections);
2542 if (shutdown_pending > 2)
2544 log_info ("shutdown forced\n");
2545 log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2552 log_info ("SIGINT received - immediate shutdown\n");
2553 log_info( "%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2559 log_info ("signal %d received - no action defined\n", signo);
2564 /* Check the nonce on a new connection. This is a NOP unless we
2565 are using our Unix domain socket emulation under Windows. */
2567 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2569 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2571 log_info (_("error reading nonce on fd %d: %s\n"),
2572 FD2INT(ctrl->thread_startup.fd), strerror (errno));
2573 assuan_sock_close (ctrl->thread_startup.fd);
2582 #ifdef HAVE_W32_SYSTEM
2583 /* The window message processing function for Putty. Warning: This
2584 code runs as a native Windows thread. Use of our own functions
2585 needs to be bracket with pth_leave/pth_enter. */
2586 static LRESULT CALLBACK
2587 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2591 COPYDATASTRUCT *cds;
2592 const char *mapfile;
2597 PSECURITY_DESCRIPTOR psd = NULL;
2600 if (msg != WM_COPYDATA)
2602 return DefWindowProc (hwnd, msg, wparam, lparam);
2605 cds = (COPYDATASTRUCT*)lparam;
2606 if (cds->dwData != PUTTY_IPC_MAGIC)
2607 return 0; /* Ignore data with the wrong magic. */
2608 mapfile = cds->lpData;
2609 if (!cds->cbData || mapfile[cds->cbData - 1])
2610 return 0; /* Ignore empty and non-properly terminated strings. */
2615 log_debug ("ssh map file '%s'", mapfile);
2619 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2623 log_debug ("ssh map handle %p\n", maphd);
2627 if (!maphd || maphd == INVALID_HANDLE_VALUE)
2632 mysid = w32_get_user_sid ();
2635 log_error ("error getting my sid\n");
2639 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2640 OWNER_SECURITY_INFORMATION,
2641 &mapsid, NULL, NULL, NULL,
2645 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2653 if (!ConvertSidToStringSid (mysid, &sidstr))
2655 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2657 if (!ConvertSidToStringSid (mapsid, &sidstr))
2659 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2663 if (!EqualSid (mysid, mapsid))
2665 log_error ("ssh map file has a non-matching sid\n");
2669 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2671 log_debug ("ssh IPC buffer at %p\n", data);
2675 /* log_printhex ("request:", data, 20); */
2677 ctrl = xtrycalloc (1, sizeof *ctrl);
2680 log_error ("error allocating connection control data: %s\n",
2684 ctrl->session_env = session_env_new ();
2685 if (!ctrl->session_env)
2687 log_error ("error allocating session environment block: %s\n",
2692 agent_init_default_ctrl (ctrl);
2693 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2694 ret = 1; /* Valid ssh message has been constructed. */
2695 agent_deinit_default_ctrl (ctrl);
2696 /* log_printhex (" reply:", data, 20); */
2701 UnmapViewOfFile (data);
2706 CloseHandle (maphd);
2712 #endif /*HAVE_W32_SYSTEM*/
2715 #ifdef HAVE_W32_SYSTEM
2716 /* The thread handling Putty's IPC requests. */
2718 putty_message_thread (void *arg)
2720 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2721 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2728 log_info ("putty message loop thread started\n");
2730 /* The message loop runs as thread independent from our nPth system.
2731 This also means that we need to make sure that we switch back to
2732 our system before calling any no-windows function. */
2735 /* First create a window to make sure that a message queue exists
2737 if (!RegisterClass (&wndwclass))
2740 log_error ("error registering Pageant window class");
2743 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2745 HWND_MESSAGE, /* hWndParent */
2746 NULL, /* hWndMenu */
2747 NULL, /* hInstance */
2752 log_error ("error creating Pageant window");
2756 while (GetMessage(&msg, NULL, 0, 0))
2758 TranslateMessage(&msg);
2759 DispatchMessage(&msg);
2766 log_info ("putty message loop thread stopped\n");
2770 #define BUFSIZE (5 * 1024)
2772 /* The thread handling Win32-OpenSSH requests through NamedPipe. */
2774 win32_openssh_thread (void *arg)
2781 log_info ("Win32-OpenSSH thread started\n");
2786 estream_t ssh_stream = NULL;
2790 pipe = CreateNamedPipeA (win32_openssh_support, PIPE_ACCESS_DUPLEX,
2791 (PIPE_TYPE_BYTE | PIPE_READMODE_BYTE
2792 | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS),
2793 PIPE_UNLIMITED_INSTANCES,
2794 BUFSIZE, BUFSIZE, 0, NULL);
2796 if (pipe == INVALID_HANDLE_VALUE)
2799 log_error ("cannot create pipe: %ld\n", GetLastError ());
2803 if (ConnectNamedPipe (pipe, NULL) == 0)
2807 log_error ("Error at ConnectNamedPipe: %ld\n", GetLastError ());
2812 ctrl = xtrycalloc (1, sizeof *ctrl);
2816 log_error ("error allocating connection control data: %s\n",
2821 #if _WIN32_WINNT >= 0x600
2822 if (!GetNamedPipeClientProcessId (pipe, &ctrl->client_pid))
2823 log_info ("failed to get client process id: %ld\n", GetLastError ());
2825 ctrl->client_uid = -1;
2828 ctrl->session_env = session_env_new ();
2829 if (!ctrl->session_env)
2831 log_error ("error allocating session environment block: %s\n",
2833 agent_deinit_default_ctrl (ctrl);
2838 agent_init_default_ctrl (ctrl);
2840 syshd.type = ES_SYSHD_HANDLE;
2841 syshd.u.handle = pipe;
2842 ssh_stream = es_sysopen (&syshd, "r+b");
2845 agent_deinit_default_ctrl (ctrl);
2851 start_command_handler_ssh_stream (ctrl, ssh_stream);
2853 agent_deinit_default_ctrl (ctrl);
2859 log_info ("Win32-OpenSSH thread stopped\n");
2862 #endif /*HAVE_W32_SYSTEM*/
2866 do_start_connection_thread (ctrl_t ctrl)
2868 active_connections++;
2869 agent_init_default_ctrl (ctrl);
2870 if (opt.verbose > 1 && !DBG_IPC)
2871 log_info (_("handler 0x%lx for fd %d started\n"),
2872 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2874 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2875 if (opt.verbose > 1 && !DBG_IPC)
2876 log_info (_("handler 0x%lx for fd %d terminated\n"),
2877 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2879 agent_deinit_default_ctrl (ctrl);
2881 active_connections--;
2886 /* This is the standard connection thread's main function. */
2888 start_connection_thread_std (void *arg)
2892 if (check_nonce (ctrl, &socket_nonce))
2894 log_error ("handler 0x%lx nonce check FAILED\n",
2895 (unsigned long) npth_self());
2899 return do_start_connection_thread (ctrl);
2903 /* This is the extra socket connection thread's main function. */
2905 start_connection_thread_extra (void *arg)
2909 if (check_nonce (ctrl, &socket_nonce_extra))
2911 log_error ("handler 0x%lx nonce check FAILED\n",
2912 (unsigned long) npth_self());
2916 ctrl->restricted = 1;
2917 return do_start_connection_thread (ctrl);
2921 /* This is the browser socket connection thread's main function. */
2923 start_connection_thread_browser (void *arg)
2927 if (check_nonce (ctrl, &socket_nonce_browser))
2929 log_error ("handler 0x%lx nonce check FAILED\n",
2930 (unsigned long) npth_self());
2934 ctrl->restricted = 2;
2935 return do_start_connection_thread (ctrl);
2939 /* This is the ssh connection thread's main function. */
2941 start_connection_thread_ssh (void *arg)
2945 if (check_nonce (ctrl, &socket_nonce_ssh))
2948 active_connections++;
2949 agent_init_default_ctrl (ctrl);
2951 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2952 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2954 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2956 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2957 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2959 agent_deinit_default_ctrl (ctrl);
2961 active_connections--;
2966 /* Connection handler loop. Wait for connection requests and spawn a
2967 thread after accepting a connection. */
2969 handle_connections (gnupg_fd_t listen_fd,
2970 gnupg_fd_t listen_fd_extra,
2971 gnupg_fd_t listen_fd_browser,
2972 gnupg_fd_t listen_fd_ssh)
2976 struct sockaddr_un paddr;
2978 fd_set fdset, read_fdset;
2983 struct timespec abstime;
2984 struct timespec curtime;
2985 struct timespec timeout;
2986 #ifdef HAVE_W32_SYSTEM
2988 unsigned int events_set;
2990 int sock_inotify_fd = -1;
2991 int home_inotify_fd = -1;
2994 void *(*func) (void *arg);
2997 { "std", start_connection_thread_std },
2998 { "extra", start_connection_thread_extra },
2999 { "browser", start_connection_thread_browser },
3000 { "ssh", start_connection_thread_ssh }
3004 ret = npth_attr_init(&tattr);
3006 log_fatal ("error allocating thread attributes: %s\n",
3008 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3010 #ifndef HAVE_W32_SYSTEM
3012 npth_sigev_add (SIGHUP);
3013 npth_sigev_add (SIGUSR1);
3014 npth_sigev_add (SIGUSR2);
3015 npth_sigev_add (SIGINT);
3016 npth_sigev_add (SIGTERM);
3019 events[0] = get_agent_daemon_notify_event ();
3020 events[1] = INVALID_HANDLE_VALUE;
3023 if (disable_check_own_socket)
3024 sock_inotify_fd = -1;
3025 else if ((err = gnupg_inotify_watch_socket (&sock_inotify_fd, socket_name)))
3027 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
3028 log_info ("error enabling daemon termination by socket removal: %s\n",
3029 gpg_strerror (err));
3032 if (disable_check_own_socket)
3033 home_inotify_fd = -1;
3034 else if ((err = gnupg_inotify_watch_delete_self (&home_inotify_fd,
3037 if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
3038 log_info ("error enabling daemon termination by homedir removal: %s\n",
3039 gpg_strerror (err));
3042 have_homedir_inotify = 1;
3044 /* On Windows we need to fire up a separate thread to listen for
3045 requests from Putty (an SSH client), so we can replace Putty's
3046 Pageant (its ssh-agent implementation). */
3047 #ifdef HAVE_W32_SYSTEM
3052 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
3054 log_error ("error spawning putty message loop: %s\n", strerror (ret));
3057 if (win32_openssh_support)
3061 ret = npth_create (&thread, &tattr, win32_openssh_thread, NULL);
3063 log_error ("error spawning Win32-OpenSSH loop: %s\n", strerror (ret));
3065 #endif /*HAVE_W32_SYSTEM*/
3067 /* Set a flag to tell call-scd.c that it may enable event
3069 opt.sigusr2_enabled = 1;
3072 FD_SET (FD2INT (listen_fd), &fdset);
3073 nfd = FD2INT (listen_fd);
3074 if (listen_fd_extra != GNUPG_INVALID_FD)
3076 FD_SET ( FD2INT(listen_fd_extra), &fdset);
3077 if (FD2INT (listen_fd_extra) > nfd)
3078 nfd = FD2INT (listen_fd_extra);
3080 if (listen_fd_browser != GNUPG_INVALID_FD)
3082 FD_SET ( FD2INT(listen_fd_browser), &fdset);
3083 if (FD2INT (listen_fd_browser) > nfd)
3084 nfd = FD2INT (listen_fd_browser);
3086 if (listen_fd_ssh != GNUPG_INVALID_FD)
3088 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
3089 if (FD2INT (listen_fd_ssh) > nfd)
3090 nfd = FD2INT (listen_fd_ssh);
3092 if (sock_inotify_fd != -1)
3094 FD_SET (sock_inotify_fd, &fdset);
3095 if (sock_inotify_fd > nfd)
3096 nfd = sock_inotify_fd;
3098 if (home_inotify_fd != -1)
3100 FD_SET (home_inotify_fd, &fdset);
3101 if (home_inotify_fd > nfd)
3102 nfd = home_inotify_fd;
3105 listentbl[0].l_fd = listen_fd;
3106 listentbl[1].l_fd = listen_fd_extra;
3107 listentbl[2].l_fd = listen_fd_browser;
3108 listentbl[3].l_fd = listen_fd_ssh;
3110 npth_clock_gettime (&abstime);
3111 abstime.tv_sec += TIMERTICK_INTERVAL;
3115 /* Shutdown test. */
3116 if (shutdown_pending)
3118 if (active_connections == 0)
3121 /* Do not accept new connections but keep on running the
3122 * loop to cope with the timer events.
3124 * Note that we do not close the listening socket because a
3125 * client trying to connect to that socket would instead
3126 * restart a new dirmngr instance - which is unlikely the
3127 * intention of a shutdown. */
3130 if (sock_inotify_fd != -1)
3132 FD_SET (sock_inotify_fd, &fdset);
3133 nfd = sock_inotify_fd;
3135 if (home_inotify_fd != -1)
3137 FD_SET (home_inotify_fd, &fdset);
3138 if (home_inotify_fd > nfd)
3139 nfd = home_inotify_fd;
3143 /* POSIX says that fd_set should be implemented as a structure,
3144 thus a simple assignment is fine to copy the entire set. */
3147 npth_clock_gettime (&curtime);
3148 if (!(npth_timercmp (&curtime, &abstime, <)))
3152 npth_clock_gettime (&abstime);
3153 abstime.tv_sec += TIMERTICK_INTERVAL;
3155 npth_timersub (&abstime, &curtime, &timeout);
3157 #ifndef HAVE_W32_SYSTEM
3158 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
3159 npth_sigev_sigmask ());
3160 saved_errno = errno;
3164 while (npth_sigev_get_pending (&signo))
3165 handle_signal (signo);
3168 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
3169 events, &events_set);
3170 saved_errno = errno;
3172 /* This is valid even if npth_eselect returns an error. */
3174 agent_sigusr2_action ();
3177 if (ret == -1 && saved_errno != EINTR)
3179 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
3180 strerror (saved_errno));
3185 /* Interrupt or timeout. Will be handled when calculating the
3189 /* The inotify fds are set even when a shutdown is pending (see
3190 * above). So we must handle them in any case. To avoid that
3191 * they trigger a second time we close them immediately. */
3192 if (sock_inotify_fd != -1
3193 && FD_ISSET (sock_inotify_fd, &read_fdset)
3194 && gnupg_inotify_has_name (sock_inotify_fd, GPG_AGENT_SOCK_NAME))
3196 shutdown_pending = 1;
3197 close (sock_inotify_fd);
3198 sock_inotify_fd = -1;
3199 log_info ("socket file has been removed - shutting down\n");
3202 if (home_inotify_fd != -1
3203 && FD_ISSET (home_inotify_fd, &read_fdset))
3205 shutdown_pending = 1;
3206 close (home_inotify_fd);
3207 home_inotify_fd = -1;
3208 log_info ("homedir has been removed - shutting down\n");
3211 if (!shutdown_pending)
3217 for (idx=0; idx < DIM(listentbl); idx++)
3219 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
3221 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
3224 plen = sizeof paddr;
3225 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
3226 (struct sockaddr *)&paddr, &plen));
3227 if (fd == GNUPG_INVALID_FD)
3229 log_error ("accept failed for %s: %s\n",
3230 listentbl[idx].name, strerror (errno));
3232 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
3234 log_error ("error allocating connection data for %s: %s\n",
3235 listentbl[idx].name, strerror (errno) );
3236 assuan_sock_close (fd);
3238 else if ( !(ctrl->session_env = session_env_new ()))
3240 log_error ("error allocating session env block for %s: %s\n",
3241 listentbl[idx].name, strerror (errno) );
3243 assuan_sock_close (fd);
3247 ctrl->thread_startup.fd = fd;
3248 ret = npth_create (&thread, &tattr,
3249 listentbl[idx].func, ctrl);
3252 log_error ("error spawning connection handler for %s:"
3253 " %s\n", listentbl[idx].name, strerror (ret));
3254 assuan_sock_close (fd);
3262 if (sock_inotify_fd != -1)
3263 close (sock_inotify_fd);
3264 if (home_inotify_fd != -1)
3265 close (home_inotify_fd);
3267 log_info (_("%s %s stopped\n"), gpgrt_strusage(11), gpgrt_strusage(13));
3268 npth_attr_destroy (&tattr);
3273 /* Helper for check_own_socket. */
3275 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
3277 membuf_t *mb = opaque;
3278 put_membuf (mb, buffer, length);
3283 /* The thread running the actual check. We need to run this in a
3284 separate thread so that check_own_thread can be called from the
3287 check_own_socket_thread (void *arg)
3290 char *sockname = arg;
3291 assuan_context_t ctx = NULL;
3295 check_own_socket_running++;
3297 rc = assuan_new (&ctx);
3300 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
3303 assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
3305 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3308 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
3312 init_membuf (&mb, 100);
3313 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
3314 NULL, NULL, NULL, NULL);
3315 put_membuf (&mb, "", 1);
3316 buffer = get_membuf (&mb, NULL);
3319 log_error ("sending command \"%s\" to my own socket failed: %s\n",
3320 "GETINFO pid", gpg_strerror (rc));
3323 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
3325 log_error ("socket is now serviced by another server\n");
3328 else if (opt.verbose > 1)
3329 log_error ("socket is still served by this server\n");
3336 assuan_release (ctx);
3339 /* We may not remove the socket as it is now in use by another
3341 inhibit_socket_removal = 1;
3342 shutdown_pending = 2;
3343 log_info ("this process is useless - shutting down\n");
3345 check_own_socket_running--;
3350 /* Check whether we are still listening on our own socket. In case
3351 another gpg-agent process started after us has taken ownership of
3352 our socket, we would linger around without any real task. Thus we
3353 better check once in a while whether we are really needed. */
3355 check_own_socket (void)
3362 if (disable_check_own_socket)
3365 if (check_own_socket_running || shutdown_pending)
3366 return; /* Still running or already shutting down. */
3368 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3370 return; /* Out of memory. */
3372 err = npth_attr_init (&tattr);
3378 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3379 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
3381 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
3382 npth_attr_destroy (&tattr);
3387 /* Figure out whether an agent is available and running. Prints an
3388 error if not. If SILENT is true, no messages are printed.
3389 Returns 0 if the agent is running. */
3391 check_for_running_agent (int silent)
3395 assuan_context_t ctx = NULL;
3397 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3399 return gpg_error_from_syserror ();
3401 err = assuan_new (&ctx);
3403 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3408 log_error (_("no gpg-agent running in this session\n"));
3411 assuan_release (ctx);
3415 if (!opt.quiet && !silent)
3416 log_info ("gpg-agent running and available\n");
3418 assuan_release (ctx);