1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
4 * Copyright (C) 2013 Werner Koch
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
34 #ifdef HAVE_W32_SYSTEM
36 # define WINVER 0x0500 /* Same as in common/sysutils.c */
38 # ifdef HAVE_WINSOCK2_H
39 # include <winsock2.h>
43 #else /*!HAVE_W32_SYSTEM*/
44 # include <sys/socket.h>
46 #endif /*!HAVE_W32_SYSTEM*/
51 #define JNLIB_NEED_LOG_LOGV
52 #define JNLIB_NEED_AFLOCAL
54 #include <assuan.h> /* Malloc hooks and socket wrappers. */
57 #include "mkdtemp.h" /* Gnulib replacement. */
60 #include "gc-opt-flags.h"
62 #include "../common/estream.h"
64 enum cmd_and_opt_values
103 oEnforcePassphraseConstraints,
105 oMinPassphraseNonalpha,
106 oCheckPassphrasePattern,
108 oEnablePassphraseHistory,
110 oNoUseStandardSocket,
113 oIgnoreCacheForSigning,
116 oAllowPresetPassphrase,
127 static ARGPARSE_OPTS opts[] = {
129 { aGPGConfList, "gpgconf-list", 256, "@" },
130 { aGPGConfTest, "gpgconf-test", 256, "@" },
131 { aUseStandardSocketP, "use-standard-socket-p", 256, "@" },
133 { 301, NULL, 0, N_("@Options:\n ") },
135 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
136 { oServer, "server", 0, N_("run in server mode (foreground)") },
137 { oVerbose, "verbose", 0, N_("verbose") },
138 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
139 { oSh, "sh", 0, N_("sh-style command output") },
140 { oCsh, "csh", 0, N_("csh-style command output") },
141 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
142 { oDebug, "debug" ,4|16, "@"},
143 { oDebugAll, "debug-all" ,0, "@"},
144 { oDebugLevel, "debug-level" ,2, "@"},
145 { oDebugWait,"debug-wait",1, "@"},
146 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
147 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
148 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
149 { oUseStandardSocket, "use-standard-socket", 0,
150 N_("use a standard location for the socket")},
151 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
152 { oPinentryProgram, "pinentry-program", 2 ,
153 N_("|PGM|use PGM as the PIN-Entry program") },
154 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
155 { oScdaemonProgram, "scdaemon-program", 2 ,
156 N_("|PGM|use PGM as the SCdaemon program") },
157 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
158 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
160 { oBatch, "batch", 0, "@" },
161 { oHomedir, "homedir", 2, "@"},
163 { oDisplay, "display", 2, "@" },
164 { oTTYname, "ttyname", 2, "@" },
165 { oTTYtype, "ttytype", 2, "@" },
166 { oLCctype, "lc-ctype", 2, "@" },
167 { oLCmessages, "lc-messages", 2, "@" },
168 { oXauthority, "xauthority", 2, "@" },
169 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
170 { oKeepDISPLAY, "keep-display",
171 0, N_("ignore requests to change the X display")},
173 { oDefCacheTTL, "default-cache-ttl", 4,
174 N_("|N|expire cached PINs after N seconds")},
175 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
176 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
177 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
179 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
180 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
181 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
182 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
183 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
184 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
186 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
187 N_("do not use the PIN cache when signing")},
188 { oNoAllowMarkTrusted, "no-allow-mark-trusted", 0,
189 N_("disallow clients to mark keys as \"trusted\"")},
190 { oAllowMarkTrusted, "allow-mark-trusted", 0, "@"},
191 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
192 N_("allow presetting passphrase")},
193 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh support") },
194 { oPuttySupport, "enable-putty-support", 0,
195 #ifdef HAVE_W32_SYSTEM
196 N_("enable putty support")
201 { oWriteEnvFile, "write-env-file", 2|8,
202 N_("|FILE|write environment settings also to FILE")},
207 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
208 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
209 #define MAX_CACHE_TTL (120*60) /* 2 hours */
210 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
211 #define MIN_PASSPHRASE_LEN (8)
212 #define MIN_PASSPHRASE_NONALPHA (1)
213 #define MAX_PASSPHRASE_DAYS (0)
215 /* The timer tick used for housekeeping stuff. For Windows we use a
216 longer period as the SetWaitableTimer seems to signal earlier than
218 #ifdef HAVE_W32_SYSTEM
219 #define TIMERTICK_INTERVAL (4)
221 #define TIMERTICK_INTERVAL (2) /* Seconds. */
225 #ifdef HAVE_W32_SYSTEM
226 /* Flag indicating that support for Putty has been enabled. */
227 static int putty_support;
228 /* A magic value used with WM_COPYDATA. */
229 #define PUTTY_IPC_MAGIC 0x804e50ba
230 /* To avoid surprises we limit the size of the mapped IPC file to this
231 value. Putty currently (0.62) uses 8k, thus 16k should be enough
232 for the foreseeable future. */
233 #define PUTTY_IPC_MAXLEN 16384
234 #endif /*HAVE_W32_SYSTEM*/
236 /* The list of open file descriptors at startup. Note that this list
237 has been allocated using the standard malloc. */
238 static int *startup_fd_list;
240 /* The signal mask at startup and a flag telling whether it is valid. */
241 #ifdef HAVE_SIGPROCMASK
242 static sigset_t startup_signal_mask;
243 static int startup_signal_mask_valid;
246 /* Flag to indicate that a shutdown was requested. */
247 static int shutdown_pending;
249 /* Counter for the currently running own socket checks. */
250 static int check_own_socket_running;
252 /* It is possible that we are currently running under setuid permissions */
253 static int maybe_setuid = 1;
255 /* Name of the communication socket used for native gpg-agent requests. */
256 static char *socket_name;
258 /* Name of the communication socket used for ssh-agent-emulation. */
259 static char *socket_name_ssh;
261 /* We need to keep track of the server's nonces (these are dummies for
263 static assuan_sock_nonce_t socket_nonce;
264 static assuan_sock_nonce_t socket_nonce_ssh;
267 /* Default values for options passed to the pinentry. */
268 static char *default_display;
269 static char *default_ttyname;
270 static char *default_ttytype;
271 static char *default_lc_ctype;
272 static char *default_lc_messages;
273 static char *default_xauthority;
275 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
276 static char *config_filename;
278 /* Helper to implement --debug-level */
279 static const char *debug_level;
281 /* Keep track of the current log file so that we can avoid updating
282 the log file after a SIGHUP if it didn't changed. Malloced. */
283 static char *current_logfile;
285 /* The handle_tick() function may test whether a parent is still
286 running. We record the PID of the parent here or -1 if it should be
288 static pid_t parent_pid = (pid_t)(-1);
295 static char *create_socket_name (char *standard_name, char *template);
296 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
297 assuan_sock_nonce_t *nonce);
298 static void create_directories (void);
300 static void agent_init_default_ctrl (ctrl_t ctrl);
301 static void agent_deinit_default_ctrl (ctrl_t ctrl);
303 static void handle_connections (gnupg_fd_t listen_fd,
304 gnupg_fd_t listen_fd_ssh);
305 static void check_own_socket (void);
306 static int check_for_running_agent (int silent, int mode);
308 /* Pth wrapper function definitions. */
309 ASSUAN_SYSTEM_PTH_IMPL;
311 #if GCRYPT_VERSION_NUMBER < 0x010600
312 GCRY_THREAD_OPTION_PTH_IMPL;
313 #if GCRY_THREAD_OPTION_VERSION < 1
314 static int fixed_gcry_pth_init (void)
316 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
319 #endif /*GCRYPT_VERSION_NUMBER < 0x10600*/
321 #ifndef PTH_HAVE_PTH_THREAD_ID
322 static unsigned long pth_thread_id (void)
324 return (unsigned long)pth_self ();
335 make_libversion (const char *libname, const char *(*getfnc)(const char*))
342 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
346 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
347 strcpy (stpcpy (stpcpy (result, libname), " "), s);
353 my_strusage (int level)
355 static char *ver_gcry;
360 case 11: p = "gpg-agent (GnuPG)";
362 case 13: p = VERSION; break;
363 case 17: p = PRINTABLE_OS_NAME; break;
364 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
365 reporting address. This is so that we can change the
366 reporting address without breaking the translations. */
367 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
371 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
376 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
378 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
379 "Secret key management for GnuPG\n");
389 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
390 only the active debug flags are propagated to the subsystems. With
391 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
392 all flags already set. Note that we don't fail here, because it is
393 important to keep gpg-agent running even after re-reading the
394 options due to a SIGHUP. */
398 int numok = (debug_level && digitp (debug_level));
399 int numlvl = numok? atoi (debug_level) : 0;
403 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
405 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
406 opt.debug = DBG_ASSUAN_VALUE;
407 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
408 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
409 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
410 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
412 else if (!strcmp (debug_level, "guru") || numok)
415 /* Unless the "guru" string has been used we don't want to allow
416 hashing debugging. The rationale is that people tend to
417 select the highest debug value and would then clutter their
418 disk with debug files which may reveal confidential data. */
420 opt.debug &= ~(DBG_HASHING_VALUE);
424 log_error (_("invalid debug-level `%s' given\n"), debug_level);
425 opt.debug = 0; /* Reset debugging, so that prior debug
426 statements won't have an undesired effect. */
429 if (opt.debug && !opt.verbose)
431 if (opt.debug && opt.quiet)
434 if (opt.debug & DBG_MPI_VALUE)
435 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
436 if (opt.debug & DBG_CRYPTO_VALUE )
437 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
438 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
441 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
442 (opt.debug & DBG_COMMAND_VALUE)? " command":"",
443 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
444 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
445 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
446 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
447 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
448 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
449 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
453 /* Helper for cleanup to remove one socket with NAME. */
455 remove_socket (char *name)
462 p = strrchr (name, '/');
476 remove_socket (socket_name);
477 remove_socket (socket_name_ssh);
482 /* Handle options which are allowed to be reset after program start.
483 Return true when the current option in PARGS could be handled and
484 false if not. As a special feature, passing a value of NULL for
485 PARGS, resets the options to the default. REREAD should be set
486 true if it is not the initial option parsing. */
488 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
496 opt.pinentry_program = NULL;
497 opt.pinentry_touch_file = NULL;
498 opt.scdaemon_program = NULL;
499 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
500 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
501 opt.max_cache_ttl = MAX_CACHE_TTL;
502 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
503 opt.enforce_passphrase_constraints = 0;
504 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
505 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
506 opt.check_passphrase_pattern = NULL;
507 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
508 opt.enable_passhrase_history = 0;
509 opt.ignore_cache_for_signing = 0;
510 opt.allow_mark_trusted = 1;
511 opt.disable_scdaemon = 0;
515 switch (pargs->r_opt)
517 case oQuiet: opt.quiet = 1; break;
518 case oVerbose: opt.verbose++; break;
520 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
521 case oDebugAll: opt.debug = ~0; break;
522 case oDebugLevel: debug_level = pargs->r.ret_str; break;
526 return 0; /* not handeld */
527 if (!current_logfile || !pargs->r.ret_str
528 || strcmp (current_logfile, pargs->r.ret_str))
530 log_set_file (pargs->r.ret_str);
532 assuan_set_assuan_log_stream (log_get_stream ());
533 xfree (current_logfile);
534 current_logfile = xtrystrdup (pargs->r.ret_str);
538 case oNoGrab: opt.no_grab = 1; break;
540 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
541 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
542 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
543 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
545 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
546 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
547 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
548 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
550 case oEnforcePassphraseConstraints:
551 opt.enforce_passphrase_constraints=1;
553 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
554 case oMinPassphraseNonalpha:
555 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
557 case oCheckPassphrasePattern:
558 opt.check_passphrase_pattern = pargs->r.ret_str;
560 case oMaxPassphraseDays:
561 opt.max_passphrase_days = pargs->r.ret_ulong;
563 case oEnablePassphraseHistory:
564 opt.enable_passhrase_history = 1;
567 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
569 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
570 case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
572 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
575 return 0; /* not handled */
578 return 1; /* handled */
582 /* The main entry point. */
584 main (int argc, char **argv )
589 FILE *configfp = NULL;
590 char *configname = NULL;
592 unsigned configlineno;
594 int default_config =1;
601 char *logfile = NULL;
603 int gpgconf_list = 0;
605 const char *env_file_name = NULL;
606 struct assuan_malloc_hooks malloc_hooks;
608 /* Before we do anything else we save the list of currently open
609 file descriptors and the signal mask. This info is required to
610 do the exec call properly. */
611 startup_fd_list = get_all_open_fds ();
612 #ifdef HAVE_SIGPROCMASK
613 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
614 startup_signal_mask_valid = 1;
615 #endif /*HAVE_SIGPROCMASK*/
617 /* Set program name etc. */
618 set_strusage (my_strusage);
619 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
620 /* Please note that we may running SUID(ROOT), so be very CAREFUL
621 when adding any stuff between here and the call to INIT_SECMEM()
622 somewhere after the option parsing */
623 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
625 /* Make sure that our subsystems are ready. */
627 init_common_subsystems ();
630 #if GCRYPT_VERSION_NUMBER < 0x010600
631 /* Libgcrypt < 1.6 requires us to register the threading model first.
632 Note that this will also do the pth_init. */
633 #if GCRY_THREAD_OPTION_VERSION < 1
634 gcry_threads_pth.init = fixed_gcry_pth_init;
636 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
639 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
642 #endif /*GCRYPT_VERSION_NUMBER < 0x010600*/
645 /* Check that the libraries are suitable. Do it here because
646 the option parsing may need services of the library. */
647 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
649 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
650 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
653 malloc_hooks.malloc = gcry_malloc;
654 malloc_hooks.realloc = gcry_realloc;
655 malloc_hooks.free = gcry_free;
656 assuan_set_malloc_hooks (&malloc_hooks);
657 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
658 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
659 assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
662 setup_libgcrypt_logging ();
663 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
665 disable_core_dumps ();
667 /* Set default options. */
668 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
669 #ifdef USE_STANDARD_SOCKET
670 opt.use_standard_socket = 1; /* Under Windows we always use a standard
674 shell = getenv ("SHELL");
675 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
678 opt.homedir = default_homedir ();
680 /* Record some of the original environment strings. */
684 static const char *names[] =
685 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
688 opt.startup_env = session_env_new ();
689 if (!opt.startup_env)
690 err = gpg_error_from_syserror ();
691 for (idx=0; !err && names[idx]; idx++)
693 s = getenv (names[idx]);
695 err = session_env_setenv (opt.startup_env, names[idx], s);
701 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
704 log_fatal ("error recording startup environment: %s\n",
707 /* Fixme: Better use the locale function here. */
708 opt.startup_lc_ctype = getenv ("LC_CTYPE");
709 if (opt.startup_lc_ctype)
710 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
711 opt.startup_lc_messages = getenv ("LC_MESSAGES");
712 if (opt.startup_lc_messages)
713 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
716 /* Check whether we have a config file on the commandline */
721 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
722 while (arg_parse( &pargs, opts))
724 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
726 else if (pargs.r_opt == oOptions)
727 { /* yes there is one, so we do not try the default one, but
728 read the option file when it is encountered at the
732 else if (pargs.r_opt == oNoOptions)
733 default_config = 0; /* --no-options */
734 else if (pargs.r_opt == oHomedir)
735 opt.homedir = pargs.r.ret_str;
738 /* Initialize the secure memory. */
739 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
743 Now we are now working under our real uid
747 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
753 pargs.flags= 1; /* do not remove the args */
758 configfp = fopen (configname, "r");
764 log_info (_("NOTE: no default option file `%s'\n"),
766 /* Save the default conf file name so that
767 reread_configuration is able to test whether the
768 config file has been created in the meantime. */
769 xfree (config_filename);
770 config_filename = configname;
775 log_error (_("option file `%s': %s\n"),
776 configname, strerror(errno) );
782 if (parse_debug && configname )
783 log_info (_("reading options from `%s'\n"), configname );
787 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
789 if (parse_rereadable_options (&pargs, 0))
790 continue; /* Already handled */
793 case aGPGConfList: gpgconf_list = 1; break;
794 case aGPGConfTest: gpgconf_list = 2; break;
795 case aUseStandardSocketP: gpgconf_list = 3; break;
796 case oBatch: opt.batch=1; break;
798 case oDebugWait: debug_wait = pargs.r.ret_int; break;
801 /* config files may not be nested (silently ignore them) */
805 configname = xstrdup(pargs.r.ret_str);
809 case oNoGreeting: nogreeting = 1; break;
810 case oNoVerbose: opt.verbose = 0; break;
811 case oNoOptions: break; /* no-options */
812 case oHomedir: opt.homedir = pargs.r.ret_str; break;
813 case oNoDetach: nodetach = 1; break;
814 case oLogFile: logfile = pargs.r.ret_str; break;
815 case oCsh: csh_style = 1; break;
816 case oSh: csh_style = 0; break;
817 case oServer: pipe_server = 1; break;
818 case oDaemon: is_daemon = 1; break;
820 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
821 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
822 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
823 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
824 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
825 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
828 case oUseStandardSocket: opt.use_standard_socket = 1; break;
829 case oNoUseStandardSocket: opt.use_standard_socket = 0; break;
831 case oFakedSystemTime:
833 time_t faked_time = isotime2epoch (pargs.r.ret_str);
834 if (faked_time == (time_t)(-1))
835 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
836 gnupg_set_time (faked_time, 0);
840 case oKeepTTY: opt.keep_tty = 1; break;
841 case oKeepDISPLAY: opt.keep_display = 1; break;
843 case oSSHSupport: opt.ssh_support = 1; break;
845 # ifdef HAVE_W32_SYSTEM
853 env_file_name = pargs.r.ret_str;
855 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
858 default : pargs.err = configfp? 1:2; break;
865 /* Keep a copy of the name so that it can be read on SIGHUP. */
866 if (config_filename != configname)
868 xfree (config_filename);
869 config_filename = configname;
877 if (log_get_errorcount(0))
884 fprintf (stderr, "%s %s; %s\n",
885 strusage(11), strusage(13), strusage(14) );
886 fprintf (stderr, "%s\n", strusage(15) );
888 #ifdef IS_DEVELOPMENT_VERSION
889 /* We don't want to print it here because gpg-agent is useful of its
890 own and quite matured. */
891 /*log_info ("NOTE: this is a development version!\n");*/
896 if (atexit (cleanup))
898 log_error ("atexit failed\n");
903 initialize_module_call_pinentry ();
904 initialize_module_call_scd ();
905 initialize_module_trustlist ();
907 /* Try to create missing directories. */
908 create_directories ();
910 if (debug_wait && pipe_server)
912 log_debug ("waiting for debugger - my pid is %u .....\n",
913 (unsigned int)getpid());
914 gnupg_sleep (debug_wait);
915 log_debug ("... okay\n");
918 if (gpgconf_list == 3)
919 agent_exit (!opt.use_standard_socket);
920 if (gpgconf_list == 2)
927 /* List options and default values in the GPG Conf format. */
928 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
929 filename_esc = percent_escape (filename, NULL);
931 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
932 GC_OPT_FLAG_DEFAULT, filename_esc);
934 xfree (filename_esc);
936 printf ("verbose:%lu:\n"
938 "debug-level:%lu:\"none:\n"
940 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
941 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
942 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
943 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
944 printf ("default-cache-ttl:%lu:%d:\n",
945 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
946 printf ("default-cache-ttl-ssh:%lu:%d:\n",
947 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
948 printf ("max-cache-ttl:%lu:%d:\n",
949 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
950 printf ("max-cache-ttl-ssh:%lu:%d:\n",
951 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
952 printf ("enforce-passphrase-constraints:%lu:\n",
953 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
954 printf ("min-passphrase-len:%lu:%d:\n",
955 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
956 printf ("min-passphrase-nonalpha:%lu:%d:\n",
957 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
958 MIN_PASSPHRASE_NONALPHA);
959 printf ("check-passphrase-pattern:%lu:\n",
960 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
961 printf ("max-passphrase-days:%lu:%d:\n",
962 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
963 MAX_PASSPHRASE_DAYS);
964 printf ("enable-passphrase-history:%lu:\n",
965 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
966 printf ("no-grab:%lu:\n",
967 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
968 printf ("ignore-cache-for-signing:%lu:\n",
969 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
970 printf ("no-allow-mark-trusted:%lu:\n",
971 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
972 printf ("disable-scdaemon:%lu:\n",
973 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
974 #ifdef HAVE_W32_SYSTEM
975 printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
977 printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
983 /* If this has been called without any options, we merely check
984 whether an agent is already running. We do this here so that we
985 don't clobber a logfile but print it directly to stderr. */
986 if (!pipe_server && !is_daemon)
988 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
989 check_for_running_agent (0, 0);
994 /* gpg-agent usually does not output any messages because it runs in
995 the background. For log files it is acceptable to have messages
996 always encoded in utf-8. We switch here to utf-8, so that
997 commands like --help still give native messages. It is far
998 easier to switch only once instead of for every message and it
999 actually helps when more then one thread is active (avoids an
1000 extra copy step). */
1001 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1004 /* Now start with logging to a file if this is desired. */
1007 log_set_file (logfile);
1008 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
1009 |JNLIB_LOG_WITH_TIME
1010 |JNLIB_LOG_WITH_PID));
1011 current_logfile = xstrdup (logfile);
1014 assuan_set_assuan_log_stream (log_get_stream ());
1016 /* Make sure that we have a default ttyname. */
1017 if (!default_ttyname && ttyname (1))
1018 default_ttyname = xstrdup (ttyname (1));
1019 if (!default_ttytype && getenv ("TERM"))
1020 default_ttytype = xstrdup (getenv ("TERM"));
1025 /* This is the simple pipe based server */
1028 ctrl = xtrycalloc (1, sizeof *ctrl);
1031 log_error ("error allocating connection control data: %s\n",
1035 ctrl->session_env = session_env_new ();
1036 if (!ctrl->session_env)
1038 log_error ("error allocating session environment block: %s\n",
1043 agent_init_default_ctrl (ctrl);
1044 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1045 agent_deinit_default_ctrl (ctrl);
1048 else if (!is_daemon)
1051 { /* Regular server mode */
1056 /* Remove the DISPLAY variable so that a pinentry does not
1057 default to a specific display. There is still a default
1058 display when gpg-agent was started using --display or a
1059 client requested this using an OPTION command. Note, that we
1060 don't do this when running in reverse daemon mode (i.e. when
1061 exec the program given as arguments). */
1062 #ifndef HAVE_W32_SYSTEM
1063 if (!opt.keep_display && !argc)
1064 unsetenv ("DISPLAY");
1068 /* Create the sockets. */
1069 socket_name = create_socket_name
1070 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
1071 if (opt.ssh_support)
1072 socket_name_ssh = create_socket_name
1073 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
1075 fd = create_server_socket (socket_name, 0, &socket_nonce);
1076 if (opt.ssh_support)
1077 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
1079 fd_ssh = GNUPG_INVALID_FD;
1081 /* If we are going to exec a program in the parent, we record
1082 the PID, so that the child may check whether the program is
1085 parent_pid = getpid ();
1088 #ifdef HAVE_W32_SYSTEM
1090 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
1091 #else /*!HAVE_W32_SYSTEM*/
1093 if (pid == (pid_t)-1)
1095 log_fatal ("fork failed: %s\n", strerror (errno) );
1099 { /* We are the parent */
1100 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
1102 /* Close the socket FD. */
1105 /* Note that we used a standard fork so that Pth runs in
1106 both the parent and the child. The pth_fork would
1107 terminate Pth in the child but that is not the way we
1108 want it. Thus we use a plain fork and terminate Pth here
1109 in the parent. The pth_kill may or may not work reliable
1110 but it should not harm to call it. Because Pth fiddles
1111 with the signal mask the signal mask might not be correct
1112 right now and thus we restore it. That is not strictly
1113 necessary but some programs falsely assume a cleared
1114 signal mask. es_pth_kill is a wrapper around pth_kill to
1115 take care not to use any Pth functions in the estream
1116 code after Pth has been killed. */
1117 if ( !es_pth_kill () )
1118 log_error ("pth_kill failed in forked process\n");
1120 #ifdef HAVE_SIGPROCMASK
1121 if (startup_signal_mask_valid)
1123 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1124 log_error ("error restoring signal mask: %s\n",
1128 log_info ("no saved signal mask\n");
1129 #endif /*HAVE_SIGPROCMASK*/
1131 /* Create the info string: <name>:<pid>:<protocol_version> */
1132 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1133 socket_name, (ulong)pid ) < 0)
1135 log_error ("out of core\n");
1136 kill (pid, SIGTERM);
1139 if (opt.ssh_support)
1141 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1142 socket_name_ssh) < 0)
1144 log_error ("out of core\n");
1145 kill (pid, SIGTERM);
1148 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1151 log_error ("out of core\n");
1152 kill (pid, SIGTERM);
1157 *socket_name = 0; /* Don't let cleanup() remove the socket -
1158 the child should do this from now on */
1159 if (opt.ssh_support)
1160 *socket_name_ssh = 0;
1166 fp = fopen (env_file_name, "w");
1168 log_error (_("error creating `%s': %s\n"),
1169 env_file_name, strerror (errno));
1172 fputs (infostr, fp);
1174 if (opt.ssh_support)
1176 fputs (infostr_ssh_sock, fp);
1178 fputs (infostr_ssh_pid, fp);
1187 { /* Run the program given on the commandline. */
1188 if (putenv (infostr))
1190 log_error ("failed to set environment: %s\n",
1192 kill (pid, SIGTERM );
1195 if (opt.ssh_support && putenv (infostr_ssh_sock))
1197 log_error ("failed to set environment: %s\n",
1199 kill (pid, SIGTERM );
1202 if (opt.ssh_support && putenv (infostr_ssh_pid))
1204 log_error ("failed to set environment: %s\n",
1206 kill (pid, SIGTERM );
1210 /* Close all the file descriptors except the standard
1211 ones and those open at startup. We explicitly don't
1212 close 0,1,2 in case something went wrong collecting
1214 close_all_fds (3, startup_fd_list);
1216 /* Run the command. */
1217 execvp (argv[0], argv);
1218 log_error ("failed to run the command: %s\n", strerror (errno));
1219 kill (pid, SIGTERM);
1224 /* Print the environment string, so that the caller can use
1225 shell's eval to set it */
1228 *strchr (infostr, '=') = ' ';
1229 printf ("setenv %s;\n", infostr);
1230 if (opt.ssh_support)
1232 *strchr (infostr_ssh_sock, '=') = ' ';
1233 printf ("setenv %s;\n", infostr_ssh_sock);
1234 *strchr (infostr_ssh_pid, '=') = ' ';
1235 printf ("setenv %s;\n", infostr_ssh_pid);
1240 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1241 if (opt.ssh_support)
1243 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1244 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1248 if (opt.ssh_support)
1250 xfree (infostr_ssh_sock);
1251 xfree (infostr_ssh_pid);
1262 /* Detach from tty and put process into a new session */
1266 unsigned int oldflags;
1268 /* Close stdin, stdout and stderr unless it is the log stream */
1269 for (i=0; i <= 2; i++)
1271 if (!log_test_fd (i) && i != fd )
1274 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1276 log_error ("failed to open `%s': %s\n",
1277 "/dev/null", strerror (errno));
1285 log_error ("setsid() failed: %s\n", strerror(errno) );
1290 log_get_prefix (&oldflags);
1291 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1292 opt.running_detached = 1;
1297 log_error ("chdir to / failed: %s\n", strerror (errno));
1302 struct sigaction sa;
1304 sa.sa_handler = SIG_IGN;
1305 sigemptyset (&sa.sa_mask);
1307 sigaction (SIGPIPE, &sa, NULL);
1309 #endif /*!HAVE_W32_SYSTEM*/
1311 log_info ("%s %s started\n", strusage(11), strusage(13) );
1312 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1313 assuan_sock_close (fd);
1323 /*FIXME: update_random_seed_file();*/
1325 /* at this time a bit annoying */
1326 if (opt.debug & DBG_MEMSTAT_VALUE)
1328 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1329 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1332 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1334 gcry_control (GCRYCTL_TERM_SECMEM );
1335 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1341 agent_init_default_ctrl (ctrl_t ctrl)
1343 assert (ctrl->session_env);
1345 /* Note we ignore malloc errors because we can't do much about it
1346 and the request will fail anyway shortly after this
1348 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1349 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1350 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1351 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1352 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1355 xfree (ctrl->lc_ctype);
1356 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1358 if (ctrl->lc_messages)
1359 xfree (ctrl->lc_messages);
1360 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1366 agent_deinit_default_ctrl (ctrl_t ctrl)
1368 session_env_release (ctrl->session_env);
1371 xfree (ctrl->lc_ctype);
1372 if (ctrl->lc_messages)
1373 xfree (ctrl->lc_messages);
1377 /* Reread parts of the configuration. Note, that this function is
1378 obviously not thread-safe and should only be called from the PTH
1381 Fixme: Due to the way the argument parsing works, we create a
1382 memory leak here for all string type arguments. There is currently
1383 no clean way to tell whether the memory for the argument has been
1384 allocated or points into the process' original arguments. Unless
1385 we have a mechanism to tell this, we need to live on with this. */
1387 reread_configuration (void)
1389 ARGPARSE_ARGS pargs;
1391 unsigned int configlineno = 0;
1394 if (!config_filename)
1395 return; /* No config file. */
1397 fp = fopen (config_filename, "r");
1400 log_info (_("option file `%s': %s\n"),
1401 config_filename, strerror(errno) );
1405 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1407 memset (&pargs, 0, sizeof pargs);
1409 pargs.argc = &dummy;
1410 pargs.flags = 1; /* do not remove the args */
1411 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1413 if (pargs.r_opt < -1)
1414 pargs.err = 1; /* Print a warning. */
1415 else /* Try to parse this option - ignore unchangeable ones. */
1416 parse_rereadable_options (&pargs, 1);
1423 /* Return the file name of the socket we are using for native
1426 get_agent_socket_name (void)
1428 const char *s = socket_name;
1430 return (s && *s)? s : NULL;
1433 /* Return the file name of the socket we are using for SSH
1436 get_agent_ssh_socket_name (void)
1438 const char *s = socket_name_ssh;
1440 return (s && *s)? s : NULL;
1444 /* Under W32, this function returns the handle of the scdaemon
1445 notification event. Calling it the first time creates that
1447 #ifdef HAVE_W32_SYSTEM
1449 get_agent_scd_notify_event (void)
1451 static HANDLE the_event;
1456 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1458 /* We need to use manual reset evet object due to the way our
1459 w32-pth wait function works: If we would use an automatic
1460 reset event we are not able to figure out which handle has
1461 been signaled because at the time we single out the signaled
1462 handles using WFSO the event has already been reset due to
1464 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1466 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1467 else if (!DuplicateHandle (GetCurrentProcess(), h,
1468 GetCurrentProcess(), &h2,
1469 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1471 log_error ("setting syncronize for scd notify event failed: %s\n",
1472 w32_strerror (-1) );
1482 log_debug ("returning notify handle %p\n", the_event);
1485 #endif /*HAVE_W32_SYSTEM*/
1489 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1490 true using STANDARD_NAME in the home directory or if given as
1491 false from the mkdir type name TEMPLATE. In the latter case a
1492 unique name in a unique new directory will be created. In both
1493 cases check for valid characters as well as against a maximum
1494 allowed length for a unix domain socket is done. The function
1495 terminates the process in case of an error. Returns: Pointer to an
1496 allocated string with the absolute name of the socket used. */
1498 create_socket_name (char *standard_name, char *template)
1502 if (opt.use_standard_socket)
1503 name = make_filename (opt.homedir, standard_name, NULL);
1506 name = xstrdup (template);
1507 p = strrchr (name, '/');
1511 if (!mkdtemp (name))
1513 log_error (_("can't create directory `%s': %s\n"),
1514 name, strerror (errno));
1520 if (strchr (name, PATHSEP_C))
1522 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1525 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1527 log_error (_("name of socket too long\n"));
1535 /* Create a Unix domain socket with NAME. Returns the file descriptor
1536 or terminates the process in case of an error. Not that this
1537 function needs to be used for the regular socket first and only
1538 then for the ssh socket. */
1540 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1542 struct sockaddr_un *serv_addr;
1547 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1548 if (fd == ASSUAN_INVALID_FD)
1550 log_error (_("can't create socket: %s\n"), strerror (errno));
1554 serv_addr = xmalloc (sizeof (*serv_addr));
1555 memset (serv_addr, 0, sizeof *serv_addr);
1556 serv_addr->sun_family = AF_UNIX;
1557 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1559 log_error (_("socket name `%s' is too long\n"), name);
1562 strcpy (serv_addr->sun_path, name);
1563 len = SUN_LEN (serv_addr);
1564 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1565 if (opt.use_standard_socket && rc == -1 && errno == EADDRINUSE)
1567 /* Check whether a gpg-agent is already running on the standard
1568 socket. We do this test only if this is not the ssh socket.
1569 For ssh we assume that a test for gpg-agent has already been
1570 done and reuse the requested ssh socket. Testing the
1571 ssh-socket is not possible because at this point, though we
1572 know the new Assuan socket, the Assuan server and thus the
1573 ssh-agent server is not yet operational. This would lead to
1575 if (!is_ssh && !check_for_running_agent (1, 1))
1577 log_error (_("a gpg-agent is already running - "
1578 "not starting a new one\n"));
1579 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1580 assuan_sock_close (fd);
1584 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1587 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1588 log_error (_("error getting nonce for the socket\n"));
1591 /* We use gpg_strerror here because it allows us to get strings
1592 for some W32 socket error codes. */
1593 log_error (_("error binding socket to `%s': %s\n"),
1594 serv_addr->sun_path,
1595 gpg_strerror (gpg_error_from_errno (errno)));
1597 assuan_sock_close (fd);
1598 if (opt.use_standard_socket)
1599 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1603 if (listen (FD2INT(fd), 5 ) == -1)
1605 log_error (_("listen() failed: %s\n"), strerror (errno));
1606 assuan_sock_close (fd);
1611 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1617 /* Check that the directory for storing the private keys exists and
1618 create it if not. This function won't fail as it is only a
1619 convenience function and not strictly necessary. */
1621 create_private_keys_directory (const char *home)
1624 struct stat statbuf;
1626 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1627 if (stat (fname, &statbuf) && errno == ENOENT)
1629 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1630 if (!CreateDirectory (fname, NULL))
1631 log_error (_("can't create directory `%s': %s\n"),
1632 fname, w32_strerror (-1) );
1634 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1635 log_error (_("can't create directory `%s': %s\n"),
1636 fname, strerror (errno) );
1638 else if (!opt.quiet)
1639 log_info (_("directory `%s' created\n"), fname);
1644 /* Create the directory only if the supplied directory name is the
1645 same as the default one. This way we avoid to create arbitrary
1646 directories when a non-default home directory is used. To cope
1647 with HOME, we compare only the suffix if we see that the default
1648 homedir does start with a tilde. We don't stop here in case of
1649 problems because other functions will throw an error anyway.*/
1651 create_directories (void)
1653 struct stat statbuf;
1654 const char *defhome = standard_homedir ();
1657 home = make_filename (opt.homedir, NULL);
1658 if ( stat (home, &statbuf) )
1660 if (errno == ENOENT)
1663 #ifdef HAVE_W32_SYSTEM
1664 ( !compare_filenames (home, defhome) )
1667 && (strlen (home) >= strlen (defhome+1)
1668 && !strcmp (home + strlen(home)
1669 - strlen (defhome+1), defhome+1)))
1670 || (*defhome != '~' && !strcmp (home, defhome) )
1674 #ifdef HAVE_W32_SYSTEM
1675 if (!CreateDirectory (home, NULL))
1676 log_error (_("can't create directory `%s': %s\n"),
1677 home, w32_strerror (-1) );
1679 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1680 log_error (_("can't create directory `%s': %s\n"),
1681 home, strerror (errno) );
1686 log_info (_("directory `%s' created\n"), home);
1687 create_private_keys_directory (home);
1692 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1694 else if ( !S_ISDIR(statbuf.st_mode))
1696 log_error (_("can't use `%s' as home directory\n"), home);
1698 else /* exists and is a directory. */
1700 create_private_keys_directory (home);
1707 /* This is the worker for the ticker. It is called every few seconds
1708 and may only do fast operations. */
1712 static time_t last_minute;
1715 last_minute = time (NULL);
1717 /* Check whether the scdaemon has died and cleanup in this case. */
1718 agent_scd_check_aliveness ();
1720 /* If we are running as a child of another process, check whether
1721 the parent is still alive and shutdown if not. */
1722 #ifndef HAVE_W32_SYSTEM
1723 if (parent_pid != (pid_t)(-1))
1725 if (kill (parent_pid, 0))
1727 shutdown_pending = 2;
1730 log_info ("parent process died - shutting down\n");
1731 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1737 #endif /*HAVE_W32_SYSTEM*/
1739 /* Code to be run every minute. */
1740 if (last_minute + 60 <= time (NULL))
1742 check_own_socket ();
1743 last_minute = time (NULL);
1749 /* A global function which allows us to call the reload stuff from
1750 other places too. This is only used when build for W32. */
1752 agent_sighup_action (void)
1754 log_info ("SIGHUP received - "
1755 "re-reading configuration and flushing cache\n");
1756 agent_flush_cache ();
1757 reread_configuration ();
1758 agent_reload_trustlist ();
1763 agent_sigusr2_action (void)
1766 log_info ("SIGUSR2 received - updating card event counter\n");
1767 /* Nothing to check right now. We only increment a counter. */
1768 bump_card_eventcounter ();
1773 handle_signal (int signo)
1777 #ifndef HAVE_W32_SYSTEM
1779 agent_sighup_action ();
1783 log_info ("SIGUSR1 received - printing internal information:\n");
1784 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1785 agent_query_dump_state ();
1786 agent_scd_dump_state ();
1790 agent_sigusr2_action ();
1794 if (!shutdown_pending)
1795 log_info ("SIGTERM received - shutting down ...\n");
1797 log_info ("SIGTERM received - still %ld running threads\n",
1798 pth_ctrl( PTH_CTRL_GETTHREADS ));
1800 if (shutdown_pending > 2)
1802 log_info ("shutdown forced\n");
1803 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1810 log_info ("SIGINT received - immediate shutdown\n");
1811 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1817 log_info ("signal %d received - no action defined\n", signo);
1822 /* Check the nonce on a new connection. This is a NOP unless we we
1823 are using our Unix domain socket emulation under Windows. */
1825 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1827 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1829 log_info (_("error reading nonce on fd %d: %s\n"),
1830 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1831 assuan_sock_close (ctrl->thread_startup.fd);
1840 #ifdef HAVE_W32_SYSTEM
1841 /* The window message processing function for Putty. Warning: This
1842 code runs as a native Windows thread. Use of our own functions
1843 needs to be bracket with pth_leave/pth_enter. */
1844 static LRESULT CALLBACK
1845 putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1849 COPYDATASTRUCT *cds;
1850 const char *mapfile;
1855 PSECURITY_DESCRIPTOR psd = NULL;
1858 if (msg != WM_COPYDATA)
1861 /* log_debug ("putty loop: received WM_%u\n", msg ); */
1863 return DefWindowProc (hwnd, msg, wparam, lparam);
1866 cds = (COPYDATASTRUCT*)lparam;
1867 if (cds->dwData != PUTTY_IPC_MAGIC)
1868 return 0; /* Ignore data with the wrong magic. */
1869 mapfile = cds->lpData;
1870 if (!cds->cbData || mapfile[cds->cbData - 1])
1871 return 0; /* Ignore empty and non-properly terminated strings. */
1876 log_debug ("ssh map file '%s'", mapfile);
1880 maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
1884 log_debug ("ssh map handle %p\n", maphd);
1888 if (!maphd || maphd == INVALID_HANDLE_VALUE)
1893 mysid = w32_get_user_sid ();
1896 log_error ("error getting my sid\n");
1900 w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
1901 OWNER_SECURITY_INFORMATION,
1902 &mapsid, NULL, NULL, NULL,
1906 log_error ("error getting sid of ssh map file: rc=%d", w32rc);
1914 if (!ConvertSidToStringSid (mysid, &sidstr))
1916 log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
1918 if (!ConvertSidToStringSid (mapsid, &sidstr))
1920 log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
1924 if (!EqualSid (mysid, mapsid))
1926 log_error ("ssh map file has a non-matching sid\n");
1930 data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
1932 log_debug ("ssh IPC buffer at %p\n", data);
1936 /* log_printhex ("request:", data, 20); */
1938 ctrl = xtrycalloc (1, sizeof *ctrl);
1941 log_error ("error allocating connection control data: %s\n",
1945 ctrl->session_env = session_env_new ();
1946 if (!ctrl->session_env)
1948 log_error ("error allocating session environment block: %s\n",
1953 agent_init_default_ctrl (ctrl);
1954 if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
1955 ret = 1; /* Valid ssh message has been constructed. */
1956 agent_deinit_default_ctrl (ctrl);
1957 /* log_printhex (" reply:", data, 20); */
1962 UnmapViewOfFile (data);
1967 CloseHandle (maphd);
1973 #endif /*HAVE_W32_SYSTEM*/
1976 #ifdef HAVE_W32_SYSTEM
1977 /* The thread handling Putty's IPC requests. */
1979 putty_message_thread (void *arg)
1981 WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
1982 NULL, NULL, NULL, NULL, NULL, "Pageant"};
1989 log_info ("putty message loop thread 0x%lx started\n", pth_thread_id ());
1991 /* The message loop runs as thread independet from out Pth system.
1992 This also meand that we need to make sure that we switch back to
1993 our system before calling any no-windows function. */
1996 /* First create a window to make sure that a message queue exists
1998 if (!RegisterClass (&wndwclass))
2001 log_error ("error registering Pageant window class");
2004 hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2006 HWND_MESSAGE, /* hWndParent */
2007 NULL, /* hWndMenu */
2008 NULL, /* hInstance */
2013 log_error ("error creating Pageant window");
2017 while (GetMessage(&msg, NULL, 0, 0))
2019 TranslateMessage(&msg);
2020 DispatchMessage(&msg);
2027 log_info ("putty message loop thread 0x%lx stopped\n", pth_thread_id ());
2030 #endif /*HAVE_W32_SYSTEM*/
2033 /* This is the standard connection thread's main function. */
2035 start_connection_thread (void *arg)
2039 if (check_nonce (ctrl, &socket_nonce))
2042 agent_init_default_ctrl (ctrl);
2044 log_info (_("handler 0x%lx for fd %d started\n"),
2045 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
2047 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2049 log_info (_("handler 0x%lx for fd %d terminated\n"),
2050 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
2052 agent_deinit_default_ctrl (ctrl);
2058 /* This is the ssh connection thread's main function. */
2060 start_connection_thread_ssh (void *arg)
2064 if (check_nonce (ctrl, &socket_nonce_ssh))
2067 agent_init_default_ctrl (ctrl);
2069 log_info (_("ssh handler 0x%lx for fd %d started\n"),
2070 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
2072 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2074 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2075 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
2077 agent_deinit_default_ctrl (ctrl);
2083 /* Connection handler loop. Wait for connection requests and spawn a
2084 thread after accepting a connection. */
2086 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
2089 pth_event_t ev, time_ev;
2092 struct sockaddr_un paddr;
2094 fd_set fdset, read_fdset;
2099 tattr = pth_attr_new();
2100 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2101 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2103 #ifndef HAVE_W32_SYSTEM /* fixme */
2104 /* Make sure that the signals we are going to handle are not blocked
2105 and create an event object for them. We also set the default
2106 action to ignore because we use an Pth event to get notified
2107 about signals. This avoids that the default action is taken in
2108 case soemthing goes wrong within Pth. The problem might also be
2110 sigemptyset (&sigs );
2112 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
2113 struct sigaction sa;
2116 for (i=0; i < DIM (mysigs); i++)
2118 sigemptyset (&sa.sa_mask);
2119 sa.sa_handler = SIG_IGN;
2121 sigaction (mysigs[i], &sa, NULL);
2123 sigaddset (&sigs, mysigs[i]);
2127 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
2128 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2130 # ifdef PTH_EVENT_HANDLE
2132 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
2135 /* Use a dummy event. */
2137 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2142 /* On Windows we need to fire up a separate thread to listen for
2143 requests from Putty (an SSH client), so we can replace Putty's
2144 Pageant (its ssh-agent implementation). */
2145 #ifdef HAVE_W32_SYSTEM
2148 pth_attr_set (tattr, PTH_ATTR_NAME, "putty message loop");
2149 if (!pth_spawn (tattr, putty_message_thread, NULL))
2151 log_error ("error spawning putty message loop: %s\n",
2155 #endif /*HAVE_W32_SYSTEM*/
2157 /* Set a flag to tell call-scd.c that it may enable event
2159 opt.sigusr2_enabled = 1;
2162 FD_SET (FD2INT (listen_fd), &fdset);
2163 nfd = FD2INT (listen_fd);
2164 if (listen_fd_ssh != GNUPG_INVALID_FD)
2166 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2167 if (FD2INT (listen_fd_ssh) > nfd)
2168 nfd = FD2INT (listen_fd_ssh);
2173 /* Make sure that our signals are not blocked. */
2174 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
2176 /* Shutdown test. */
2177 if (shutdown_pending)
2179 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
2182 /* Do not accept new connections but keep on running the
2183 loop to cope with the timer events. */
2187 /* Create a timeout event if needed. To help with power saving
2188 we syncronize the ticks to the next full second. */
2191 pth_time_t nexttick;
2193 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
2194 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
2197 nexttick.tv_usec = 0;
2199 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
2202 /* POSIX says that fd_set should be implemented as a structure,
2203 thus a simple assignment is fine to copy the entire set. */
2207 pth_event_concat (ev, time_ev, NULL);
2208 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
2210 pth_event_isolate (time_ev);
2214 if (pth_event_occurred (ev)
2215 || (time_ev && pth_event_occurred (time_ev)))
2217 if (pth_event_occurred (ev))
2219 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
2220 agent_sigusr2_action ();
2222 handle_signal (signo);
2225 if (time_ev && pth_event_occurred (time_ev))
2227 pth_event_free (time_ev, PTH_FREE_ALL);
2233 log_error (_("pth_select failed: %s - waiting 1s\n"),
2239 if (pth_event_occurred (ev))
2241 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
2242 agent_sigusr2_action ();
2244 handle_signal (signo);
2248 if (time_ev && pth_event_occurred (time_ev))
2250 pth_event_free (time_ev, PTH_FREE_ALL);
2256 /* We now might create new threads and because we don't want any
2257 signals (as we are handling them here) to be delivered to a
2258 new thread. Thus we need to block those signals. */
2259 pth_sigmask (SIG_BLOCK, &sigs, NULL);
2261 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
2265 plen = sizeof paddr;
2266 fd = INT2FD (pth_accept (FD2INT(listen_fd),
2267 (struct sockaddr *)&paddr, &plen));
2268 if (fd == GNUPG_INVALID_FD)
2270 log_error ("accept failed: %s\n", strerror (errno));
2272 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2274 log_error ("error allocating connection control data: %s\n",
2276 assuan_sock_close (fd);
2278 else if ( !(ctrl->session_env = session_env_new ()) )
2280 log_error ("error allocating session environment block: %s\n",
2283 assuan_sock_close (fd);
2287 char threadname[50];
2289 snprintf (threadname, sizeof threadname-1,
2290 "conn fd=%d (gpg)", FD2INT(fd));
2291 threadname[sizeof threadname -1] = 0;
2292 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2293 ctrl->thread_startup.fd = fd;
2294 if (!pth_spawn (tattr, start_connection_thread, ctrl))
2296 log_error ("error spawning connection handler: %s\n",
2298 assuan_sock_close (fd);
2302 fd = GNUPG_INVALID_FD;
2305 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
2306 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
2310 plen = sizeof paddr;
2311 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
2312 (struct sockaddr *)&paddr, &plen));
2313 if (fd == GNUPG_INVALID_FD)
2315 log_error ("accept failed for ssh: %s\n", strerror (errno));
2317 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2319 log_error ("error allocating connection control data: %s\n",
2321 assuan_sock_close (fd);
2323 else if ( !(ctrl->session_env = session_env_new ()) )
2325 log_error ("error allocating session environment block: %s\n",
2328 assuan_sock_close (fd);
2332 char threadname[50];
2334 agent_init_default_ctrl (ctrl);
2335 snprintf (threadname, sizeof threadname-1,
2336 "conn fd=%d (ssh)", FD2INT(fd));
2337 threadname[sizeof threadname -1] = 0;
2338 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2339 ctrl->thread_startup.fd = fd;
2340 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2342 log_error ("error spawning ssh connection handler: %s\n",
2344 assuan_sock_close (fd);
2348 fd = GNUPG_INVALID_FD;
2352 pth_event_free (ev, PTH_FREE_ALL);
2354 pth_event_free (time_ev, PTH_FREE_ALL);
2356 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2361 /* Helper for check_own_socket. */
2363 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2365 membuf_t *mb = opaque;
2366 put_membuf (mb, buffer, length);
2371 /* The thread running the actual check. We need to run this in a
2372 separate thread so that check_own_thread can be called from the
2375 check_own_socket_thread (void *arg)
2378 char *sockname = arg;
2379 assuan_context_t ctx = NULL;
2383 check_own_socket_running++;
2385 rc = assuan_new (&ctx);
2388 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2392 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2395 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2399 init_membuf (&mb, 100);
2400 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2401 NULL, NULL, NULL, NULL);
2402 put_membuf (&mb, "", 1);
2403 buffer = get_membuf (&mb, NULL);
2406 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2407 "GETINFO pid", gpg_strerror (rc));
2410 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2412 log_error ("socket is now serviced by another server\n");
2415 else if (opt.verbose > 1)
2416 log_error ("socket is still served by this server\n");
2423 assuan_release (ctx);
2426 /* We may not remove the socket as it is now in use by another
2427 server. Setting the name to empty does this. */
2430 if (socket_name_ssh)
2431 *socket_name_ssh = 0;
2432 shutdown_pending = 2;
2433 log_info ("this process is useless - shutting down\n");
2435 check_own_socket_running--;
2440 /* Check whether we are still listening on our own socket. In case
2441 another gpg-agent process started after us has taken ownership of
2442 our socket, we woul linger around without any real taks. Thus we
2443 better check once in a while whether we are really needed. */
2445 check_own_socket (void)
2450 if (!opt.use_standard_socket)
2451 return; /* This check makes only sense in standard socket mode. */
2453 if (check_own_socket_running || shutdown_pending)
2454 return; /* Still running or already shutting down. */
2456 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2458 return; /* Out of memory. */
2460 tattr = pth_attr_new();
2461 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2462 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2463 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2465 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2466 log_error ("error spawning check_own_socket_thread: %s\n",
2468 pth_attr_destroy (tattr);
2473 /* Figure out whether an agent is available and running. Prints an
2474 error if not. If SILENT is true, no messages are printed. Usually
2475 started with MODE 0. Returns 0 if the agent is running. */
2477 check_for_running_agent (int silent, int mode)
2481 assuan_context_t ctx = NULL;
2486 infostr = getenv ("GPG_AGENT_INFO");
2487 if (!infostr || !*infostr)
2489 if (!check_for_running_agent (silent, 1))
2490 return 0; /* Okay, its running on the standard socket. */
2492 log_error (_("no gpg-agent running in this session\n"));
2496 infostr = xstrdup (infostr);
2497 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2500 if (!check_for_running_agent (silent, 1))
2501 return 0; /* Okay, its running on the standard socket. */
2503 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2509 while (*p && *p != PATHSEP_C)
2511 prot = *p? atoi (p+1) : 0;
2516 log_error (_("gpg-agent protocol version %d is not supported\n"),
2518 if (!check_for_running_agent (silent, 1))
2519 return 0; /* Okay, its running on the standard socket. */
2523 else /* MODE != 0 */
2525 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2529 rc = assuan_new (&ctx);
2531 rc = assuan_socket_connect (ctx, infostr, pid, 0);
2535 if (!mode && !check_for_running_agent (silent, 1))
2536 return 0; /* Okay, its running on the standard socket. */
2538 if (!mode && !silent)
2539 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2542 assuan_release (ctx);
2546 if (!opt.quiet && !silent)
2547 log_info ("gpg-agent running and available\n");
2549 assuan_release (ctx);