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 presetting passphrase")),
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 /* The main entry point. */
633 main (int argc, char **argv )
638 FILE *configfp = NULL;
639 char *configname = NULL;
641 unsigned configlineno;
643 int default_config =1;
648 char *logfile = NULL;
650 int gpgconf_list = 0;
652 struct assuan_malloc_hooks malloc_hooks;
654 /* Before we do anything else we save the list of currently open
655 file descriptors and the signal mask. This info is required to
656 do the exec call properly. */
657 startup_fd_list = get_all_open_fds ();
658 #ifdef HAVE_SIGPROCMASK
659 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
660 startup_signal_mask_valid = 1;
661 #endif /*HAVE_SIGPROCMASK*/
663 /* Set program name etc. */
664 set_strusage (my_strusage);
665 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
666 /* Please note that we may running SUID(ROOT), so be very CAREFUL
667 when adding any stuff between here and the call to INIT_SECMEM()
668 somewhere after the option parsing */
669 log_set_prefix (GPG_AGENT_NAME, JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
671 /* Make sure that our subsystems are ready. */
673 init_common_subsystems (&argc, &argv);
677 /* Check that the libraries are suitable. Do it here because
678 the option parsing may need services of the library. */
679 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
681 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
682 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
685 malloc_hooks.malloc = gcry_malloc;
686 malloc_hooks.realloc = gcry_realloc;
687 malloc_hooks.free = gcry_free;
688 assuan_set_malloc_hooks (&malloc_hooks);
689 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
690 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
692 setup_libassuan_logging (&opt.debug);
694 setup_libgcrypt_logging ();
695 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
697 disable_core_dumps ();
699 /* Set default options. */
700 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
702 shell = getenv ("SHELL");
703 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
706 opt.homedir = default_homedir ();
708 /* Record some of the original environment strings. */
712 static const char *names[] =
713 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
716 opt.startup_env = session_env_new ();
717 if (!opt.startup_env)
718 err = gpg_error_from_syserror ();
719 for (idx=0; !err && names[idx]; idx++)
721 s = getenv (names[idx]);
723 err = session_env_setenv (opt.startup_env, names[idx], s);
727 s = gnupg_ttyname (0);
729 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
732 log_fatal ("error recording startup environment: %s\n",
735 /* Fixme: Better use the locale function here. */
736 opt.startup_lc_ctype = getenv ("LC_CTYPE");
737 if (opt.startup_lc_ctype)
738 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
739 opt.startup_lc_messages = getenv ("LC_MESSAGES");
740 if (opt.startup_lc_messages)
741 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
744 /* Check whether we have a config file on the commandline */
749 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
750 while (arg_parse( &pargs, opts))
752 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
754 else if (pargs.r_opt == oOptions)
755 { /* yes there is one, so we do not try the default one, but
756 read the option file when it is encountered at the
760 else if (pargs.r_opt == oNoOptions)
761 default_config = 0; /* --no-options */
762 else if (pargs.r_opt == oHomedir)
763 opt.homedir = pargs.r.ret_str;
764 else if (pargs.r_opt == oDebugQuickRandom)
766 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
771 /* Initialize the secure memory. */
772 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
776 Now we are now working under our real uid
780 configname = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
787 pargs.flags= 1; /* do not remove the args */
792 configfp = fopen (configname, "r");
798 log_info (_("Note: no default option file '%s'\n"),
800 /* Save the default conf file name so that
801 reread_configuration is able to test whether the
802 config file has been created in the meantime. */
803 xfree (config_filename);
804 config_filename = configname;
809 log_error (_("option file '%s': %s\n"),
810 configname, strerror(errno) );
816 if (parse_debug && configname )
817 log_info (_("reading options from '%s'\n"), configname );
821 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
823 if (parse_rereadable_options (&pargs, 0))
824 continue; /* Already handled */
827 case aGPGConfList: gpgconf_list = 1; break;
828 case aGPGConfTest: gpgconf_list = 2; break;
829 case aUseStandardSocketP: gpgconf_list = 3; break;
830 case oBatch: opt.batch=1; break;
832 case oDebugWait: debug_wait = pargs.r.ret_int; break;
835 /* config files may not be nested (silently ignore them) */
839 configname = xstrdup(pargs.r.ret_str);
843 case oNoGreeting: /* Dummy option. */ break;
844 case oNoVerbose: opt.verbose = 0; break;
845 case oNoOptions: break; /* no-options */
846 case oHomedir: opt.homedir = pargs.r.ret_str; break;
847 case oNoDetach: nodetach = 1; break;
848 case oLogFile: logfile = pargs.r.ret_str; break;
849 case oCsh: csh_style = 1; break;
850 case oSh: csh_style = 0; break;
851 case oServer: pipe_server = 1; break;
852 case oDaemon: is_daemon = 1; break;
854 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
855 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
856 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
857 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
858 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
860 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
863 case oUseStandardSocket: /* dummy */ break;
864 case oNoUseStandardSocket: /* dummy */ break;
866 case oFakedSystemTime:
868 time_t faked_time = isotime2epoch (pargs.r.ret_str);
869 if (faked_time == (time_t)(-1))
870 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
871 gnupg_set_time (faked_time, 0);
875 case oKeepTTY: opt.keep_tty = 1; break;
876 case oKeepDISPLAY: opt.keep_display = 1; break;
878 case oSSHSupport: opt.ssh_support = 1; break;
880 # ifdef HAVE_W32_SYSTEM
887 opt.extra_socket = 1; /* (1 = points into argv) */
888 socket_name_extra = pargs.r.ret_str;
891 case oDebugQuickRandom:
892 /* Only used by the first stage command line parser. */
895 case oWriteEnvFile: /* dummy */ break;
897 default : pargs.err = configfp? 1:2; break;
904 /* Keep a copy of the name so that it can be read on SIGHUP. */
905 if (config_filename != configname)
907 xfree (config_filename);
908 config_filename = configname;
916 if (log_get_errorcount(0))
919 /* Turn the homedir into an absolute one. */
920 opt.homedir = make_absfilename (opt.homedir, NULL);
922 /* Print a warning if an argument looks like an option. */
923 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
927 for (i=0; i < argc; i++)
928 if (argv[i][0] == '-' && argv[i][1] == '-')
929 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
933 /* gpg-agent usually does not output any messages because it runs in
934 the background. For log files it is acceptable to have messages
935 always encoded in utf-8. We switch here to utf-8, so that
936 commands like --help still give native messages. It is far
937 easier to switch only once instead of for every message and it
938 actually helps when more then one thread is active (avoids an
940 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
943 if (!pipe_server && !is_daemon && !gpgconf_list)
945 /* We have been called without any options and thus we merely
946 check whether an agent is already running. We do this right
947 here so that we don't clobber a logfile with this check but
948 print the status directly to stderr. */
951 check_for_running_agent (0);
957 if (atexit (cleanup))
959 log_error ("atexit failed\n");
964 initialize_module_cache ();
965 initialize_module_call_pinentry ();
966 initialize_module_call_scd ();
967 initialize_module_trustlist ();
969 /* Try to create missing directories. */
970 create_directories ();
972 if (debug_wait && pipe_server)
974 log_debug ("waiting for debugger - my pid is %u .....\n",
975 (unsigned int)getpid());
976 gnupg_sleep (debug_wait);
977 log_debug ("... okay\n");
980 if (gpgconf_list == 3)
982 /* We now use the standard socket always - return true for
983 backward compatibility. */
986 else if (gpgconf_list == 2)
988 else if (gpgconf_list)
993 /* List options and default values in the GPG Conf format. */
994 filename = make_filename (opt.homedir, GPG_AGENT_NAME EXTSEP_S "conf",
996 filename_esc = percent_escape (filename, NULL);
998 es_printf ("%s-%s.conf:%lu:\"%s\n",
999 GPGCONF_NAME, GPG_AGENT_NAME,
1000 GC_OPT_FLAG_DEFAULT, filename_esc);
1002 xfree (filename_esc);
1004 es_printf ("verbose:%lu:\n"
1006 "debug-level:%lu:\"none:\n"
1008 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1009 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1010 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1011 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1012 es_printf ("default-cache-ttl:%lu:%d:\n",
1013 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1014 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1015 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1016 es_printf ("max-cache-ttl:%lu:%d:\n",
1017 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1018 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1019 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1020 es_printf ("enforce-passphrase-constraints:%lu:\n",
1021 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1022 es_printf ("min-passphrase-len:%lu:%d:\n",
1023 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1024 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1025 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1026 MIN_PASSPHRASE_NONALPHA);
1027 es_printf ("check-passphrase-pattern:%lu:\n",
1028 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1029 es_printf ("max-passphrase-days:%lu:%d:\n",
1030 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1031 MAX_PASSPHRASE_DAYS);
1032 es_printf ("enable-passphrase-history:%lu:\n",
1033 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1034 es_printf ("no-grab:%lu:\n",
1035 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1036 es_printf ("ignore-cache-for-signing:%lu:\n",
1037 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1038 es_printf ("no-allow-mark-trusted:%lu:\n",
1039 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1040 es_printf ("disable-scdaemon:%lu:\n",
1041 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1042 #ifdef HAVE_W32_SYSTEM
1043 es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1045 es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1051 /* Now start with logging to a file if this is desired. */
1054 log_set_file (logfile);
1055 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
1056 |JNLIB_LOG_WITH_TIME
1057 |JNLIB_LOG_WITH_PID));
1058 current_logfile = xstrdup (logfile);
1061 /* Make sure that we have a default ttyname. */
1062 if (!default_ttyname && gnupg_ttyname (1))
1063 default_ttyname = xstrdup (gnupg_ttyname (1));
1064 if (!default_ttytype && getenv ("TERM"))
1065 default_ttytype = xstrdup (getenv ("TERM"));
1070 /* This is the simple pipe based server */
1073 ctrl = xtrycalloc (1, sizeof *ctrl);
1076 log_error ("error allocating connection control data: %s\n",
1080 ctrl->session_env = session_env_new ();
1081 if (!ctrl->session_env)
1083 log_error ("error allocating session environment block: %s\n",
1088 agent_init_default_ctrl (ctrl);
1089 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1090 agent_deinit_default_ctrl (ctrl);
1093 else if (!is_daemon)
1096 { /* Regular server mode */
1098 gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1099 gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1102 /* Remove the DISPLAY variable so that a pinentry does not
1103 default to a specific display. There is still a default
1104 display when gpg-agent was started using --display or a
1105 client requested this using an OPTION command. Note, that we
1106 don't do this when running in reverse daemon mode (i.e. when
1107 exec the program given as arguments). */
1108 #ifndef HAVE_W32_SYSTEM
1109 if (!opt.keep_display && !argc)
1110 gnupg_unsetenv ("DISPLAY");
1113 /* Create the sockets. */
1114 socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1115 fd = create_server_socket (socket_name, 1,
1116 &redir_socket_name, &socket_nonce);
1118 if (opt.extra_socket)
1120 socket_name_extra = create_socket_name (socket_name_extra, 0);
1121 opt.extra_socket = 2; /* Indicate that it has been malloced. */
1122 fd_extra = create_server_socket (socket_name_extra, 0,
1123 &redir_socket_name_extra,
1124 &socket_nonce_extra);
1127 if (opt.ssh_support)
1129 socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1130 fd_ssh = create_server_socket (socket_name_ssh, 0,
1131 &redir_socket_name_ssh,
1135 /* If we are going to exec a program in the parent, we record
1136 the PID, so that the child may check whether the program is
1139 parent_pid = getpid ();
1142 #ifdef HAVE_W32_SYSTEM
1146 #else /*!HAVE_W32_SYSTEM*/
1148 if (pid == (pid_t)-1)
1150 log_fatal ("fork failed: %s\n", strerror (errno) );
1154 { /* We are the parent */
1155 char *infostr_ssh_sock, *infostr_ssh_valid;
1157 /* Close the socket FD. */
1160 /* The signal mask might not be correct right now and thus
1161 we restore it. That is not strictly necessary but some
1162 programs falsely assume a cleared signal mask. */
1164 #ifdef HAVE_SIGPROCMASK
1165 if (startup_signal_mask_valid)
1167 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1168 log_error ("error restoring signal mask: %s\n",
1172 log_info ("no saved signal mask\n");
1173 #endif /*HAVE_SIGPROCMASK*/
1175 /* Create the SSH info string if enabled. */
1176 if (opt.ssh_support)
1178 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1179 socket_name_ssh) < 0)
1181 log_error ("out of core\n");
1182 kill (pid, SIGTERM);
1185 if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1186 (unsigned long)getpid()) < 0)
1188 log_error ("out of core\n");
1189 kill (pid, SIGTERM);
1194 *socket_name = 0; /* Don't let cleanup() remove the socket -
1195 the child should do this from now on */
1196 if (opt.extra_socket)
1197 *socket_name_extra = 0;
1198 if (opt.ssh_support)
1199 *socket_name_ssh = 0;
1202 { /* Run the program given on the commandline. */
1203 if (opt.ssh_support && (putenv (infostr_ssh_sock)
1204 || putenv (infostr_ssh_valid)))
1206 log_error ("failed to set environment: %s\n",
1208 kill (pid, SIGTERM );
1212 /* Close all the file descriptors except the standard
1213 ones and those open at startup. We explicitly don't
1214 close 0,1,2 in case something went wrong collecting
1216 close_all_fds (3, startup_fd_list);
1218 /* Run the command. */
1219 execvp (argv[0], argv);
1220 log_error ("failed to run the command: %s\n", strerror (errno));
1221 kill (pid, SIGTERM);
1226 /* Print the environment string, so that the caller can use
1227 shell's eval to set it */
1230 if (opt.ssh_support)
1232 *strchr (infostr_ssh_sock, '=') = ' ';
1233 es_printf ("setenv %s;\n", infostr_ssh_sock);
1238 if (opt.ssh_support)
1240 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1244 if (opt.ssh_support)
1246 xfree (infostr_ssh_sock);
1247 xfree (infostr_ssh_valid);
1258 /* Detach from tty and put process into a new session */
1262 unsigned int oldflags;
1264 /* Close stdin, stdout and stderr unless it is the log stream */
1265 for (i=0; i <= 2; i++)
1267 if (!log_test_fd (i) && i != fd )
1270 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1272 log_error ("failed to open '%s': %s\n",
1273 "/dev/null", strerror (errno));
1281 log_error ("setsid() failed: %s\n", strerror(errno) );
1286 log_get_prefix (&oldflags);
1287 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1288 opt.running_detached = 1;
1293 log_error ("chdir to / failed: %s\n", strerror (errno));
1298 struct sigaction sa;
1300 sa.sa_handler = SIG_IGN;
1301 sigemptyset (&sa.sa_mask);
1303 sigaction (SIGPIPE, &sa, NULL);
1305 #endif /*!HAVE_W32_SYSTEM*/
1307 log_info ("%s %s started\n", strusage(11), strusage(13) );
1308 handle_connections (fd, fd_extra, fd_ssh);
1309 assuan_sock_close (fd);
1316 /* Exit entry point. This function should be called instead of a
1321 /*FIXME: update_random_seed_file();*/
1323 /* We run our cleanup handler because that may close cipher contexts
1324 stored in secure memory and thus this needs to be done before we
1325 explicitly terminate secure memory. */
1329 /* at this time a bit annoying */
1330 if (opt.debug & DBG_MEMSTAT_VALUE)
1332 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1333 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1336 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1338 gcry_control (GCRYCTL_TERM_SECMEM );
1339 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1344 /* Each thread has its own local variables conveyed by a control
1345 structure usually identified by an argument named CTRL. This
1346 function is called immediately after allocating the control
1347 structure. Its purpose is to setup the default values for that
1348 structure. Note that some values may have already been set. */
1350 agent_init_default_ctrl (ctrl_t ctrl)
1352 assert (ctrl->session_env);
1354 /* Note we ignore malloc errors because we can't do much about it
1355 and the request will fail anyway shortly after this
1357 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1358 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1359 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1360 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1361 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1364 xfree (ctrl->lc_ctype);
1365 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1367 if (ctrl->lc_messages)
1368 xfree (ctrl->lc_messages);
1369 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1371 ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1375 /* Release all resources allocated by default in the control
1376 structure. This is the counterpart to agent_init_default_ctrl. */
1378 agent_deinit_default_ctrl (ctrl_t ctrl)
1380 session_env_release (ctrl->session_env);
1383 xfree (ctrl->lc_ctype);
1384 if (ctrl->lc_messages)
1385 xfree (ctrl->lc_messages);
1389 /* Reread parts of the configuration. Note, that this function is
1390 obviously not thread-safe and should only be called from the PTH
1393 Fixme: Due to the way the argument parsing works, we create a
1394 memory leak here for all string type arguments. There is currently
1395 no clean way to tell whether the memory for the argument has been
1396 allocated or points into the process' original arguments. Unless
1397 we have a mechanism to tell this, we need to live on with this. */
1399 reread_configuration (void)
1401 ARGPARSE_ARGS pargs;
1403 unsigned int configlineno = 0;
1406 if (!config_filename)
1407 return; /* No config file. */
1409 fp = fopen (config_filename, "r");
1412 log_info (_("option file '%s': %s\n"),
1413 config_filename, strerror(errno) );
1417 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1419 memset (&pargs, 0, sizeof pargs);
1421 pargs.argc = &dummy;
1422 pargs.flags = 1; /* do not remove the args */
1423 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1425 if (pargs.r_opt < -1)
1426 pargs.err = 1; /* Print a warning. */
1427 else /* Try to parse this option - ignore unchangeable ones. */
1428 parse_rereadable_options (&pargs, 1);
1435 /* Return the file name of the socket we are using for native
1438 get_agent_socket_name (void)
1440 const char *s = socket_name;
1442 return (s && *s)? s : NULL;
1445 /* Return the file name of the socket we are using for SSH
1448 get_agent_ssh_socket_name (void)
1450 const char *s = socket_name_ssh;
1452 return (s && *s)? s : NULL;
1456 /* Under W32, this function returns the handle of the scdaemon
1457 notification event. Calling it the first time creates that
1459 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1461 get_agent_scd_notify_event (void)
1463 static HANDLE the_event = INVALID_HANDLE_VALUE;
1465 if (the_event == INVALID_HANDLE_VALUE)
1468 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1470 /* We need to use a manual reset event object due to the way our
1471 w32-pth wait function works: If we would use an automatic
1472 reset event we are not able to figure out which handle has
1473 been signaled because at the time we single out the signaled
1474 handles using WFSO the event has already been reset due to
1476 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1478 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1479 else if (!DuplicateHandle (GetCurrentProcess(), h,
1480 GetCurrentProcess(), &h2,
1481 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1483 log_error ("setting syncronize for scd notify event failed: %s\n",
1484 w32_strerror (-1) );
1496 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1500 /* Create a name for the socket in the home directory as using
1501 STANDARD_NAME. We also check for valid characters as well as
1502 against a maximum allowed length for a unix domain socket is done.
1503 The function terminates the process in case of an error. Returns:
1504 Pointer to an allocated string with the absolute name of the socket
1507 create_socket_name (char *standard_name, int with_homedir)
1512 name = make_filename (opt.homedir, standard_name, NULL);
1514 name = make_filename (standard_name, NULL);
1515 if (strchr (name, PATHSEP_C))
1517 log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
1525 /* Create a Unix domain socket with NAME. Returns the file descriptor
1526 or terminates the process in case of an error. Note that this
1527 function needs to be used for the regular socket first (indicated
1528 by PRIMARY) and only then for the extra and the ssh sockets. If
1529 the socket has been redirected the name of the real socket is
1530 stored as a malloced string at R_REDIR_NAME. */
1532 create_server_socket (char *name, int primary,
1533 char **r_redir_name, assuan_sock_nonce_t *nonce)
1535 struct sockaddr *addr;
1536 struct sockaddr_un *unaddr;
1541 xfree (*r_redir_name);
1542 *r_redir_name = NULL;
1544 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1545 if (fd == ASSUAN_INVALID_FD)
1547 log_error (_("can't create socket: %s\n"), strerror (errno));
1548 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1552 unaddr = xmalloc (sizeof *unaddr);
1553 addr = (struct sockaddr*)unaddr;
1555 #if ASSUAN_VERSION_NUMBER >= 0x020104 /* >= 2.1.4 */
1559 if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
1561 if (errno == ENAMETOOLONG)
1562 log_error (_("socket name '%s' is too long\n"), name);
1564 log_error ("error preparing socket '%s': %s\n",
1565 name, gpg_strerror (gpg_error_from_syserror ()));
1566 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1571 *r_redir_name = xstrdup (unaddr->sun_path);
1573 log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
1576 #else /* Assuan < 2.1.4 */
1577 memset (unaddr, 0, sizeof *unaddr);
1578 unaddr->sun_family = AF_UNIX;
1579 if (strlen (name) + 1 >= sizeof (unaddr->sun_path))
1581 log_error (_("socket name '%s' is too long\n"), name);
1582 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1585 strcpy (unaddr->sun_path, name);
1586 #endif /* Assuan < 2.1.4 */
1588 len = SUN_LEN (unaddr);
1589 rc = assuan_sock_bind (fd, addr, len);
1591 /* Our error code mapping on W32CE returns EEXIST thus we also test
1594 && (errno == EADDRINUSE
1595 #ifdef HAVE_W32_SYSTEM
1600 /* Check whether a gpg-agent is already running. We do this
1601 test only if this is the primary socket. For secondary
1602 sockets we assume that a test for gpg-agent has already been
1603 done and reuse the requested socket. Testing the ssh-socket
1604 is not possible because at this point, though we know the new
1605 Assuan socket, the Assuan server and thus the ssh-agent
1606 server is not yet operational; this would lead to a hang. */
1607 if (primary && !check_for_running_agent (1))
1609 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
1610 log_set_file (NULL);
1611 log_error (_("a gpg-agent is already running - "
1612 "not starting a new one\n"));
1613 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1614 assuan_sock_close (fd);
1617 gnupg_remove (unaddr->sun_path);
1618 rc = assuan_sock_bind (fd, addr, len);
1620 if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
1621 log_error (_("error getting nonce for the socket\n"));
1624 /* We use gpg_strerror here because it allows us to get strings
1625 for some W32 socket error codes. */
1626 log_error (_("error binding socket to '%s': %s\n"),
1628 gpg_strerror (gpg_error_from_syserror ()));
1630 assuan_sock_close (fd);
1631 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1635 if (listen (FD2INT(fd), 5 ) == -1)
1637 log_error (_("listen() failed: %s\n"), strerror (errno));
1638 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1639 assuan_sock_close (fd);
1644 log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
1650 /* Check that the directory for storing the private keys exists and
1651 create it if not. This function won't fail as it is only a
1652 convenience function and not strictly necessary. */
1654 create_private_keys_directory (const char *home)
1657 struct stat statbuf;
1659 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1660 if (stat (fname, &statbuf) && errno == ENOENT)
1662 if (gnupg_mkdir (fname, "-rwx"))
1663 log_error (_("can't create directory '%s': %s\n"),
1664 fname, strerror (errno) );
1665 else if (!opt.quiet)
1666 log_info (_("directory '%s' created\n"), fname);
1671 /* Create the directory only if the supplied directory name is the
1672 same as the default one. This way we avoid to create arbitrary
1673 directories when a non-default home directory is used. To cope
1674 with HOME, we compare only the suffix if we see that the default
1675 homedir does start with a tilde. We don't stop here in case of
1676 problems because other functions will throw an error anyway.*/
1678 create_directories (void)
1680 struct stat statbuf;
1681 const char *defhome = standard_homedir ();
1684 home = make_filename (opt.homedir, NULL);
1685 if ( stat (home, &statbuf) )
1687 if (errno == ENOENT)
1690 #ifdef HAVE_W32_SYSTEM
1691 ( !compare_filenames (home, defhome) )
1694 && (strlen (home) >= strlen (defhome+1)
1695 && !strcmp (home + strlen(home)
1696 - strlen (defhome+1), defhome+1)))
1697 || (*defhome != '~' && !strcmp (home, defhome) )
1701 if (gnupg_mkdir (home, "-rwx"))
1702 log_error (_("can't create directory '%s': %s\n"),
1703 home, strerror (errno) );
1707 log_info (_("directory '%s' created\n"), home);
1708 create_private_keys_directory (home);
1713 log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
1715 else if ( !S_ISDIR(statbuf.st_mode))
1717 log_error (_("can't use '%s' as home directory\n"), home);
1719 else /* exists and is a directory. */
1721 create_private_keys_directory (home);
1728 /* This is the worker for the ticker. It is called every few seconds
1729 and may only do fast operations. */
1733 static time_t last_minute;
1736 last_minute = time (NULL);
1738 /* Check whether the scdaemon has died and cleanup in this case. */
1739 agent_scd_check_aliveness ();
1741 /* If we are running as a child of another process, check whether
1742 the parent is still alive and shutdown if not. */
1743 #ifndef HAVE_W32_SYSTEM
1744 if (parent_pid != (pid_t)(-1))
1746 if (kill (parent_pid, 0))
1748 shutdown_pending = 2;
1749 log_info ("parent process died - shutting down\n");
1750 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1755 #endif /*HAVE_W32_SYSTEM*/
1757 /* Code to be run from time to time. */
1758 #if CHECK_OWN_SOCKET_INTERVAL > 0
1759 if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
1761 check_own_socket ();
1762 last_minute = time (NULL);
1769 /* A global function which allows us to call the reload stuff from
1770 other places too. This is only used when build for W32. */
1772 agent_sighup_action (void)
1774 log_info ("SIGHUP received - "
1775 "re-reading configuration and flushing cache\n");
1776 agent_flush_cache ();
1777 reread_configuration ();
1778 agent_reload_trustlist ();
1782 /* A helper function to handle SIGUSR2. */
1784 agent_sigusr2_action (void)
1787 log_info ("SIGUSR2 received - updating card event counter\n");
1788 /* Nothing to check right now. We only increment a counter. */
1789 bump_card_eventcounter ();
1793 #ifndef HAVE_W32_SYSTEM
1794 /* The signal handler for this program. It is expected to be run in
1795 its own trhead and not in the context of a signal handler. */
1797 handle_signal (int signo)
1801 #ifndef HAVE_W32_SYSTEM
1803 agent_sighup_action ();
1807 log_info ("SIGUSR1 received - printing internal information:\n");
1808 /* Fixme: We need to see how to integrate pth dumping into our
1810 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1811 agent_query_dump_state ();
1812 agent_scd_dump_state ();
1816 agent_sigusr2_action ();
1820 if (!shutdown_pending)
1821 log_info ("SIGTERM received - shutting down ...\n");
1823 log_info ("SIGTERM received - still %i open connections\n",
1824 active_connections);
1826 if (shutdown_pending > 2)
1828 log_info ("shutdown forced\n");
1829 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1836 log_info ("SIGINT received - immediate shutdown\n");
1837 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1843 log_info ("signal %d received - no action defined\n", signo);
1848 /* Check the nonce on a new connection. This is a NOP unless we we
1849 are using our Unix domain socket emulation under Windows. */
1851 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1853 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1855 log_info (_("error reading nonce on fd %d: %s\n"),
1856 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1857 assuan_sock_close (ctrl->thread_startup.fd);
1866 #ifdef HAVE_W32_SYSTEM
1867 /* The window message processing function for Putty. Warning: This
1868 code runs as a native Windows thread. Use of our own functions
1869 needs to be bracket with pth_leave/pth_enter. */
1870 static LRESULT CALLBACK
1871 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1875 COPYDATASTRUCT *cds;
1876 const char *mapfile;
1881 PSECURITY_DESCRIPTOR psd = NULL;
1884 if (msg != WM_COPYDATA)
1886 return DefWindowProc (hwnd, msg, wparam, lparam);
1889 cds = (COPYDATASTRUCT*)lparam;
1890 if (cds->dwData != PUTTY_IPC_MAGIC)
1891 return 0; /* Ignore data with the wrong magic. */
1892 mapfile = cds->lpData;
1893 if (!cds->cbData || mapfile[cds->cbData - 1])
1894 return 0; /* Ignore empty and non-properly terminated strings. */
1899 log_debug ("ssh map file '%s'", mapfile);
1903 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
1907 log_debug ("ssh map handle %p\n", maphd);
1911 if (!maphd || maphd == INVALID_HANDLE_VALUE)
1916 mysid = w32_get_user_sid ();
1919 log_error ("error getting my sid\n");
1923 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
1924 OWNER_SECURITY_INFORMATION,
1925 &mapsid, NULL, NULL, NULL,
1929 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
1937 if (!ConvertSidToStringSid (mysid, &sidstr))
1939 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
1941 if (!ConvertSidToStringSid (mapsid, &sidstr))
1943 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
1947 if (!EqualSid (mysid, mapsid))
1949 log_error ("ssh map file has a non-matching sid\n");
1953 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
1955 log_debug ("ssh IPC buffer at %p\n", data);
1959 /* log_printhex ("request:", data, 20); */
1961 ctrl = xtrycalloc (1, sizeof *ctrl);
1964 log_error ("error allocating connection control data: %s\n",
1968 ctrl->session_env = session_env_new ();
1969 if (!ctrl->session_env)
1971 log_error ("error allocating session environment block: %s\n",
1976 agent_init_default_ctrl (ctrl);
1977 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
1978 ret = 1; /* Valid ssh message has been constructed. */
1979 agent_deinit_default_ctrl (ctrl);
1980 /* log_printhex (" reply:", data, 20); */
1985 UnmapViewOfFile (data);
1990 CloseHandle (maphd);
1996 #endif /*HAVE_W32_SYSTEM*/
1999 #ifdef HAVE_W32_SYSTEM
2000 /* The thread handling Putty's IPC requests. */
2002 putty_message_thread (void *arg)
2004 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2005 NULL, NULL, NULL, NULL, NULL, "Pageant"};
2012 log_info ("putty message loop thread started\n");
2014 /* The message loop runs as thread independent from our nPth system.
2015 This also means that we need to make sure that we switch back to
2016 our system before calling any no-windows function. */
2019 /* First create a window to make sure that a message queue exists
2021 if (!RegisterClass (&wndwclass))
2024 log_error ("error registering Pageant window class");
2027 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2029 HWND_MESSAGE, /* hWndParent */
2030 NULL, /* hWndMenu */
2031 NULL, /* hInstance */
2036 log_error ("error creating Pageant window");
2040 while (GetMessage(&msg, NULL, 0, 0))
2042 TranslateMessage(&msg);
2043 DispatchMessage(&msg);
2050 log_info ("putty message loop thread stopped\n");
2053 #endif /*HAVE_W32_SYSTEM*/
2057 start_connection_thread (ctrl_t ctrl)
2059 if (check_nonce (ctrl, &socket_nonce))
2061 log_error ("handler 0x%lx nonce check FAILED\n",
2062 (unsigned long) npth_self());
2066 agent_init_default_ctrl (ctrl);
2068 log_info (_("handler 0x%lx for fd %d started\n"),
2069 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2071 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2073 log_info (_("handler 0x%lx for fd %d terminated\n"),
2074 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2076 agent_deinit_default_ctrl (ctrl);
2082 /* This is the standard connection thread's main function. */
2084 start_connection_thread_std (void *arg)
2088 return start_connection_thread (ctrl);
2092 /* This is the extra socket connection thread's main function. */
2094 start_connection_thread_extra (void *arg)
2098 ctrl->restricted = 1;
2099 return start_connection_thread (ctrl);
2103 /* This is the ssh connection thread's main function. */
2105 start_connection_thread_ssh (void *arg)
2109 if (check_nonce (ctrl, &socket_nonce_ssh))
2112 agent_init_default_ctrl (ctrl);
2114 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2115 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2117 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2119 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2120 (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2122 agent_deinit_default_ctrl (ctrl);
2128 /* Connection handler loop. Wait for connection requests and spawn a
2129 thread after accepting a connection. */
2131 handle_connections (gnupg_fd_t listen_fd,
2132 gnupg_fd_t listen_fd_extra,
2133 gnupg_fd_t listen_fd_ssh)
2136 struct sockaddr_un paddr;
2138 fd_set fdset, read_fdset;
2143 struct timespec abstime;
2144 struct timespec curtime;
2145 struct timespec timeout;
2146 #ifdef HAVE_W32_SYSTEM
2148 unsigned int events_set;
2152 void *(*func) (void *arg);
2155 { "std", start_connection_thread_std },
2156 { "extra",start_connection_thread_extra },
2157 { "ssh", start_connection_thread_ssh }
2161 ret = npth_attr_init(&tattr);
2163 log_fatal ("error allocating thread attributes: %s\n",
2165 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2167 #ifndef HAVE_W32_SYSTEM
2169 npth_sigev_add (SIGHUP);
2170 npth_sigev_add (SIGUSR1);
2171 npth_sigev_add (SIGUSR2);
2172 npth_sigev_add (SIGINT);
2173 npth_sigev_add (SIGTERM);
2176 # ifdef HAVE_W32CE_SYSTEM
2177 /* Use a dummy event. */
2179 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2181 events[0] = get_agent_scd_notify_event ();
2182 events[1] = INVALID_HANDLE_VALUE;
2186 /* On Windows we need to fire up a separate thread to listen for
2187 requests from Putty (an SSH client), so we can replace Putty's
2188 Pageant (its ssh-agent implementation). */
2189 #ifdef HAVE_W32_SYSTEM
2194 ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2197 log_error ("error spawning putty message loop: %s\n", strerror (ret));
2200 #endif /*HAVE_W32_SYSTEM*/
2202 /* Set a flag to tell call-scd.c that it may enable event
2204 opt.sigusr2_enabled = 1;
2207 FD_SET (FD2INT (listen_fd), &fdset);
2208 nfd = FD2INT (listen_fd);
2209 if (listen_fd_extra != GNUPG_INVALID_FD)
2211 FD_SET ( FD2INT(listen_fd_extra), &fdset);
2212 if (FD2INT (listen_fd_extra) > nfd)
2213 nfd = FD2INT (listen_fd_extra);
2215 if (listen_fd_ssh != GNUPG_INVALID_FD)
2217 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2218 if (FD2INT (listen_fd_ssh) > nfd)
2219 nfd = FD2INT (listen_fd_ssh);
2222 listentbl[0].l_fd = listen_fd;
2223 listentbl[1].l_fd = listen_fd_extra;
2224 listentbl[2].l_fd = listen_fd_ssh;
2226 npth_clock_gettime (&abstime);
2227 abstime.tv_sec += TIMERTICK_INTERVAL;
2231 /* Shutdown test. */
2232 if (shutdown_pending)
2234 if (active_connections == 0)
2237 /* Do not accept new connections but keep on running the
2238 loop to cope with the timer events. */
2242 /* POSIX says that fd_set should be implemented as a structure,
2243 thus a simple assignment is fine to copy the entire set. */
2246 npth_clock_gettime (&curtime);
2247 if (!(npth_timercmp (&curtime, &abstime, <)))
2251 npth_clock_gettime (&abstime);
2252 abstime.tv_sec += TIMERTICK_INTERVAL;
2254 npth_timersub (&abstime, &curtime, &timeout);
2256 #ifndef HAVE_W32_SYSTEM
2257 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2258 npth_sigev_sigmask ());
2259 saved_errno = errno;
2263 while (npth_sigev_get_pending (&signo))
2264 handle_signal (signo);
2267 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2268 events, &events_set);
2269 saved_errno = errno;
2271 /* This is valid even if npth_eselect returns an error. */
2273 agent_sigusr2_action ();
2276 if (ret == -1 && saved_errno != EINTR)
2278 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2279 strerror (saved_errno));
2284 /* Interrupt or timeout. Will be handled when calculating the
2288 if (!shutdown_pending)
2294 for (idx=0; idx < DIM(listentbl); idx++)
2296 if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2298 if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2301 plen = sizeof paddr;
2302 fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2303 (struct sockaddr *)&paddr, &plen));
2304 if (fd == GNUPG_INVALID_FD)
2306 log_error ("accept failed for %s: %s\n",
2307 listentbl[idx].name, strerror (errno));
2309 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2311 log_error ("error allocating connection data for %s: %s\n",
2312 listentbl[idx].name, strerror (errno) );
2313 assuan_sock_close (fd);
2315 else if ( !(ctrl->session_env = session_env_new ()))
2317 log_error ("error allocating session env block for %s: %s\n",
2318 listentbl[idx].name, strerror (errno) );
2320 assuan_sock_close (fd);
2324 ctrl->thread_startup.fd = fd;
2325 ret = npth_create (&thread, &tattr,
2326 listentbl[idx].func, ctrl);
2329 log_error ("error spawning connection handler for %s:"
2330 " %s\n", listentbl[idx].name, strerror (ret));
2331 assuan_sock_close (fd);
2335 fd = GNUPG_INVALID_FD;
2341 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2342 npth_attr_destroy (&tattr);
2347 /* Helper for check_own_socket. */
2349 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2351 membuf_t *mb = opaque;
2352 put_membuf (mb, buffer, length);
2357 /* The thread running the actual check. We need to run this in a
2358 separate thread so that check_own_thread can be called from the
2361 check_own_socket_thread (void *arg)
2364 char *sockname = arg;
2365 assuan_context_t ctx = NULL;
2369 check_own_socket_running++;
2371 rc = assuan_new (&ctx);
2374 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2378 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2381 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2385 init_membuf (&mb, 100);
2386 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2387 NULL, NULL, NULL, NULL);
2388 put_membuf (&mb, "", 1);
2389 buffer = get_membuf (&mb, NULL);
2392 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2393 "GETINFO pid", gpg_strerror (rc));
2396 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2398 log_error ("socket is now serviced by another server\n");
2401 else if (opt.verbose > 1)
2402 log_error ("socket is still served by this server\n");
2409 assuan_release (ctx);
2412 /* We may not remove the socket as it is now in use by another
2413 server. Setting the name to empty does this. */
2416 if (socket_name_ssh)
2417 *socket_name_ssh = 0;
2418 shutdown_pending = 2;
2419 log_info ("this process is useless - shutting down\n");
2421 check_own_socket_running--;
2426 /* Check whether we are still listening on our own socket. In case
2427 another gpg-agent process started after us has taken ownership of
2428 our socket, we would linger around without any real task. Thus we
2429 better check once in a while whether we are really needed. */
2431 check_own_socket (void)
2438 if (disable_check_own_socket)
2441 if (check_own_socket_running || shutdown_pending)
2442 return; /* Still running or already shutting down. */
2444 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2446 return; /* Out of memory. */
2448 err = npth_attr_init (&tattr);
2451 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2452 err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
2454 log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
2455 npth_attr_destroy (&tattr);
2460 /* Figure out whether an agent is available and running. Prints an
2461 error if not. If SILENT is true, no messages are printed.
2462 Returns 0 if the agent is running. */
2464 check_for_running_agent (int silent)
2468 assuan_context_t ctx = NULL;
2470 sockname = make_filename (opt.homedir, GPG_AGENT_SOCK_NAME, NULL);
2472 err = assuan_new (&ctx);
2474 err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2479 log_error (_("no gpg-agent running in this session\n"));
2482 assuan_release (ctx);
2486 if (!opt.quiet && !silent)
2487 log_info ("gpg-agent running and available\n");
2489 assuan_release (ctx);