1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc.
3 * Copyright (C) 2000-2014 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
33 #ifdef HAVE_W32_SYSTEM
35 # define WINVER 0x0500 /* Same as in common/sysutils.c */
37 # ifdef HAVE_WINSOCK2_H
38 # include <winsock2.h>
42 #else /*!HAVE_W32_SYSTEM*/
43 # include <sys/socket.h>
45 #endif /*!HAVE_W32_SYSTEM*/
52 #define JNLIB_NEED_LOG_LOGV
53 #define JNLIB_NEED_AFLOCAL
55 #include <assuan.h> /* Malloc hooks and socket wrappers. */
59 #include "gc-opt-flags.h"
62 #include "openpgpdefs.h" /* for PUBKEY_ALGO_ECDSA, PUBKEY_ALGO_ECDH */
63 #include "../common/init.h"
66 enum cmd_and_opt_values
106 oEnforcePassphraseConstraints,
108 oMinPassphraseNonalpha,
109 oCheckPassphrasePattern,
111 oEnablePassphraseHistory,
113 oNoUseStandardSocket,
117 oIgnoreCacheForSigning,
120 oAllowPresetPassphrase,
121 oAllowLoopbackPinentry,
127 oDisableCheckOwnSocket,
133 # define ENAMETOOLONG EINVAL
137 static ARGPARSE_OPTS opts[] = {
139 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
140 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
141 ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
143 ARGPARSE_group (301, N_("@Options:\n ")),
145 ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
146 ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
147 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
148 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
149 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
150 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
151 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
153 ARGPARSE_s_u (oDebug, "debug", "@"),
154 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
155 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
156 ARGPARSE_s_i (oDebugWait," debug-wait", "@"),
157 ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
159 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
160 ARGPARSE_s_n (oNoGrab, "no-grab", N_("do not grab keyboard and mouse")),
161 ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
162 ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
163 /* */ N_("|PGM|use PGM as the PIN-Entry program")),
164 ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
165 ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
166 /* */ N_("|PGM|use PGM as the SCdaemon program") ),
167 ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
168 /* */ N_("do not use the SCdaemon") ),
169 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
170 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
172 ARGPARSE_s_n (oBatch, "batch", "@"),
173 ARGPARSE_s_s (oHomedir, "homedir", "@"),
175 ARGPARSE_s_s (oDisplay, "display", "@"),
176 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
177 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
178 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
179 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
180 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
181 ARGPARSE_s_n (oKeepTTY, "keep-tty",
182 /* */ N_("ignore requests to change the TTY")),
183 ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
184 /* */ N_("ignore requests to change the X display")),
186 ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
187 N_("|N|expire cached PINs after N seconds")),
188 ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
189 ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
190 ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
192 ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
194 ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
195 ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
196 ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
197 ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
198 ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
200 ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
201 /* */ N_("do not use the PIN cache when signing")),
202 ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
203 /* */ N_("disallow clients to mark keys as \"trusted\"")),
204 ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
205 ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
206 /* */ N_("allow presetting passphrase")),
207 ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry",
208 N_("allow caller to override the pinentry")),
209 ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
210 ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
211 #ifdef HAVE_W32_SYSTEM
212 /* */ N_("enable putty support")
217 ARGPARSE_s_s (oExtraSocket, "extra-socket", "@"),
219 /* Dummy options for backward compatibility. */
220 ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
221 ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
222 ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
224 {0} /* End of list */
228 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
229 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
230 #define MAX_CACHE_TTL (120*60) /* 2 hours */
231 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
232 #define MIN_PASSPHRASE_LEN (8)
233 #define MIN_PASSPHRASE_NONALPHA (1)
234 #define MAX_PASSPHRASE_DAYS (0)
236 /* The timer tick used for housekeeping stuff. For Windows we use a
237 longer period as the SetWaitableTimer seems to signal earlier than
238 the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
239 check our own socket in standard socket mode. If that value is 0
240 we don't check at all. All values are in seconds. */
241 #if defined(HAVE_W32CE_SYSTEM)
242 # define TIMERTICK_INTERVAL (60)
243 # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
244 #elif defined(HAVE_W32_SYSTEM)
245 # define TIMERTICK_INTERVAL (4)
246 # define CHECK_OWN_SOCKET_INTERVAL (60)
248 # define TIMERTICK_INTERVAL (2)
249 # define CHECK_OWN_SOCKET_INTERVAL (60)
253 #ifdef HAVE_W32_SYSTEM
254 /* Flag indicating that support for Putty has been enabled. */
255 static int putty_support;
256 /* A magic value used with WM_COPYDATA. */
257 #define PUTTY_IPC_MAGIC 0x804e50ba
258 /* To avoid surprises we limit the size of the mapped IPC file to this
259 value. Putty currently (0.62) uses 8k, thus 16k should be enough
260 for the foreseeable future. */
261 #define PUTTY_IPC_MAXLEN 16384
262 #endif /*HAVE_W32_SYSTEM*/
264 /* The list of open file descriptors at startup. Note that this list
265 has been allocated using the standard malloc. */
266 static int *startup_fd_list;
268 /* The signal mask at startup and a flag telling whether it is valid. */
269 #ifdef HAVE_SIGPROCMASK
270 static sigset_t startup_signal_mask;
271 static int startup_signal_mask_valid;
274 /* Flag to indicate that a shutdown was requested. */
275 static int shutdown_pending;
277 /* Counter for the currently running own socket checks. */
278 static int check_own_socket_running;
280 /* Flags to indicate that check_own_socket shall not be called. */
281 static int disable_check_own_socket;
283 /* It is possible that we are currently running under setuid permissions */
284 static int maybe_setuid = 1;
286 /* Name of the communication socket used for native gpg-agent
287 requests. The second variable is either NULL or a malloced string
288 with the real socket name in case it has been redirected. */
289 static char *socket_name;
290 static char *redir_socket_name;
292 /* Name of the optional extra socket used for native gpg-agent requests. */
293 static char *socket_name_extra;
294 static char *redir_socket_name_extra;
296 /* Name of the communication socket used for ssh-agent-emulation. */
297 static char *socket_name_ssh;
298 static char *redir_socket_name_ssh;
300 /* We need to keep track of the server's nonces (these are dummies for
302 static assuan_sock_nonce_t socket_nonce;
303 static assuan_sock_nonce_t socket_nonce_extra;
304 static assuan_sock_nonce_t socket_nonce_ssh;
307 /* Default values for options passed to the pinentry. */
308 static char *default_display;
309 static char *default_ttyname;
310 static char *default_ttytype;
311 static char *default_lc_ctype;
312 static char *default_lc_messages;
313 static char *default_xauthority;
315 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
316 static char *config_filename;
318 /* Helper to implement --debug-level */
319 static const char *debug_level;
321 /* Keep track of the current log file so that we can avoid updating
322 the log file after a SIGHUP if it didn't changed. Malloced. */
323 static char *current_logfile;
325 /* The handle_tick() function may test whether a parent is still
326 running. We record the PID of the parent here or -1 if it should be
328 static pid_t parent_pid = (pid_t)(-1);
330 /* Number of active connections. */
331 static int active_connections;
338 static char *create_socket_name (char *standard_name, int with_homedir);
339 static gnupg_fd_t create_server_socket (char *name, int primary,
341 assuan_sock_nonce_t *nonce);
342 static void create_directories (void);
344 static void agent_init_default_ctrl (ctrl_t ctrl);
345 static void agent_deinit_default_ctrl (ctrl_t ctrl);
347 static void handle_connections (gnupg_fd_t listen_fd,
348 gnupg_fd_t listen_fd_extra,
349 gnupg_fd_t listen_fd_ssh);
350 static void check_own_socket (void);
351 static int check_for_running_agent (int silent);
353 /* Pth wrapper function definitions. */
354 ASSUAN_SYSTEM_NPTH_IMPL;
361 /* Allocate a string describing a library version by calling a GETFNC.
362 This function is expected to be called only once. GETFNC is
363 expected to have a semantic like gcry_check_version (). */
365 make_libversion (const char *libname, const char *(*getfnc)(const char*))
372 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
376 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
377 strcpy (stpcpy (stpcpy (result, libname), " "), s);
381 /* Return strings describing this program. The case values are
382 described in common/argparse.c:strusage. The values here override
383 the default values given by strusage. */
385 my_strusage (int level)
387 static char *ver_gcry;
392 case 11: p = "@GPG_AGENT@ (@GNUPG@)";
394 case 13: p = VERSION; break;
395 case 17: p = PRINTABLE_OS_NAME; break;
396 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
397 reporting address. This is so that we can change the
398 reporting address without breaking the translations. */
399 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
403 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
408 case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
410 case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
411 "Secret key management for @GNUPG@\n");
421 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
422 only the active debug flags are propagated to the subsystems. With
423 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
424 all flags already set. Note that we don't fail here, because it is
425 important to keep gpg-agent running even after re-reading the
426 options due to a SIGHUP. */
430 int numok = (debug_level && digitp (debug_level));
431 int numlvl = numok? atoi (debug_level) : 0;
435 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
437 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
438 opt.debug = DBG_ASSUAN_VALUE;
439 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
440 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
441 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
442 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
444 else if (!strcmp (debug_level, "guru") || numok)
447 /* Unless the "guru" string has been used we don't want to allow
448 hashing debugging. The rationale is that people tend to
449 select the highest debug value and would then clutter their
450 disk with debug files which may reveal confidential data. */
452 opt.debug &= ~(DBG_HASHING_VALUE);
456 log_error (_("invalid debug-level '%s' given\n"), debug_level);
457 opt.debug = 0; /* Reset debugging, so that prior debug
458 statements won't have an undesired effect. */
461 if (opt.debug && !opt.verbose)
463 if (opt.debug && opt.quiet)
466 if (opt.debug & DBG_MPI_VALUE)
467 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
468 if (opt.debug & DBG_CRYPTO_VALUE )
469 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
470 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
473 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
474 (opt.debug & DBG_COMMAND_VALUE)? " command":"",
475 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
476 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
477 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
478 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
479 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
480 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
481 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
485 /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
486 the corresponding real name if the socket has been redirected. */
488 remove_socket (char *name, char *redir_name)
498 p = strrchr (name, '/');
510 /* Cleanup code for this program. This is either called has an atexit
511 handler or directly. */
520 deinitialize_module_cache ();
521 remove_socket (socket_name, redir_socket_name);
522 if (opt.extra_socket > 1)
523 remove_socket (socket_name_extra, redir_socket_name_extra);
524 remove_socket (socket_name_ssh, redir_socket_name_ssh);
529 /* Handle options which are allowed to be reset after program start.
530 Return true when the current option in PARGS could be handled and
531 false if not. As a special feature, passing a value of NULL for
532 PARGS, resets the options to the default. REREAD should be set
533 true if it is not the initial option parsing. */
535 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
543 opt.pinentry_program = NULL;
544 opt.pinentry_touch_file = NULL;
545 opt.scdaemon_program = NULL;
546 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
547 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
548 opt.max_cache_ttl = MAX_CACHE_TTL;
549 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
550 opt.enforce_passphrase_constraints = 0;
551 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
552 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
553 opt.check_passphrase_pattern = NULL;
554 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
555 opt.enable_passhrase_history = 0;
556 opt.ignore_cache_for_signing = 0;
557 opt.allow_mark_trusted = 1;
558 opt.disable_scdaemon = 0;
559 disable_check_own_socket = 0;
563 switch (pargs->r_opt)
565 case oQuiet: opt.quiet = 1; break;
566 case oVerbose: opt.verbose++; break;
568 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
569 case oDebugAll: opt.debug = ~0; break;
570 case oDebugLevel: debug_level = pargs->r.ret_str; break;
574 return 0; /* not handeld */
575 if (!current_logfile || !pargs->r.ret_str
576 || strcmp (current_logfile, pargs->r.ret_str))
578 log_set_file (pargs->r.ret_str);
579 xfree (current_logfile);
580 current_logfile = xtrystrdup (pargs->r.ret_str);
584 case oNoGrab: opt.no_grab = 1; break;
586 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
587 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
588 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
589 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
590 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
592 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
593 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
594 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
595 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
597 case oEnforcePassphraseConstraints:
598 opt.enforce_passphrase_constraints=1;
600 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
601 case oMinPassphraseNonalpha:
602 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
604 case oCheckPassphrasePattern:
605 opt.check_passphrase_pattern = pargs->r.ret_str;
607 case oMaxPassphraseDays:
608 opt.max_passphrase_days = pargs->r.ret_ulong;
610 case oEnablePassphraseHistory:
611 opt.enable_passhrase_history = 1;
614 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
616 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
617 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
619 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
621 case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
624 return 0; /* not handled */
627 return 1; /* handled */
631 /* Fixup some options after all have been processed. */
633 finalize_rereadable_options (void)
635 /* It would be too surprising if the max-cache-ttl is lower than the
636 default-cache-ttl - thus we silently correct that. */
637 if (opt.def_cache_ttl > opt.max_cache_ttl)
638 opt.max_cache_ttl = opt.def_cache_ttl;
639 if (opt.def_cache_ttl_ssh > opt.max_cache_ttl_ssh)
640 opt.max_cache_ttl_ssh = opt.def_cache_ttl_ssh;
645 /* The main entry point. */
647 main (int argc, char **argv )
652 FILE *configfp = NULL;
653 char *configname = NULL;
655 unsigned configlineno;
657 int default_config =1;
662 char *logfile = NULL;
664 int gpgconf_list = 0;
666 struct assuan_malloc_hooks malloc_hooks;
668 early_system_init ();
670 /* Before we do anything else we save the list of currently open
671 file descriptors and the signal mask. This info is required to
672 do the exec call properly. */
673 startup_fd_list = get_all_open_fds ();
674 #ifdef HAVE_SIGPROCMASK
675 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
676 startup_signal_mask_valid = 1;
677 #endif /*HAVE_SIGPROCMASK*/
679 /* Set program name etc. */
680 set_strusage (my_strusage);
681 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
682 /* Please note that we may running SUID(ROOT), so be very CAREFUL
683 when adding any stuff between here and the call to INIT_SECMEM()
684 somewhere after the option parsing */
685 log_set_prefix (GPG_AGENT_NAME, JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
687 /* Make sure that our subsystems are ready. */
689 init_common_subsystems (&argc, &argv);
693 /* Check that the libraries are suitable. Do it here because
694 the option parsing may need services of the library. */
695 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
697 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
698 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
701 malloc_hooks.malloc = gcry_malloc;
702 malloc_hooks.realloc = gcry_realloc;
703 malloc_hooks.free = gcry_free;
704 assuan_set_malloc_hooks (&malloc_hooks);
705 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
706 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
708 setup_libassuan_logging (&opt.debug);
710 setup_libgcrypt_logging ();
711 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
713 disable_core_dumps ();
715 /* Set default options. */
716 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
718 shell = getenv ("SHELL");
719 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
722 opt.homedir = default_homedir ();
724 /* Record some of the original environment strings. */
728 static const char *names[] =
729 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
732 opt.startup_env = session_env_new ();
733 if (!opt.startup_env)
734 err = gpg_error_from_syserror ();
735 for (idx=0; !err && names[idx]; idx++)
737 s = getenv (names[idx]);
739 err = session_env_setenv (opt.startup_env, names[idx], s);
743 s = gnupg_ttyname (0);
745 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
748 log_fatal ("error recording startup environment: %s\n",
751 /* Fixme: Better use the locale function here. */
752 opt.startup_lc_ctype = getenv ("LC_CTYPE");
753 if (opt.startup_lc_ctype)
754 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
755 opt.startup_lc_messages = getenv ("LC_MESSAGES");
756 if (opt.startup_lc_messages)
757 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
760 /* Check whether we have a config file on the commandline */
765 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
766 while (arg_parse( &pargs, opts))
768 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
770 else if (pargs.r_opt == oOptions)
771 { /* yes there is one, so we do not try the default one, but
772 read the option file when it is encountered at the
776 else if (pargs.r_opt == oNoOptions)
777 default_config = 0; /* --no-options */
778 else if (pargs.r_opt == oHomedir)
779 opt.homedir = pargs.r.ret_str;
780 else if (pargs.r_opt == oDebugQuickRandom)
782 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
787 /* Initialize the secure memory. */
788 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
792 Now we are now working under our real uid
796 configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
803 pargs.flags= 1; /* do not remove the args */
808 configfp = fopen (configname, "r");
814 log_info (_("Note: no default option file '%s'\n"),
816 /* Save the default conf file name so that
817 reread_configuration is able to test whether the
818 config file has been created in the meantime. */
819 xfree (config_filename);
820 config_filename = configname;
825 log_error (_("option file '%s': %s\n"),
826 configname, strerror(errno) );
832 if (parse_debug && configname )
833 log_info (_("reading options from '%s'\n"), configname );
837 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
839 if (parse_rereadable_options (&pargs, 0))
840 continue; /* Already handled */
843 case aGPGConfList: gpgconf_list = 1; break;
844 case aGPGConfTest: gpgconf_list = 2; break;
845 case aUseStandardSocketP: gpgconf_list = 3; break;
846 case oBatch: opt.batch=1; break;
848 case oDebugWait: debug_wait = pargs.r.ret_int; break;
851 /* config files may not be nested (silently ignore them) */
855 configname = xstrdup(pargs.r.ret_str);
859 case oNoGreeting: /* Dummy option. */ break;
860 case oNoVerbose: opt.verbose = 0; break;
861 case oNoOptions: break; /* no-options */
862 case oHomedir: opt.homedir = pargs.r.ret_str; break;
863 case oNoDetach: nodetach = 1; break;
864 case oLogFile: logfile = pargs.r.ret_str; break;
865 case oCsh: csh_style = 1; break;
866 case oSh: csh_style = 0; break;
867 case oServer: pipe_server = 1; break;
868 case oDaemon: is_daemon = 1; break;
870 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
871 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
872 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
873 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
874 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
876 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
879 case oUseStandardSocket: /* dummy */ break;
880 case oNoUseStandardSocket: /* dummy */ break;
882 case oFakedSystemTime:
884 time_t faked_time = isotime2epoch (pargs.r.ret_str);
885 if (faked_time == (time_t)(-1))
886 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
887 gnupg_set_time (faked_time, 0);
891 case oKeepTTY: opt.keep_tty = 1; break;
892 case oKeepDISPLAY: opt.keep_display = 1; break;
894 case oSSHSupport: opt.ssh_support = 1; break;
896 # ifdef HAVE_W32_SYSTEM
903 opt.extra_socket = 1; /* (1 = points into argv) */
904 socket_name_extra = pargs.r.ret_str;
907 case oDebugQuickRandom:
908 /* Only used by the first stage command line parser. */
911 case oWriteEnvFile: /* dummy */ break;
913 default : pargs.err = configfp? 1:2; break;
920 /* Keep a copy of the name so that it can be read on SIGHUP. */
921 if (config_filename != configname)
923 xfree (config_filename);
924 config_filename = configname;
932 if (log_get_errorcount(0))
935 finalize_rereadable_options ();
937 /* Turn the homedir into an absolute one. */
938 opt.homedir = make_absfilename (opt.homedir, NULL);
940 /* Print a warning if an argument looks like an option. */
941 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
945 for (i=0; i < argc; i++)
946 if (argv[i][0] == '-' && argv[i][1] == '-')
947 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
951 /* gpg-agent usually does not output any messages because it runs in
952 the background. For log files it is acceptable to have messages
953 always encoded in utf-8. We switch here to utf-8, so that
954 commands like --help still give native messages. It is far
955 easier to switch only once instead of for every message and it
956 actually helps when more then one thread is active (avoids an
958 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
961 if (!pipe_server && !is_daemon && !gpgconf_list)
963 /* We have been called without any options and thus we merely
964 check whether an agent is already running. We do this right
965 here so that we don't clobber a logfile with this check but
966 print the status directly to stderr. */
969 check_for_running_agent (0);
975 if (atexit (cleanup))
977 log_error ("atexit failed\n");
982 initialize_module_cache ();
983 initialize_module_call_pinentry ();
984 initialize_module_call_scd ();
985 initialize_module_trustlist ();
987 /* Try to create missing directories. */
988 create_directories ();
990 if (debug_wait && pipe_server)
992 log_debug ("waiting for debugger - my pid is %u .....\n",
993 (unsigned int)getpid());
994 gnupg_sleep (debug_wait);
995 log_debug ("... okay\n");
998 if (gpgconf_list == 3)
1000 /* We now use the standard socket always - return true for
1001 backward compatibility. */
1004 else if (gpgconf_list == 2)
1006 else if (gpgconf_list)
1011 /* List options and default values in the GPG Conf format. */
1012 filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
1014 filename_esc = percent_escape (filename, NULL);
1016 es_printf ("%s-%s.conf:%lu:\"%s\n",
1017 GPGCONF_NAME, GPG_AGENT_NAME,
1018 GC_OPT_FLAG_DEFAULT, filename_esc);
1020 xfree (filename_esc);
1022 es_printf ("verbose:%lu:\n"
1024 "debug-level:%lu:\"none:\n"
1026 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1027 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1028 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1029 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1030 es_printf ("default-cache-ttl:%lu:%d:\n",
1031 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1032 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1033 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1034 es_printf ("max-cache-ttl:%lu:%d:\n",
1035 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1036 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1037 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1038 es_printf ("enforce-passphrase-constraints:%lu:\n",
1039 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1040 es_printf ("min-passphrase-len:%lu:%d:\n",
1041 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1042 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1043 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1044 MIN_PASSPHRASE_NONALPHA);
1045 es_printf ("check-passphrase-pattern:%lu:\n",
1046 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1047 es_printf ("max-passphrase-days:%lu:%d:\n",
1048 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1049 MAX_PASSPHRASE_DAYS);
1050 es_printf ("enable-passphrase-history:%lu:\n",
1051 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1052 es_printf ("no-grab:%lu:\n",
1053 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1054 es_printf ("ignore-cache-for-signing:%lu:\n",
1055 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1056 es_printf ("no-allow-mark-trusted:%lu:\n",
1057 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1058 es_printf ("disable-scdaemon:%lu:\n",
1059 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1060 #ifdef HAVE_W32_SYSTEM
1061 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1063 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1065 es_printf ("allow-loopback-pinentry:%lu:\n",
1066 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1071 /* Now start with logging to a file if this is desired. */
1074 log_set_file (logfile);
1075 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
1076 |JNLIB_LOG_WITH_TIME
1077 |JNLIB_LOG_WITH_PID));
1078 current_logfile = xstrdup (logfile);
1081 /* Make sure that we have a default ttyname. */
1082 if (!default_ttyname && gnupg_ttyname (1))
1083 default_ttyname = xstrdup (gnupg_ttyname (1));
1084 if (!default_ttytype && getenv ("TERM"))
1085 default_ttytype = xstrdup (getenv ("TERM"));
1090 /* This is the simple pipe based server */
1093 ctrl = xtrycalloc (1, sizeof *ctrl);
1096 log_error ("error allocating connection control data: %s\n",
1100 ctrl->session_env = session_env_new ();
1101 if (!ctrl->session_env)
1103 log_error ("error allocating session environment block: %s\n",
1108 agent_init_default_ctrl (ctrl);
1109 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1110 agent_deinit_default_ctrl (ctrl);
1113 else if (!is_daemon)
1116 { /* Regular server mode */
1118 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1119 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1122 /* Remove the DISPLAY variable so that a pinentry does not
1123 default to a specific display. There is still a default
1124 display when gpg-agent was started using --display or a
1125 client requested this using an OPTION command. Note, that we
1126 don't do this when running in reverse daemon mode (i.e. when
1127 exec the program given as arguments). */
1128 #ifndef HAVE_W32_SYSTEM
1129 if (!opt.keep_display && !argc)
1130 gnupg_unsetenv ("DISPLAY");
1133 /* Create the sockets. */
1134 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1135 fd = create_server_socket (socket_name, 1,
1136 &redir_socket_name, &socket_nonce);
1138 if (opt.extra_socket)
1140 socket_name_extra = create_socket_name (socket_name_extra, 0);
1141 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1142 fd_extra = create_server_socket (socket_name_extra, 0,
1143 &redir_socket_name_extra,
1144 &socket_nonce_extra);
1147 if (opt.ssh_support)
1149 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1150 fd_ssh = create_server_socket (socket_name_ssh, 0,
1151 &redir_socket_name_ssh,
1155 /* If we are going to exec a program in the parent, we record
1156 the PID, so that the child may check whether the program is
1159 parent_pid = getpid ();
1162 #ifdef HAVE_W32_SYSTEM
1166 #else /*!HAVE_W32_SYSTEM*/
1168 if (pid == (pid_t)-1)
1170 log_fatal ("fork failed: %s\n", strerror (errno) );
1174 { /* We are the parent */
1175 char *infostr_ssh_sock, *infostr_ssh_valid;
1177 /* Close the socket FD. */
1180 /* The signal mask might not be correct right now and thus
1181 we restore it. That is not strictly necessary but some
1182 programs falsely assume a cleared signal mask. */
1184 #ifdef HAVE_SIGPROCMASK
1185 if (startup_signal_mask_valid)
1187 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1188 log_error ("error restoring signal mask: %s\n",
1192 log_info ("no saved signal mask\n");
1193 #endif /*HAVE_SIGPROCMASK*/
1195 /* Create the SSH info string if enabled. */
1196 if (opt.ssh_support)
1198 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1199 socket_name_ssh) < 0)
1201 log_error ("out of core\n");
1202 kill (pid, SIGTERM);
1205 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1206 (unsigned long)getpid()) < 0)
1208 log_error ("out of core\n");
1209 kill (pid, SIGTERM);
1214 *socket_name = 0; /* Don't let cleanup() remove the socket -
1215 the child should do this from now on */
1216 if (opt.extra_socket)
1217 *socket_name_extra = 0;
1218 if (opt.ssh_support)
1219 *socket_name_ssh = 0;
1222 { /* Run the program given on the commandline. */
1223 if (opt.ssh_support && (putenv (infostr_ssh_sock)
1224 || putenv (infostr_ssh_valid)))
1226 log_error ("failed to set environment: %s\n",
1228 kill (pid, SIGTERM );
1232 /* Close all the file descriptors except the standard
1233 ones and those open at startup. We explicitly don't
1234 close 0,1,2 in case something went wrong collecting
1236 close_all_fds (3, startup_fd_list);
1238 /* Run the command. */
1239 execvp (argv[0], argv);
1240 log_error ("failed to run the command: %s\n", strerror (errno));
1241 kill (pid, SIGTERM);
1246 /* Print the environment string, so that the caller can use
1247 shell's eval to set it */
1250 if (opt.ssh_support)
1252 *strchr (infostr_ssh_sock, '=') = ' ';
1253 es_printf ("setenv %s;\n", infostr_ssh_sock);
1258 if (opt.ssh_support)
1260 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1264 if (opt.ssh_support)
1266 xfree (infostr_ssh_sock);
1267 xfree (infostr_ssh_valid);
1278 /* Detach from tty and put process into a new session */
1282 unsigned int oldflags;
1284 /* Close stdin, stdout and stderr unless it is the log stream */
1285 for (i=0; i <= 2; i++)
1287 if (!log_test_fd (i) && i != fd )
1290 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1292 log_error ("failed to open '%s': %s\n",
1293 "/dev/null", strerror (errno));
1301 log_error ("setsid() failed: %s\n", strerror(errno) );
1306 log_get_prefix (&oldflags);
1307 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1308 opt.running_detached = 1;
1313 log_error ("chdir to / failed: %s\n", strerror (errno));
1318 struct sigaction sa;
1320 sa.sa_handler = SIG_IGN;
1321 sigemptyset (&sa.sa_mask);
1323 sigaction (SIGPIPE, &sa, NULL);
1325 #endif /*!HAVE_W32_SYSTEM*/
1327 log_info ("%s %s started\n", strusage(11), strusage(13) );
1328 handle_connections (fd, fd_extra, fd_ssh);
1329 assuan_sock_close (fd);
1336 /* Exit entry point. This function should be called instead of a
1341 /*FIXME: update_random_seed_file();*/
1343 /* We run our cleanup handler because that may close cipher contexts
1344 stored in secure memory and thus this needs to be done before we
1345 explicitly terminate secure memory. */
1349 /* at this time a bit annoying */
1350 if (opt.debug & DBG_MEMSTAT_VALUE)
1352 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1353 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1356 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1358 gcry_control (GCRYCTL_TERM_SECMEM );
1359 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1364 /* Each thread has its own local variables conveyed by a control
1365 structure usually identified by an argument named CTRL. This
1366 function is called immediately after allocating the control
1367 structure. Its purpose is to setup the default values for that
1368 structure. Note that some values may have already been set. */
1370 agent_init_default_ctrl (ctrl_t ctrl)
1372 assert (ctrl->session_env);
1374 /* Note we ignore malloc errors because we can't do much about it
1375 and the request will fail anyway shortly after this
1377 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1378 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1379 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1380 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1381 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1384 xfree (ctrl->lc_ctype);
1385 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1387 if (ctrl->lc_messages)
1388 xfree (ctrl->lc_messages);
1389 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1391 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1395 /* Release all resources allocated by default in the control
1396 structure. This is the counterpart to agent_init_default_ctrl. */
1398 agent_deinit_default_ctrl (ctrl_t ctrl)
1400 session_env_release (ctrl->session_env);
1403 xfree (ctrl->lc_ctype);
1404 if (ctrl->lc_messages)
1405 xfree (ctrl->lc_messages);
1409 /* Because the ssh protocol does not send us information about the
1410 current TTY setting, we use this function to use those from startup
1411 or those explictly set. This is also used for the restricted mode
1412 where we ignore requests to change the environment. */
1414 agent_copy_startup_env (ctrl_t ctrl)
1416 static const char *names[] =
1417 {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1418 gpg_error_t err = 0;
1422 for (idx=0; !err && names[idx]; idx++)
1423 if ((value = session_env_getenv (opt.startup_env, names[idx])))
1424 err = session_env_setenv (ctrl->session_env, names[idx], value);
1426 if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1427 if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1428 err = gpg_error_from_syserror ();
1430 if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1431 if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1432 err = gpg_error_from_syserror ();
1435 log_error ("error setting default session environment: %s\n",
1436 gpg_strerror (err));
1442 /* Reread parts of the configuration. Note, that this function is
1443 obviously not thread-safe and should only be called from the PTH
1446 Fixme: Due to the way the argument parsing works, we create a
1447 memory leak here for all string type arguments. There is currently
1448 no clean way to tell whether the memory for the argument has been
1449 allocated or points into the process' original arguments. Unless
1450 we have a mechanism to tell this, we need to live on with this. */
1452 reread_configuration (void)
1454 ARGPARSE_ARGS pargs;
1456 unsigned int configlineno = 0;
1459 if (!config_filename)
1460 return; /* No config file. */
1462 fp = fopen (config_filename, "r");
1465 log_info (_("option file '%s': %s\n"),
1466 config_filename, strerror(errno) );
1470 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1472 memset (&pargs, 0, sizeof pargs);
1474 pargs.argc = &dummy;
1475 pargs.flags = 1; /* do not remove the args */
1476 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1478 if (pargs.r_opt < -1)
1479 pargs.err = 1; /* Print a warning. */
1480 else /* Try to parse this option - ignore unchangeable ones. */
1481 parse_rereadable_options (&pargs, 1);
1484 finalize_rereadable_options ();
1489 /* Return the file name of the socket we are using for native
1492 get_agent_socket_name (void)
1494 const char *s = socket_name;
1496 return (s && *s)? s : NULL;
1499 /* Return the file name of the socket we are using for SSH
1502 get_agent_ssh_socket_name (void)
1504 const char *s = socket_name_ssh;
1506 return (s && *s)? s : NULL;
1510 /* Under W32, this function returns the handle of the scdaemon
1511 notification event. Calling it the first time creates that
1513 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1515 get_agent_scd_notify_event (void)
1517 static HANDLE the_event = INVALID_HANDLE_VALUE;
1519 if (the_event == INVALID_HANDLE_VALUE)
1522 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1524 /* We need to use a manual reset event object due to the way our
1525 w32-pth wait function works: If we would use an automatic
1526 reset event we are not able to figure out which handle has
1527 been signaled because at the time we single out the signaled
1528 handles using WFSO the event has already been reset due to
1530 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1532 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1533 else if (!DuplicateHandle (GetCurrentProcess(), h,
1534 GetCurrentProcess(), &h2,
1535 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1537 log_error ("setting syncronize for scd notify event failed: %s\n",
1538 w32_strerror (-1) );
1550 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1554 /* Create a name for the socket in the home directory as using
1555 STANDARD_NAME. We also check for valid characters as well as
1556 against a maximum allowed length for a unix domain socket is done.
1557 The function terminates the process in case of an error. Returns:
1558 Pointer to an allocated string with the absolute name of the socket
1561 create_socket_name (char *standard_name, int with_homedir)
1566 name = make_filename (opt.homedir, standard_name, NULL);
1568 name = make_filename (standard_name, NULL);
1569 if (strchr (name, PATHSEP_C))
1571 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1579 /* Create a Unix domain socket with NAME. Returns the file descriptor
1580 or terminates the process in case of an error. Note that this
1581 function needs to be used for the regular socket first (indicated
1582 by PRIMARY) and only then for the extra and the ssh sockets. If
1583 the socket has been redirected the name of the real socket is
1584 stored as a malloced string at R_REDIR_NAME. */
1586 create_server_socket (char *name, int primary,
1587 char **r_redir_name, assuan_sock_nonce_t *nonce)
1589 struct sockaddr *addr;
1590 struct sockaddr_un *unaddr;
1595 xfree (*r_redir_name);
1596 *r_redir_name = NULL;
1598 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1599 if (fd == ASSUAN_INVALID_FD)
1601 log_error (_("can't create socket: %s\n"), strerror (errno));
1602 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1606 unaddr = xmalloc (sizeof *unaddr);
1607 addr = (struct sockaddr*)unaddr;
1609 #if ASSUAN_VERSION_NUMBER >= 0x020104 /* >= 2.1.4 */
1613 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1615 if (errno == ENAMETOOLONG)
1616 log_error (_("socket name '%s' is too long\n"), name);
1618 log_error ("error preparing socket '%s': %s\n",
1619 name, gpg_strerror (gpg_error_from_syserror ()));
1620 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1625 *r_redir_name = xstrdup (unaddr->sun_path);
1627 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1630 #else /* Assuan < 2.1.4 */
1631 memset (unaddr, 0, sizeof *unaddr);
1632 unaddr->sun_family = AF_UNIX;
1633 if (strlen (name) + 1 >= sizeof (unaddr->sun_path))
1635 log_error (_("socket name '%s' is too long\n"), name);
1636 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1639 strcpy (unaddr->sun_path, name);
1640 #endif /* Assuan < 2.1.4 */
1642 len = SUN_LEN (unaddr);
1643 rc = assuan_sock_bind (fd, addr, len);
1645 /* Our error code mapping on W32CE returns EEXIST thus we also test
1648 && (errno == EADDRINUSE
1649 #ifdef HAVE_W32_SYSTEM
1654 /* Check whether a gpg-agent is already running. We do this
1655 test only if this is the primary socket. For secondary
1656 sockets we assume that a test for gpg-agent has already been
1657 done and reuse the requested socket. Testing the ssh-socket
1658 is not possible because at this point, though we know the new
1659 Assuan socket, the Assuan server and thus the ssh-agent
1660 server is not yet operational; this would lead to a hang. */
1661 if (primary && !check_for_running_agent (1))
1663 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
1664 log_set_file (NULL);
1665 log_error (_("a gpg-agent is already running - "
1666 "not starting a new one\n"));
1667 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1668 assuan_sock_close (fd);
1671 gnupg_remove (unaddr->sun_path);
1672 rc = assuan_sock_bind (fd, addr, len);
1674 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1675 log_error (_("error getting nonce for the socket\n"));
1678 /* We use gpg_strerror here because it allows us to get strings
1679 for some W32 socket error codes. */
1680 log_error (_("error binding socket to '%s': %s\n"),
1682 gpg_strerror (gpg_error_from_syserror ()));
1684 assuan_sock_close (fd);
1685 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1689 if (listen (FD2INT(fd), 5 ) == -1)
1691 log_error (_("listen() failed: %s\n"), strerror (errno));
1692 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1693 assuan_sock_close (fd);
1698 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1704 /* Check that the directory for storing the private keys exists and
1705 create it if not. This function won't fail as it is only a
1706 convenience function and not strictly necessary. */
1708 create_private_keys_directory (const char *home)
1711 struct stat statbuf;
1713 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1714 if (stat (fname, &statbuf) && errno == ENOENT)
1716 if (gnupg_mkdir (fname, "-rwx"))
1717 log_error (_("can't create directory '%s': %s\n"),
1718 fname, strerror (errno) );
1719 else if (!opt.quiet)
1720 log_info (_("directory '%s' created\n"), fname);
1725 /* Create the directory only if the supplied directory name is the
1726 same as the default one. This way we avoid to create arbitrary
1727 directories when a non-default home directory is used. To cope
1728 with HOME, we compare only the suffix if we see that the default
1729 homedir does start with a tilde. We don't stop here in case of
1730 problems because other functions will throw an error anyway.*/
1732 create_directories (void)
1734 struct stat statbuf;
1735 const char *defhome = standard_homedir ();
1738 home = make_filename (opt.homedir, NULL);
1739 if ( stat (home, &statbuf) )
1741 if (errno == ENOENT)
1744 #ifdef HAVE_W32_SYSTEM
1745 ( !compare_filenames (home, defhome) )
1748 && (strlen (home) >= strlen (defhome+1)
1749 && !strcmp (home + strlen(home)
1750 - strlen (defhome+1), defhome+1)))
1751 || (*defhome != '~' && !strcmp (home, defhome) )
1755 if (gnupg_mkdir (home, "-rwx"))
1756 log_error (_("can't create directory '%s': %s\n"),
1757 home, strerror (errno) );
1761 log_info (_("directory '%s' created\n"), home);
1762 create_private_keys_directory (home);
1767 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1769 else if ( !S_ISDIR(statbuf.st_mode))
1771 log_error (_("can't use '%s' as home directory\n"), home);
1773 else /* exists and is a directory. */
1775 create_private_keys_directory (home);
1782 /* This is the worker for the ticker. It is called every few seconds
1783 and may only do fast operations. */
1787 static time_t last_minute;
1790 last_minute = time (NULL);
1792 /* Check whether the scdaemon has died and cleanup in this case. */
1793 agent_scd_check_aliveness ();
1795 /* If we are running as a child of another process, check whether
1796 the parent is still alive and shutdown if not. */
1797 #ifndef HAVE_W32_SYSTEM
1798 if (parent_pid != (pid_t)(-1))
1800 if (kill (parent_pid, 0))
1802 shutdown_pending = 2;
1803 log_info ("parent process died - shutting down\n");
1804 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1809 #endif /*HAVE_W32_SYSTEM*/
1811 /* Code to be run from time to time. */
1812 #if CHECK_OWN_SOCKET_INTERVAL > 0
1813 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
1815 check_own_socket ();
1816 last_minute = time (NULL);
1823 /* A global function which allows us to call the reload stuff from
1824 other places too. This is only used when build for W32. */
1826 agent_sighup_action (void)
1828 log_info ("SIGHUP received - "
1829 "re-reading configuration and flushing cache\n");
1831 agent_flush_cache ();
1832 reread_configuration ();
1833 agent_reload_trustlist ();
1834 /* We flush the module name cache so that after installing a
1835 "pinentry" binary that one can be used in case the
1836 "pinentry-basic" fallback was in use. */
1837 gnupg_module_name_flush_some ();
1841 /* A helper function to handle SIGUSR2. */
1843 agent_sigusr2_action (void)
1846 log_info ("SIGUSR2 received - updating card event counter\n");
1847 /* Nothing to check right now. We only increment a counter. */
1848 bump_card_eventcounter ();
1852 #ifndef HAVE_W32_SYSTEM
1853 /* The signal handler for this program. It is expected to be run in
1854 its own trhead and not in the context of a signal handler. */
1856 handle_signal (int signo)
1860 #ifndef HAVE_W32_SYSTEM
1862 agent_sighup_action ();
1866 log_info ("SIGUSR1 received - printing internal information:\n");
1867 /* Fixme: We need to see how to integrate pth dumping into our
1869 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1870 agent_query_dump_state ();
1871 agent_scd_dump_state ();
1875 agent_sigusr2_action ();
1879 if (!shutdown_pending)
1880 log_info ("SIGTERM received - shutting down ...\n");
1882 log_info ("SIGTERM received - still %i open connections\n",
1883 active_connections);
1885 if (shutdown_pending > 2)
1887 log_info ("shutdown forced\n");
1888 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1895 log_info ("SIGINT received - immediate shutdown\n");
1896 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1902 log_info ("signal %d received - no action defined\n", signo);
1907 /* Check the nonce on a new connection. This is a NOP unless we we
1908 are using our Unix domain socket emulation under Windows. */
1910 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1912 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1914 log_info (_("error reading nonce on fd %d: %s\n"),
1915 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1916 assuan_sock_close (ctrl->thread_startup.fd);
1925 #ifdef HAVE_W32_SYSTEM
1926 /* The window message processing function for Putty. Warning: This
1927 code runs as a native Windows thread. Use of our own functions
1928 needs to be bracket with pth_leave/pth_enter. */
1929 static LRESULT CALLBACK
1930 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1934 COPYDATASTRUCT *cds;
1935 const char *mapfile;
1940 PSECURITY_DESCRIPTOR psd = NULL;
1943 if (msg != WM_COPYDATA)
1945 return DefWindowProc (hwnd, msg, wparam, lparam);
1948 cds = (COPYDATASTRUCT*)lparam;
1949 if (cds->dwData != PUTTY_IPC_MAGIC)
1950 return 0; /* Ignore data with the wrong magic. */
1951 mapfile = cds->lpData;
1952 if (!cds->cbData || mapfile[cds->cbData - 1])
1953 return 0; /* Ignore empty and non-properly terminated strings. */
1958 log_debug ("ssh map file '%s'", mapfile);
1962 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
1966 log_debug ("ssh map handle %p\n", maphd);
1970 if (!maphd || maphd == INVALID_HANDLE_VALUE)
1975 mysid = w32_get_user_sid ();
1978 log_error ("error getting my sid\n");
1982 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
1983 OWNER_SECURITY_INFORMATION,
1984 &mapsid, NULL, NULL, NULL,
1988 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
1996 if (!ConvertSidToStringSid (mysid, &sidstr))
1998 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2000 if (!ConvertSidToStringSid (mapsid, &sidstr))
2002 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2006 if (!EqualSid (mysid, mapsid))
2008 log_error ("ssh map file has a non-matching sid\n");
2012 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2014 log_debug ("ssh IPC buffer at %p\n", data);
2018 /* log_printhex ("request:", data, 20); */
2020 ctrl = xtrycalloc (1, sizeof *ctrl);
2023 log_error ("error allocating connection control data: %s\n",
2027 ctrl->session_env = session_env_new ();
2028 if (!ctrl->session_env)
2030 log_error ("error allocating session environment block: %s\n",
2035 agent_init_default_ctrl (ctrl);
2036 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2037 ret = 1; /* Valid ssh message has been constructed. */
2038 agent_deinit_default_ctrl (ctrl);
2039 /* log_printhex (" reply:", data, 20); */
2044 UnmapViewOfFile (data);
2049 CloseHandle (maphd);
2055 #endif /*HAVE_W32_SYSTEM*/
2058 #ifdef HAVE_W32_SYSTEM
2059 /* The thread handling Putty's IPC requests. */
2061 putty_message_thread (void *arg)
2063 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2064 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2071 log_info ("putty message loop thread started\n");
2073 /* The message loop runs as thread independent from our nPth system.
2074 This also means that we need to make sure that we switch back to
2075 our system before calling any no-windows function. */
2078 /* First create a window to make sure that a message queue exists
2080 if (!RegisterClass (&wndwclass))
2083 log_error ("error registering Pageant window class");
2086 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2088 HWND_MESSAGE, /* hWndParent */
2089 NULL, /* hWndMenu */
2090 NULL, /* hInstance */
2095 log_error ("error creating Pageant window");
2099 while (GetMessage(&msg, NULL, 0, 0))
2101 TranslateMessage(&msg);
2102 DispatchMessage(&msg);
2109 log_info ("putty message loop thread stopped\n");
2112 #endif /*HAVE_W32_SYSTEM*/
2116 start_connection_thread (ctrl_t ctrl)
2118 if (check_nonce (ctrl, &socket_nonce))
2120 log_error ("handler 0x%lx nonce check FAILED\n",
2121 (unsigned long) npth_self());
2125 agent_init_default_ctrl (ctrl);
2127 log_info (_("handler 0x%lx for fd %d started\n"),
2128 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2130 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2132 log_info (_("handler 0x%lx for fd %d terminated\n"),
2133 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2135 agent_deinit_default_ctrl (ctrl);
2141 /* This is the standard connection thread's main function. */
2143 start_connection_thread_std (void *arg)
2147 return start_connection_thread (ctrl);
2151 /* This is the extra socket connection thread's main function. */
2153 start_connection_thread_extra (void *arg)
2157 ctrl->restricted = 1;
2158 return start_connection_thread (ctrl);
2162 /* This is the ssh connection thread's main function. */
2164 start_connection_thread_ssh (void *arg)
2168 if (check_nonce (ctrl, &socket_nonce_ssh))
2171 agent_init_default_ctrl (ctrl);
2173 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2174 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2176 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2178 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2179 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2181 agent_deinit_default_ctrl (ctrl);
2187 /* Connection handler loop. Wait for connection requests and spawn a
2188 thread after accepting a connection. */
2190 handle_connections (gnupg_fd_t listen_fd,
2191 gnupg_fd_t listen_fd_extra,
2192 gnupg_fd_t listen_fd_ssh)
2195 struct sockaddr_un paddr;
2197 fd_set fdset, read_fdset;
2202 struct timespec abstime;
2203 struct timespec curtime;
2204 struct timespec timeout;
2205 #ifdef HAVE_W32_SYSTEM
2207 unsigned int events_set;
2211 void *(*func) (void *arg);
2214 { "std", start_connection_thread_std },
2215 { "extra",start_connection_thread_extra },
2216 { "ssh", start_connection_thread_ssh }
2220 ret = npth_attr_init(&tattr);
2222 log_fatal ("error allocating thread attributes: %s\n",
2224 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2226 #ifndef HAVE_W32_SYSTEM
2228 npth_sigev_add (SIGHUP);
2229 npth_sigev_add (SIGUSR1);
2230 npth_sigev_add (SIGUSR2);
2231 npth_sigev_add (SIGINT);
2232 npth_sigev_add (SIGTERM);
2235 # ifdef HAVE_W32CE_SYSTEM
2236 /* Use a dummy event. */
2238 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2240 events[0] = get_agent_scd_notify_event ();
2241 events[1] = INVALID_HANDLE_VALUE;
2245 /* On Windows we need to fire up a separate thread to listen for
2246 requests from Putty (an SSH client), so we can replace Putty's
2247 Pageant (its ssh-agent implementation). */
2248 #ifdef HAVE_W32_SYSTEM
2253 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2256 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2259 #endif /*HAVE_W32_SYSTEM*/
2261 /* Set a flag to tell call-scd.c that it may enable event
2263 opt.sigusr2_enabled = 1;
2266 FD_SET (FD2INT (listen_fd), &fdset);
2267 nfd = FD2INT (listen_fd);
2268 if (listen_fd_extra != GNUPG_INVALID_FD)
2270 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2271 if (FD2INT (listen_fd_extra) > nfd)
2272 nfd = FD2INT (listen_fd_extra);
2274 if (listen_fd_ssh != GNUPG_INVALID_FD)
2276 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2277 if (FD2INT (listen_fd_ssh) > nfd)
2278 nfd = FD2INT (listen_fd_ssh);
2281 listentbl[0].l_fd = listen_fd;
2282 listentbl[1].l_fd = listen_fd_extra;
2283 listentbl[2].l_fd = listen_fd_ssh;
2285 npth_clock_gettime (&abstime);
2286 abstime.tv_sec += TIMERTICK_INTERVAL;
2290 /* Shutdown test. */
2291 if (shutdown_pending)
2293 if (active_connections == 0)
2296 /* Do not accept new connections but keep on running the
2297 loop to cope with the timer events. */
2301 /* POSIX says that fd_set should be implemented as a structure,
2302 thus a simple assignment is fine to copy the entire set. */
2305 npth_clock_gettime (&curtime);
2306 if (!(npth_timercmp (&curtime, &abstime, <)))
2310 npth_clock_gettime (&abstime);
2311 abstime.tv_sec += TIMERTICK_INTERVAL;
2313 npth_timersub (&abstime, &curtime, &timeout);
2315 #ifndef HAVE_W32_SYSTEM
2316 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2317 npth_sigev_sigmask ());
2318 saved_errno = errno;
2322 while (npth_sigev_get_pending (&signo))
2323 handle_signal (signo);
2326 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2327 events, &events_set);
2328 saved_errno = errno;
2330 /* This is valid even if npth_eselect returns an error. */
2332 agent_sigusr2_action ();
2335 if (ret == -1 && saved_errno != EINTR)
2337 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2338 strerror (saved_errno));
2343 /* Interrupt or timeout. Will be handled when calculating the
2347 if (!shutdown_pending)
2353 for (idx=0; idx < DIM(listentbl); idx++)
2355 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2357 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2360 plen = sizeof paddr;
2361 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2362 (struct sockaddr *)&paddr, &plen));
2363 if (fd == GNUPG_INVALID_FD)
2365 log_error ("accept failed for %s: %s\n",
2366 listentbl[idx].name, strerror (errno));
2368 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2370 log_error ("error allocating connection data for %s: %s\n",
2371 listentbl[idx].name, strerror (errno) );
2372 assuan_sock_close (fd);
2374 else if ( !(ctrl->session_env = session_env_new ()))
2376 log_error ("error allocating session env block for %s: %s\n",
2377 listentbl[idx].name, strerror (errno) );
2379 assuan_sock_close (fd);
2383 ctrl->thread_startup.fd = fd;
2384 ret = npth_create (&thread, &tattr,
2385 listentbl[idx].func, ctrl);
2388 log_error ("error spawning connection handler for %s:"
2389 " %s\n", listentbl[idx].name, strerror (ret));
2390 assuan_sock_close (fd);
2394 fd = GNUPG_INVALID_FD;
2400 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2401 npth_attr_destroy (&tattr);
2406 /* Helper for check_own_socket. */
2408 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2410 membuf_t *mb = opaque;
2411 put_membuf (mb, buffer, length);
2416 /* The thread running the actual check. We need to run this in a
2417 separate thread so that check_own_thread can be called from the
2420 check_own_socket_thread (void *arg)
2423 char *sockname = arg;
2424 assuan_context_t ctx = NULL;
2428 check_own_socket_running++;
2430 rc = assuan_new (&ctx);
2433 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2437 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2440 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2444 init_membuf (&mb, 100);
2445 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2446 NULL, NULL, NULL, NULL);
2447 put_membuf (&mb, "", 1);
2448 buffer = get_membuf (&mb, NULL);
2451 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2452 "GETINFO pid", gpg_strerror (rc));
2455 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2457 log_error ("socket is now serviced by another server\n");
2460 else if (opt.verbose > 1)
2461 log_error ("socket is still served by this server\n");
2468 assuan_release (ctx);
2471 /* We may not remove the socket as it is now in use by another
2472 server. Setting the name to empty does this. */
2475 if (socket_name_ssh)
2476 *socket_name_ssh = 0;
2477 shutdown_pending = 2;
2478 log_info ("this process is useless - shutting down\n");
2480 check_own_socket_running--;
2485 /* Check whether we are still listening on our own socket. In case
2486 another gpg-agent process started after us has taken ownership of
2487 our socket, we would linger around without any real task. Thus we
2488 better check once in a while whether we are really needed. */
2490 check_own_socket (void)
2497 if (disable_check_own_socket)
2500 if (check_own_socket_running || shutdown_pending)
2501 return; /* Still running or already shutting down. */
2503 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2505 return; /* Out of memory. */
2507 err = npth_attr_init (&tattr);
2510 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2511 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2513 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2514 npth_attr_destroy (&tattr);
2519 /* Figure out whether an agent is available and running. Prints an
2520 error if not. If SILENT is true, no messages are printed.
2521 Returns 0 if the agent is running. */
2523 check_for_running_agent (int silent)
2527 assuan_context_t ctx = NULL;
2529 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2531 err = assuan_new (&ctx);
2533 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2538 log_error (_("no gpg-agent running in this session\n"));
2541 assuan_release (ctx);
2545 if (!opt.quiet && !silent)
2546 log_info ("gpg-agent running and available\n");
2548 assuan_release (ctx);