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.
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 #ifndef HAVE_W32_SYSTEM
34 # include <sys/socket.h>
36 #endif /*!HAVE_W32_SYSTEM*/
41 #define JNLIB_NEED_LOG_LOGV
42 #define JNLIB_NEED_AFLOCAL
44 #include <assuan.h> /* Malloc hooks and socket wrappers. */
47 #include "mkdtemp.h" /* Gnulib replacement. */
50 #include "gc-opt-flags.h"
52 #include "../common/estream.h"
54 enum cmd_and_opt_values
93 oEnforcePassphraseConstraints,
95 oMinPassphraseNonalpha,
96 oCheckPassphrasePattern,
98 oEnablePassphraseHistory,
100 oNoUseStandardSocket,
103 oIgnoreCacheForSigning,
105 oAllowPresetPassphrase,
115 static ARGPARSE_OPTS opts[] = {
117 { aGPGConfList, "gpgconf-list", 256, "@" },
118 { aGPGConfTest, "gpgconf-test", 256, "@" },
119 { aUseStandardSocketP, "use-standard-socket-p", 256, "@" },
121 { 301, NULL, 0, N_("@Options:\n ") },
123 { oServer, "server", 0, N_("run in server mode (foreground)") },
124 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
125 { oVerbose, "verbose", 0, N_("verbose") },
126 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
127 { oSh, "sh", 0, N_("sh-style command output") },
128 { oCsh, "csh", 0, N_("csh-style command output") },
129 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
130 { oDebug, "debug" ,4|16, "@"},
131 { oDebugAll, "debug-all" ,0, "@"},
132 { oDebugLevel, "debug-level" ,2, "@"},
133 { oDebugWait,"debug-wait",1, "@"},
134 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
135 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
136 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
137 { oUseStandardSocket, "use-standard-socket", 0,
138 N_("use a standard location for the socket")},
139 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
140 { oPinentryProgram, "pinentry-program", 2 ,
141 N_("|PGM|use PGM as the PIN-Entry program") },
142 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
143 { oScdaemonProgram, "scdaemon-program", 2 ,
144 N_("|PGM|use PGM as the SCdaemon program") },
145 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
146 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
148 { oBatch, "batch", 0, "@" },
149 { oHomedir, "homedir", 2, "@"},
151 { oDisplay, "display", 2, "@" },
152 { oTTYname, "ttyname", 2, "@" },
153 { oTTYtype, "ttytype", 2, "@" },
154 { oLCctype, "lc-ctype", 2, "@" },
155 { oLCmessages, "lc-messages", 2, "@" },
156 { oXauthority, "xauthority", 2, "@" },
157 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
158 { oKeepDISPLAY, "keep-display",
159 0, N_("ignore requests to change the X display")},
161 { oDefCacheTTL, "default-cache-ttl", 4,
162 N_("|N|expire cached PINs after N seconds")},
163 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
164 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
165 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
167 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
168 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
169 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
170 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
171 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
172 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
174 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
175 N_("do not use the PIN cache when signing")},
176 { oAllowMarkTrusted, "allow-mark-trusted", 0,
177 N_("allow clients to mark keys as \"trusted\"")},
178 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
179 N_("allow presetting passphrase")},
180 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
181 { oWriteEnvFile, "write-env-file", 2|8,
182 N_("|FILE|write environment settings also to FILE")},
187 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
188 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
189 #define MAX_CACHE_TTL (120*60) /* 2 hours */
190 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
191 #define MIN_PASSPHRASE_LEN (8)
192 #define MIN_PASSPHRASE_NONALPHA (1)
193 #define MAX_PASSPHRASE_DAYS (0)
195 /* The timer tick used for housekeeping stuff. For Windows we use a
196 longer period as the SetWaitableTimer seems to signal earlier than
198 #ifdef HAVE_W32_SYSTEM
199 #define TIMERTICK_INTERVAL (4)
201 #define TIMERTICK_INTERVAL (2) /* Seconds. */
205 /* The list of open file descriptors at startup. Note that this list
206 has been allocated using the standard malloc. */
207 static int *startup_fd_list;
209 /* The signal mask at startup and a flag telling whether it is valid. */
210 #ifdef HAVE_SIGPROCMASK
211 static sigset_t startup_signal_mask;
212 static int startup_signal_mask_valid;
215 /* Flag to indicate that a shutdown was requested. */
216 static int shutdown_pending;
218 /* Counter for the currently running own socket checks. */
219 static int check_own_socket_running;
221 /* It is possible that we are currently running under setuid permissions */
222 static int maybe_setuid = 1;
224 /* Name of the communication socket used for native gpg-agent requests. */
225 static char *socket_name;
227 /* Name of the communication socket used for ssh-agent-emulation. */
228 static char *socket_name_ssh;
230 /* We need to keep track of the server's nonces (these are dummies for
232 static assuan_sock_nonce_t socket_nonce;
233 static assuan_sock_nonce_t socket_nonce_ssh;
236 /* Default values for options passed to the pinentry. */
237 static char *default_display;
238 static char *default_ttyname;
239 static char *default_ttytype;
240 static char *default_lc_ctype;
241 static char *default_lc_messages;
242 static char *default_xauthority;
244 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
245 static char *config_filename;
247 /* Helper to implement --debug-level */
248 static const char *debug_level;
250 /* Keep track of the current log file so that we can avoid updating
251 the log file after a SIGHUP if it didn't changed. Malloced. */
252 static char *current_logfile;
254 /* The handle_tick() function may test whether a parent is still
255 running. We record the PID of the parent here or -1 if it should be
257 static pid_t parent_pid = (pid_t)(-1);
264 static char *create_socket_name (char *standard_name, char *template);
265 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
266 assuan_sock_nonce_t *nonce);
267 static void create_directories (void);
269 static void agent_init_default_ctrl (ctrl_t ctrl);
270 static void agent_deinit_default_ctrl (ctrl_t ctrl);
272 static void handle_connections (gnupg_fd_t listen_fd,
273 gnupg_fd_t listen_fd_ssh);
274 static void check_own_socket (void);
275 static int check_for_running_agent (int silent, int mode);
277 /* Pth wrapper function definitions. */
278 ASSUAN_SYSTEM_PTH_IMPL;
280 GCRY_THREAD_OPTION_PTH_IMPL;
281 static int fixed_gcry_pth_init (void)
283 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
287 #ifndef PTH_HAVE_PTH_THREAD_ID
288 static unsigned long pth_thread_id (void)
290 return (unsigned long)pth_self ();
301 make_libversion (const char *libname, const char *(*getfnc)(const char*))
308 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
312 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
313 strcpy (stpcpy (stpcpy (result, libname), " "), s);
319 my_strusage (int level)
321 static char *ver_gcry;
326 case 11: p = "gpg-agent (GnuPG)";
328 case 13: p = VERSION; break;
329 case 17: p = PRINTABLE_OS_NAME; break;
330 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
331 reporting address. This is so that we can change the
332 reporting address without breaking the translations. */
333 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
337 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
342 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
344 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
345 "Secret key management for GnuPG\n");
355 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
356 only the active debug flags are propagated to the subsystems. With
357 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
358 all flags already set. Note that we don't fail here, because it is
359 important to keep gpg-agent running even after re-reading the
360 options due to a SIGHUP. */
364 int numok = (debug_level && digitp (debug_level));
365 int numlvl = numok? atoi (debug_level) : 0;
369 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
371 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
372 opt.debug = DBG_ASSUAN_VALUE;
373 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
374 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
375 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
376 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
378 else if (!strcmp (debug_level, "guru") || numok)
381 /* Unless the "guru" string has been used we don't want to allow
382 hashing debugging. The rationale is that people tend to
383 select the highest debug value and would then clutter their
384 disk with debug files which may reveal confidential data. */
386 opt.debug &= ~(DBG_HASHING_VALUE);
390 log_error (_("invalid debug-level `%s' given\n"), debug_level);
391 opt.debug = 0; /* Reset debugging, so that prior debug
392 statements won't have an undesired effect. */
395 if (opt.debug && !opt.verbose)
397 if (opt.debug && opt.quiet)
400 if (opt.debug & DBG_MPI_VALUE)
401 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
402 if (opt.debug & DBG_CRYPTO_VALUE )
403 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
404 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
407 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
408 (opt.debug & DBG_COMMAND_VALUE)? " command":"",
409 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
410 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
411 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
412 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
413 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
414 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
415 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
419 /* Helper for cleanup to remove one socket with NAME. */
421 remove_socket (char *name)
428 p = strrchr (name, '/');
442 remove_socket (socket_name);
443 remove_socket (socket_name_ssh);
448 /* Handle options which are allowed to be reset after program start.
449 Return true when the current option in PARGS could be handled and
450 false if not. As a special feature, passing a value of NULL for
451 PARGS, resets the options to the default. REREAD should be set
452 true if it is not the initial option parsing. */
454 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
462 opt.pinentry_program = NULL;
463 opt.pinentry_touch_file = NULL;
464 opt.scdaemon_program = NULL;
465 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
466 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
467 opt.max_cache_ttl = MAX_CACHE_TTL;
468 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
469 opt.enforce_passphrase_constraints = 0;
470 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
471 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
472 opt.check_passphrase_pattern = NULL;
473 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
474 opt.enable_passhrase_history = 0;
475 opt.ignore_cache_for_signing = 0;
476 opt.allow_mark_trusted = 0;
477 opt.disable_scdaemon = 0;
481 switch (pargs->r_opt)
483 case oQuiet: opt.quiet = 1; break;
484 case oVerbose: opt.verbose++; break;
486 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
487 case oDebugAll: opt.debug = ~0; break;
488 case oDebugLevel: debug_level = pargs->r.ret_str; break;
492 return 0; /* not handeld */
493 if (!current_logfile || !pargs->r.ret_str
494 || strcmp (current_logfile, pargs->r.ret_str))
496 log_set_file (pargs->r.ret_str);
498 assuan_set_assuan_log_stream (log_get_stream ());
499 xfree (current_logfile);
500 current_logfile = xtrystrdup (pargs->r.ret_str);
504 case oNoGrab: opt.no_grab = 1; break;
506 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
507 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
508 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
509 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
511 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
512 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
513 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
514 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
516 case oEnforcePassphraseConstraints:
517 opt.enforce_passphrase_constraints=1;
519 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
520 case oMinPassphraseNonalpha:
521 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
523 case oCheckPassphrasePattern:
524 opt.check_passphrase_pattern = pargs->r.ret_str;
526 case oMaxPassphraseDays:
527 opt.max_passphrase_days = pargs->r.ret_ulong;
529 case oEnablePassphraseHistory:
530 opt.enable_passhrase_history = 1;
533 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
535 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
537 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
540 return 0; /* not handled */
543 return 1; /* handled */
547 /* The main entry point. */
549 main (int argc, char **argv )
554 FILE *configfp = NULL;
555 char *configname = NULL;
557 unsigned configlineno;
559 int default_config =1;
566 char *logfile = NULL;
568 int gpgconf_list = 0;
570 const char *env_file_name = NULL;
571 struct assuan_malloc_hooks malloc_hooks;
573 /* Before we do anything else we save the list of currently open
574 file descriptors and the signal mask. This info is required to
575 do the exec call properly. */
576 startup_fd_list = get_all_open_fds ();
577 #ifdef HAVE_SIGPROCMASK
578 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
579 startup_signal_mask_valid = 1;
580 #endif /*HAVE_SIGPROCMASK*/
582 /* Set program name etc. */
583 set_strusage (my_strusage);
584 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
585 /* Please note that we may running SUID(ROOT), so be very CAREFUL
586 when adding any stuff between here and the call to INIT_SECMEM()
587 somewhere after the option parsing */
588 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
590 /* Make sure that our subsystems are ready. */
592 init_common_subsystems ();
595 /* Libgcrypt requires us to register the threading model first.
596 Note that this will also do the pth_init. */
597 gcry_threads_pth.init = fixed_gcry_pth_init;
598 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
601 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
606 /* Check that the libraries are suitable. Do it here because
607 the option parsing may need services of the library. */
608 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
610 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
611 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
614 malloc_hooks.malloc = gcry_malloc;
615 malloc_hooks.realloc = gcry_realloc;
616 malloc_hooks.free = gcry_free;
617 assuan_set_malloc_hooks (&malloc_hooks);
618 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
619 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
620 assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
623 setup_libgcrypt_logging ();
624 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
626 disable_core_dumps ();
628 /* Set default options. */
629 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
630 #ifdef USE_STANDARD_SOCKET
631 opt.use_standard_socket = 1; /* Under Windows we always use a standard
635 shell = getenv ("SHELL");
636 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
639 opt.homedir = default_homedir ();
641 /* Record some of the original environment strings. */
645 static const char *names[] =
646 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
649 opt.startup_env = session_env_new ();
650 if (!opt.startup_env)
651 err = gpg_error_from_syserror ();
652 for (idx=0; !err && names[idx]; idx++)
654 s = getenv (names[idx]);
656 err = session_env_setenv (opt.startup_env, names[idx], s);
662 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
665 log_fatal ("error recording startup environment: %s\n",
668 /* Fixme: Better use the locale function here. */
669 opt.startup_lc_ctype = getenv ("LC_CTYPE");
670 if (opt.startup_lc_ctype)
671 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
672 opt.startup_lc_messages = getenv ("LC_MESSAGES");
673 if (opt.startup_lc_messages)
674 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
677 /* Check whether we have a config file on the commandline */
682 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
683 while (arg_parse( &pargs, opts))
685 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
687 else if (pargs.r_opt == oOptions)
688 { /* yes there is one, so we do not try the default one, but
689 read the option file when it is encountered at the
693 else if (pargs.r_opt == oNoOptions)
694 default_config = 0; /* --no-options */
695 else if (pargs.r_opt == oHomedir)
696 opt.homedir = pargs.r.ret_str;
699 /* Initialize the secure memory. */
700 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
704 Now we are now working under our real uid
708 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
714 pargs.flags= 1; /* do not remove the args */
719 configfp = fopen (configname, "r");
725 log_info (_("NOTE: no default option file `%s'\n"),
727 /* Save the default conf file name so that
728 reread_configuration is able to test whether the
729 config file has been created in the meantime. */
730 xfree (config_filename);
731 config_filename = configname;
736 log_error (_("option file `%s': %s\n"),
737 configname, strerror(errno) );
743 if (parse_debug && configname )
744 log_info (_("reading options from `%s'\n"), configname );
748 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
750 if (parse_rereadable_options (&pargs, 0))
751 continue; /* Already handled */
754 case aGPGConfList: gpgconf_list = 1; break;
755 case aGPGConfTest: gpgconf_list = 2; break;
756 case aUseStandardSocketP: gpgconf_list = 3; break;
757 case oBatch: opt.batch=1; break;
759 case oDebugWait: debug_wait = pargs.r.ret_int; break;
762 /* config files may not be nested (silently ignore them) */
766 configname = xstrdup(pargs.r.ret_str);
770 case oNoGreeting: nogreeting = 1; break;
771 case oNoVerbose: opt.verbose = 0; break;
772 case oNoOptions: break; /* no-options */
773 case oHomedir: opt.homedir = pargs.r.ret_str; break;
774 case oNoDetach: nodetach = 1; break;
775 case oLogFile: logfile = pargs.r.ret_str; break;
776 case oCsh: csh_style = 1; break;
777 case oSh: csh_style = 0; break;
778 case oServer: pipe_server = 1; break;
779 case oDaemon: is_daemon = 1; break;
781 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
782 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
783 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
784 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
785 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
786 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
789 case oUseStandardSocket: opt.use_standard_socket = 1; break;
790 case oNoUseStandardSocket: opt.use_standard_socket = 0; break;
792 case oFakedSystemTime:
794 time_t faked_time = isotime2epoch (pargs.r.ret_str);
795 if (faked_time == (time_t)(-1))
796 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
797 gnupg_set_time (faked_time, 0);
801 case oKeepTTY: opt.keep_tty = 1; break;
802 case oKeepDISPLAY: opt.keep_display = 1; break;
804 case oSSHSupport: opt.ssh_support = 1; break;
807 env_file_name = pargs.r.ret_str;
809 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
812 default : pargs.err = configfp? 1:2; break;
819 /* Keep a copy of the name so that it can be read on SIGHUP. */
820 if (config_filename != configname)
822 xfree (config_filename);
823 config_filename = configname;
831 if (log_get_errorcount(0))
838 fprintf (stderr, "%s %s; %s\n",
839 strusage(11), strusage(13), strusage(14) );
840 fprintf (stderr, "%s\n", strusage(15) );
842 #ifdef IS_DEVELOPMENT_VERSION
843 /* We don't want to print it here because gpg-agent is useful of its
844 own and quite matured. */
845 /*log_info ("NOTE: this is a development version!\n");*/
850 if (atexit (cleanup))
852 log_error ("atexit failed\n");
857 initialize_module_call_pinentry ();
858 initialize_module_call_scd ();
859 initialize_module_trustlist ();
861 /* Try to create missing directories. */
862 create_directories ();
864 if (debug_wait && pipe_server)
866 log_debug ("waiting for debugger - my pid is %u .....\n",
867 (unsigned int)getpid());
868 gnupg_sleep (debug_wait);
869 log_debug ("... okay\n");
872 if (gpgconf_list == 3)
873 agent_exit (!opt.use_standard_socket);
874 if (gpgconf_list == 2)
881 /* List options and default values in the GPG Conf format. */
882 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
883 filename_esc = percent_escape (filename, NULL);
885 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
886 GC_OPT_FLAG_DEFAULT, filename_esc);
888 xfree (filename_esc);
890 printf ("verbose:%lu:\n"
892 "debug-level:%lu:\"none:\n"
894 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
895 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
896 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
897 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
898 printf ("default-cache-ttl:%lu:%d:\n",
899 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
900 printf ("default-cache-ttl-ssh:%lu:%d:\n",
901 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
902 printf ("max-cache-ttl:%lu:%d:\n",
903 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
904 printf ("max-cache-ttl-ssh:%lu:%d:\n",
905 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
906 printf ("enforce-passphrase-constraints:%lu:\n",
907 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
908 printf ("min-passphrase-len:%lu:%d:\n",
909 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
910 printf ("min-passphrase-nonalpha:%lu:%d:\n",
911 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
912 MIN_PASSPHRASE_NONALPHA);
913 printf ("check-passphrase-pattern:%lu:\n",
914 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
915 printf ("max-passphrase-days:%lu:%d:\n",
916 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
917 MAX_PASSPHRASE_DAYS);
918 printf ("enable-passphrase-history:%lu:\n",
919 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
920 printf ("no-grab:%lu:\n",
921 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
922 printf ("ignore-cache-for-signing:%lu:\n",
923 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
924 printf ("allow-mark-trusted:%lu:\n",
925 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
926 printf ("disable-scdaemon:%lu:\n",
927 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
932 /* If this has been called without any options, we merely check
933 whether an agent is already running. We do this here so that we
934 don't clobber a logfile but print it directly to stderr. */
935 if (!pipe_server && !is_daemon)
937 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
938 check_for_running_agent (0, 0);
943 /* gpg-agent usually does not output any messages because it runs in
944 the background. For log files it is acceptable to have messages
945 always encoded in utf-8. We switch here to utf-8, so that
946 commands like --help still give native messages. It is far
947 easier to switch only once instead of for every message and it
948 actually helps when more then one thread is active (avoids an
950 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
953 /* Now start with logging to a file if this is desired. */
956 log_set_file (logfile);
957 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
959 |JNLIB_LOG_WITH_PID));
960 current_logfile = xstrdup (logfile);
963 assuan_set_assuan_log_stream (log_get_stream ());
965 /* Make sure that we have a default ttyname. */
966 if (!default_ttyname && ttyname (1))
967 default_ttyname = xstrdup (ttyname (1));
968 if (!default_ttytype && getenv ("TERM"))
969 default_ttytype = xstrdup (getenv ("TERM"));
974 /* This is the simple pipe based server */
977 ctrl = xtrycalloc (1, sizeof *ctrl);
980 log_error ("error allocating connection control data: %s\n",
984 ctrl->session_env = session_env_new ();
985 if (!ctrl->session_env)
987 log_error ("error allocating session environment block: %s\n",
992 agent_init_default_ctrl (ctrl);
993 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
994 agent_deinit_default_ctrl (ctrl);
1000 { /* Regular server mode */
1005 /* Remove the DISPLAY variable so that a pinentry does not
1006 default to a specific display. There is still a default
1007 display when gpg-agent was started using --display or a
1008 client requested this using an OPTION command. Note, that we
1009 don't do this when running in reverse daemon mode (i.e. when
1010 exec the program given as arguments). */
1011 #ifndef HAVE_W32_SYSTEM
1012 if (!opt.keep_display && !argc)
1013 unsetenv ("DISPLAY");
1017 /* Create the sockets. */
1018 socket_name = create_socket_name
1019 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
1020 if (opt.ssh_support)
1021 socket_name_ssh = create_socket_name
1022 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
1024 fd = create_server_socket (socket_name, 0, &socket_nonce);
1025 if (opt.ssh_support)
1026 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
1028 fd_ssh = GNUPG_INVALID_FD;
1030 /* If we are going to exec a program in the parent, we record
1031 the PID, so that the child may check whether the program is
1034 parent_pid = getpid ();
1037 #ifdef HAVE_W32_SYSTEM
1039 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
1040 #else /*!HAVE_W32_SYSTEM*/
1042 if (pid == (pid_t)-1)
1044 log_fatal ("fork failed: %s\n", strerror (errno) );
1048 { /* We are the parent */
1049 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
1051 /* Close the socket FD. */
1054 /* Note that we used a standard fork so that Pth runs in
1055 both the parent and the child. The pth_fork would
1056 terminate Pth in the child but that is not the way we
1057 want it. Thus we use a plain fork and terminate Pth here
1058 in the parent. The pth_kill may or may not work reliable
1059 but it should not harm to call it. Because Pth fiddles
1060 with the signal mask the signal mask might not be correct
1061 right now and thus we restore it. That is not strictly
1062 necessary but some programs falsely assume a cleared
1063 signal mask. es_pth_kill is a wrapper around pth_kill to
1064 take care not to use any Pth functions in the estream
1065 code after Pth has been killed. */
1066 if ( !es_pth_kill () )
1067 log_error ("pth_kill failed in forked process\n");
1069 #ifdef HAVE_SIGPROCMASK
1070 if (startup_signal_mask_valid)
1072 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1073 log_error ("error restoring signal mask: %s\n",
1077 log_info ("no saved signal mask\n");
1078 #endif /*HAVE_SIGPROCMASK*/
1080 /* Create the info string: <name>:<pid>:<protocol_version> */
1081 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1082 socket_name, (ulong)pid ) < 0)
1084 log_error ("out of core\n");
1085 kill (pid, SIGTERM);
1088 if (opt.ssh_support)
1090 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1091 socket_name_ssh) < 0)
1093 log_error ("out of core\n");
1094 kill (pid, SIGTERM);
1097 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1100 log_error ("out of core\n");
1101 kill (pid, SIGTERM);
1106 *socket_name = 0; /* Don't let cleanup() remove the socket -
1107 the child should do this from now on */
1108 if (opt.ssh_support)
1109 *socket_name_ssh = 0;
1115 fp = fopen (env_file_name, "w");
1117 log_error (_("error creating `%s': %s\n"),
1118 env_file_name, strerror (errno));
1121 fputs (infostr, fp);
1123 if (opt.ssh_support)
1125 fputs (infostr_ssh_sock, fp);
1127 fputs (infostr_ssh_pid, fp);
1136 { /* Run the program given on the commandline. */
1137 if (putenv (infostr))
1139 log_error ("failed to set environment: %s\n",
1141 kill (pid, SIGTERM );
1144 if (opt.ssh_support && putenv (infostr_ssh_sock))
1146 log_error ("failed to set environment: %s\n",
1148 kill (pid, SIGTERM );
1151 if (opt.ssh_support && putenv (infostr_ssh_pid))
1153 log_error ("failed to set environment: %s\n",
1155 kill (pid, SIGTERM );
1159 /* Close all the file descriptors except the standard
1160 ones and those open at startup. We explicitly don't
1161 close 0,1,2 in case something went wrong collecting
1163 close_all_fds (3, startup_fd_list);
1165 /* Run the command. */
1166 execvp (argv[0], argv);
1167 log_error ("failed to run the command: %s\n", strerror (errno));
1168 kill (pid, SIGTERM);
1173 /* Print the environment string, so that the caller can use
1174 shell's eval to set it */
1177 *strchr (infostr, '=') = ' ';
1178 printf ("setenv %s;\n", infostr);
1179 if (opt.ssh_support)
1181 *strchr (infostr_ssh_sock, '=') = ' ';
1182 printf ("setenv %s;\n", infostr_ssh_sock);
1183 *strchr (infostr_ssh_pid, '=') = ' ';
1184 printf ("setenv %s;\n", infostr_ssh_pid);
1189 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1190 if (opt.ssh_support)
1192 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1193 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1197 if (opt.ssh_support)
1199 xfree (infostr_ssh_sock);
1200 xfree (infostr_ssh_pid);
1211 /* Detach from tty and put process into a new session */
1215 unsigned int oldflags;
1217 /* Close stdin, stdout and stderr unless it is the log stream */
1218 for (i=0; i <= 2; i++)
1220 if (!log_test_fd (i) && i != fd )
1223 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1225 log_error ("failed to open `%s': %s\n",
1226 "/dev/null", strerror (errno));
1234 log_error ("setsid() failed: %s\n", strerror(errno) );
1239 log_get_prefix (&oldflags);
1240 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1241 opt.running_detached = 1;
1246 log_error ("chdir to / failed: %s\n", strerror (errno));
1251 struct sigaction sa;
1253 sa.sa_handler = SIG_IGN;
1254 sigemptyset (&sa.sa_mask);
1256 sigaction (SIGPIPE, &sa, NULL);
1258 #endif /*!HAVE_W32_SYSTEM*/
1260 log_info ("%s %s started\n", strusage(11), strusage(13) );
1261 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1262 assuan_sock_close (fd);
1272 /*FIXME: update_random_seed_file();*/
1274 /* at this time a bit annoying */
1275 if (opt.debug & DBG_MEMSTAT_VALUE)
1277 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1278 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1281 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1283 gcry_control (GCRYCTL_TERM_SECMEM );
1284 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1290 agent_init_default_ctrl (ctrl_t ctrl)
1292 /* Note we ignore malloc errors because we can't do much about it
1293 and the request will fail anyway shortly after this
1295 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1296 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1297 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1298 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1299 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1302 xfree (ctrl->lc_ctype);
1303 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1305 if (ctrl->lc_messages)
1306 xfree (ctrl->lc_messages);
1307 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1314 agent_deinit_default_ctrl (ctrl_t ctrl)
1316 session_env_release (ctrl->session_env);
1319 xfree (ctrl->lc_ctype);
1320 if (ctrl->lc_messages)
1321 xfree (ctrl->lc_messages);
1325 /* Reread parts of the configuration. Note, that this function is
1326 obviously not thread-safe and should only be called from the PTH
1329 Fixme: Due to the way the argument parsing works, we create a
1330 memory leak here for all string type arguments. There is currently
1331 no clean way to tell whether the memory for the argument has been
1332 allocated or points into the process' original arguments. Unless
1333 we have a mechanism to tell this, we need to live on with this. */
1335 reread_configuration (void)
1337 ARGPARSE_ARGS pargs;
1339 unsigned int configlineno = 0;
1342 if (!config_filename)
1343 return; /* No config file. */
1345 fp = fopen (config_filename, "r");
1348 log_info (_("option file `%s': %s\n"),
1349 config_filename, strerror(errno) );
1353 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1355 memset (&pargs, 0, sizeof pargs);
1357 pargs.argc = &dummy;
1358 pargs.flags = 1; /* do not remove the args */
1359 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1361 if (pargs.r_opt < -1)
1362 pargs.err = 1; /* Print a warning. */
1363 else /* Try to parse this option - ignore unchangeable ones. */
1364 parse_rereadable_options (&pargs, 1);
1371 /* Return the file name of the socket we are using for native
1374 get_agent_socket_name (void)
1376 const char *s = socket_name;
1378 return (s && *s)? s : NULL;
1381 /* Return the file name of the socket we are using for SSH
1384 get_agent_ssh_socket_name (void)
1386 const char *s = socket_name_ssh;
1388 return (s && *s)? s : NULL;
1392 /* Under W32, this function returns the handle of the scdaemon
1393 notification event. Calling it the first time creates that
1395 #ifdef HAVE_W32_SYSTEM
1397 get_agent_scd_notify_event (void)
1399 static HANDLE the_event;
1404 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1406 /* We need to use manual reset evet object due to the way our
1407 w32-pth wait function works: If we would use an automatic
1408 reset event we are not able to figure out which handle has
1409 been signaled because at the time we single out the signaled
1410 handles using WFSO the event has already been reset due to
1412 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1414 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1415 else if (!DuplicateHandle (GetCurrentProcess(), h,
1416 GetCurrentProcess(), &h2,
1417 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1419 log_error ("setting syncronize for scd notify event failed: %s\n",
1420 w32_strerror (-1) );
1430 log_debug ("returning notify handle %p\n", the_event);
1433 #endif /*HAVE_W32_SYSTEM*/
1437 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1438 true using STANDARD_NAME in the home directory or if given as
1439 false from the mkdir type name TEMPLATE. In the latter case a
1440 unique name in a unique new directory will be created. In both
1441 cases check for valid characters as well as against a maximum
1442 allowed length for a unix domain socket is done. The function
1443 terminates the process in case of an error. Returns: Pointer to an
1444 allocated string with the absolute name of the socket used. */
1446 create_socket_name (char *standard_name, char *template)
1450 if (opt.use_standard_socket)
1451 name = make_filename (opt.homedir, standard_name, NULL);
1454 name = xstrdup (template);
1455 p = strrchr (name, '/');
1459 if (!mkdtemp (name))
1461 log_error (_("can't create directory `%s': %s\n"),
1462 name, strerror (errno));
1468 if (strchr (name, PATHSEP_C))
1470 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1473 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1475 log_error (_("name of socket too long\n"));
1483 /* Create a Unix domain socket with NAME. Returns the file descriptor
1484 or terminates the process in case of an error. Not that this
1485 function needs to be used for the regular socket first and only
1486 then for the ssh socket. */
1488 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1490 struct sockaddr_un *serv_addr;
1495 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1496 if (fd == ASSUAN_INVALID_FD)
1498 log_error (_("can't create socket: %s\n"), strerror (errno));
1502 serv_addr = xmalloc (sizeof (*serv_addr));
1503 memset (serv_addr, 0, sizeof *serv_addr);
1504 serv_addr->sun_family = AF_UNIX;
1505 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1507 log_error (_("socket name `%s' is too long\n"), name);
1510 strcpy (serv_addr->sun_path, name);
1511 len = SUN_LEN (serv_addr);
1512 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1513 if (opt.use_standard_socket && rc == -1 && errno == EADDRINUSE)
1515 /* Check whether a gpg-agent is already running on the standard
1516 socket. We do this test only if this is not the ssh socket.
1517 For ssh we assume that a test for gpg-agent has already been
1518 done and reuse the requested ssh socket. Testing the
1519 ssh-socket is not possible because at this point, though we
1520 know the new Assuan socket, the Assuan server and thus the
1521 ssh-agent server is not yet operational. This would lead to
1523 if (!is_ssh && !check_for_running_agent (1, 1))
1525 log_error (_("a gpg-agent is already running - "
1526 "not starting a new one\n"));
1527 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1528 assuan_sock_close (fd);
1532 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1535 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1536 log_error (_("error getting nonce for the socket\n"));
1539 /* We use gpg_strerror here because it allows us to get strings
1540 for some W32 socket error codes. */
1541 log_error (_("error binding socket to `%s': %s\n"),
1542 serv_addr->sun_path,
1543 gpg_strerror (gpg_error_from_errno (errno)));
1545 assuan_sock_close (fd);
1546 if (opt.use_standard_socket)
1547 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1551 if (listen (FD2INT(fd), 5 ) == -1)
1553 log_error (_("listen() failed: %s\n"), strerror (errno));
1554 assuan_sock_close (fd);
1559 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1565 /* Check that the directory for storing the private keys exists and
1566 create it if not. This function won't fail as it is only a
1567 convenience function and not strictly necessary. */
1569 create_private_keys_directory (const char *home)
1572 struct stat statbuf;
1574 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1575 if (stat (fname, &statbuf) && errno == ENOENT)
1577 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1578 if (!CreateDirectory (fname, NULL))
1579 log_error (_("can't create directory `%s': %s\n"),
1580 fname, w32_strerror (-1) );
1582 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1583 log_error (_("can't create directory `%s': %s\n"),
1584 fname, strerror (errno) );
1586 else if (!opt.quiet)
1587 log_info (_("directory `%s' created\n"), fname);
1592 /* Create the directory only if the supplied directory name is the
1593 same as the default one. This way we avoid to create arbitrary
1594 directories when a non-default home directory is used. To cope
1595 with HOME, we compare only the suffix if we see that the default
1596 homedir does start with a tilde. We don't stop here in case of
1597 problems because other functions will throw an error anyway.*/
1599 create_directories (void)
1601 struct stat statbuf;
1602 const char *defhome = standard_homedir ();
1605 home = make_filename (opt.homedir, NULL);
1606 if ( stat (home, &statbuf) )
1608 if (errno == ENOENT)
1611 #ifdef HAVE_W32_SYSTEM
1612 ( !compare_filenames (home, defhome) )
1615 && (strlen (home) >= strlen (defhome+1)
1616 && !strcmp (home + strlen(home)
1617 - strlen (defhome+1), defhome+1)))
1618 || (*defhome != '~' && !strcmp (home, defhome) )
1622 #ifdef HAVE_W32_SYSTEM
1623 if (!CreateDirectory (home, NULL))
1624 log_error (_("can't create directory `%s': %s\n"),
1625 home, w32_strerror (-1) );
1627 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1628 log_error (_("can't create directory `%s': %s\n"),
1629 home, strerror (errno) );
1634 log_info (_("directory `%s' created\n"), home);
1635 create_private_keys_directory (home);
1640 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1642 else if ( !S_ISDIR(statbuf.st_mode))
1644 log_error (_("can't use `%s' as home directory\n"), home);
1646 else /* exists and is a directory. */
1648 create_private_keys_directory (home);
1655 /* This is the worker for the ticker. It is called every few seconds
1656 and may only do fast operations. */
1660 static time_t last_minute;
1663 last_minute = time (NULL);
1665 /* Check whether the scdaemon has died and cleanup in this case. */
1666 agent_scd_check_aliveness ();
1668 /* If we are running as a child of another process, check whether
1669 the parent is still alive and shutdown if not. */
1670 #ifndef HAVE_W32_SYSTEM
1671 if (parent_pid != (pid_t)(-1))
1673 if (kill (parent_pid, 0))
1675 shutdown_pending = 2;
1678 log_info ("parent process died - shutting down\n");
1679 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1685 #endif /*HAVE_W32_SYSTEM*/
1687 /* Code to be run every minute. */
1688 if (last_minute + 60 <= time (NULL))
1690 check_own_socket ();
1691 last_minute = time (NULL);
1697 /* A global function which allows us to call the reload stuff from
1698 other places too. This is only used when build for W32. */
1700 agent_sighup_action (void)
1702 log_info ("SIGHUP received - "
1703 "re-reading configuration and flushing cache\n");
1704 agent_flush_cache ();
1705 reread_configuration ();
1706 agent_reload_trustlist ();
1711 agent_sigusr2_action (void)
1714 log_info ("SIGUSR2 received - updating card event counter\n");
1715 /* Nothing to check right now. We only increment a counter. */
1716 bump_card_eventcounter ();
1721 handle_signal (int signo)
1725 #ifndef HAVE_W32_SYSTEM
1727 agent_sighup_action ();
1731 log_info ("SIGUSR1 received - printing internal information:\n");
1732 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1733 agent_query_dump_state ();
1734 agent_scd_dump_state ();
1738 agent_sigusr2_action ();
1742 if (!shutdown_pending)
1743 log_info ("SIGTERM received - shutting down ...\n");
1745 log_info ("SIGTERM received - still %ld running threads\n",
1746 pth_ctrl( PTH_CTRL_GETTHREADS ));
1748 if (shutdown_pending > 2)
1750 log_info ("shutdown forced\n");
1751 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1758 log_info ("SIGINT received - immediate shutdown\n");
1759 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1765 log_info ("signal %d received - no action defined\n", signo);
1770 /* Check the nonce on a new connection. This is a NOP unless we we
1771 are using our Unix domain socket emulation under Windows. */
1773 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1775 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1777 log_info (_("error reading nonce on fd %d: %s\n"),
1778 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1779 assuan_sock_close (ctrl->thread_startup.fd);
1788 /* This is the standard connection thread's main function. */
1790 start_connection_thread (void *arg)
1794 if (check_nonce (ctrl, &socket_nonce))
1797 agent_init_default_ctrl (ctrl);
1799 log_info (_("handler 0x%lx for fd %d started\n"),
1800 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1802 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1804 log_info (_("handler 0x%lx for fd %d terminated\n"),
1805 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1807 agent_deinit_default_ctrl (ctrl);
1813 /* This is the ssh connection thread's main function. */
1815 start_connection_thread_ssh (void *arg)
1819 if (check_nonce (ctrl, &socket_nonce_ssh))
1822 agent_init_default_ctrl (ctrl);
1824 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1825 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1827 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1829 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1830 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1832 agent_deinit_default_ctrl (ctrl);
1838 /* Connection handler loop. Wait for connection requests and spawn a
1839 thread after accepting a connection. */
1841 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1844 pth_event_t ev, time_ev;
1847 struct sockaddr_un paddr;
1849 fd_set fdset, read_fdset;
1854 tattr = pth_attr_new();
1855 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1856 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1858 #ifndef HAVE_W32_SYSTEM /* fixme */
1859 /* Make sure that the signals we are going to handle are not blocked
1860 and create an event object for them. We also set the default
1861 action to ignore because we use an Pth event to get notified
1862 about signals. This avoids that the default action is taken in
1863 case soemthing goes wrong within Pth. The problem might also be
1865 sigemptyset (&sigs );
1867 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1868 struct sigaction sa;
1871 for (i=0; i < DIM (mysigs); i++)
1873 sigemptyset (&sa.sa_mask);
1874 sa.sa_handler = SIG_IGN;
1876 sigaction (mysigs[i], &sa, NULL);
1878 sigaddset (&sigs, mysigs[i]);
1882 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1883 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1885 # ifdef PTH_EVENT_HANDLE
1887 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1890 /* Use a dummy event. */
1892 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1897 /* Set a flag to tell call-scd.c that it may enable event
1899 opt.sigusr2_enabled = 1;
1902 FD_SET (FD2INT (listen_fd), &fdset);
1903 nfd = FD2INT (listen_fd);
1904 if (listen_fd_ssh != GNUPG_INVALID_FD)
1906 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1907 if (FD2INT (listen_fd_ssh) > nfd)
1908 nfd = FD2INT (listen_fd_ssh);
1913 /* Make sure that our signals are not blocked. */
1914 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1916 /* Shutdown test. */
1917 if (shutdown_pending)
1919 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1922 /* Do not accept new connections but keep on running the
1923 loop to cope with the timer events. */
1927 /* Create a timeout event if needed. To help with power saving
1928 we syncronize the ticks to the next full second. */
1931 pth_time_t nexttick;
1933 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1934 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
1937 nexttick.tv_usec = 0;
1939 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1942 /* POSIX says that fd_set should be implemented as a structure,
1943 thus a simple assignment is fine to copy the entire set. */
1947 pth_event_concat (ev, time_ev, NULL);
1948 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1950 pth_event_isolate (time_ev);
1954 if (pth_event_occurred (ev)
1955 || (time_ev && pth_event_occurred (time_ev)))
1957 if (pth_event_occurred (ev))
1959 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1960 agent_sigusr2_action ();
1962 handle_signal (signo);
1965 if (time_ev && pth_event_occurred (time_ev))
1967 pth_event_free (time_ev, PTH_FREE_ALL);
1973 log_error (_("pth_select failed: %s - waiting 1s\n"),
1979 if (pth_event_occurred (ev))
1981 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1982 agent_sigusr2_action ();
1984 handle_signal (signo);
1988 if (time_ev && pth_event_occurred (time_ev))
1990 pth_event_free (time_ev, PTH_FREE_ALL);
1996 /* We now might create new threads and because we don't want any
1997 signals (as we are handling them here) to be delivered to a
1998 new thread. Thus we need to block those signals. */
1999 pth_sigmask (SIG_BLOCK, &sigs, NULL);
2001 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
2005 plen = sizeof paddr;
2006 fd = INT2FD (pth_accept (FD2INT(listen_fd),
2007 (struct sockaddr *)&paddr, &plen));
2008 if (fd == GNUPG_INVALID_FD)
2010 log_error ("accept failed: %s\n", strerror (errno));
2012 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2014 log_error ("error allocating connection control data: %s\n",
2016 assuan_sock_close (fd);
2018 else if ( !(ctrl->session_env = session_env_new ()) )
2020 log_error ("error allocating session environment block: %s\n",
2023 assuan_sock_close (fd);
2027 char threadname[50];
2029 snprintf (threadname, sizeof threadname-1,
2030 "conn fd=%d (gpg)", FD2INT(fd));
2031 threadname[sizeof threadname -1] = 0;
2032 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2033 ctrl->thread_startup.fd = fd;
2034 if (!pth_spawn (tattr, start_connection_thread, ctrl))
2036 log_error ("error spawning connection handler: %s\n",
2038 assuan_sock_close (fd);
2042 fd = GNUPG_INVALID_FD;
2045 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
2046 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
2050 plen = sizeof paddr;
2051 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
2052 (struct sockaddr *)&paddr, &plen));
2053 if (fd == GNUPG_INVALID_FD)
2055 log_error ("accept failed for ssh: %s\n", strerror (errno));
2057 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2059 log_error ("error allocating connection control data: %s\n",
2061 assuan_sock_close (fd);
2063 else if ( !(ctrl->session_env = session_env_new ()) )
2065 log_error ("error allocating session environment block: %s\n",
2068 assuan_sock_close (fd);
2072 char threadname[50];
2074 agent_init_default_ctrl (ctrl);
2075 snprintf (threadname, sizeof threadname-1,
2076 "conn fd=%d (ssh)", FD2INT(fd));
2077 threadname[sizeof threadname -1] = 0;
2078 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2079 ctrl->thread_startup.fd = fd;
2080 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2082 log_error ("error spawning ssh connection handler: %s\n",
2084 assuan_sock_close (fd);
2088 fd = GNUPG_INVALID_FD;
2092 pth_event_free (ev, PTH_FREE_ALL);
2094 pth_event_free (time_ev, PTH_FREE_ALL);
2096 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2101 /* Helper for check_own_socket. */
2103 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2105 membuf_t *mb = opaque;
2106 put_membuf (mb, buffer, length);
2111 /* The thread running the actual check. We need to run this in a
2112 separate thread so that check_own_thread can be called from the
2115 check_own_socket_thread (void *arg)
2118 char *sockname = arg;
2119 assuan_context_t ctx = NULL;
2123 check_own_socket_running++;
2125 rc = assuan_new (&ctx);
2128 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2132 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2135 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2139 init_membuf (&mb, 100);
2140 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2141 NULL, NULL, NULL, NULL);
2142 put_membuf (&mb, "", 1);
2143 buffer = get_membuf (&mb, NULL);
2146 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2147 "GETINFO pid", gpg_strerror (rc));
2150 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2152 log_error ("socket is now serviced by another server\n");
2155 else if (opt.verbose > 1)
2156 log_error ("socket is still served by this server\n");
2163 assuan_release (ctx);
2166 /* We may not remove the socket as it is now in use by another
2167 server. Setting the name to empty does this. */
2170 if (socket_name_ssh)
2171 *socket_name_ssh = 0;
2172 shutdown_pending = 2;
2173 log_info ("this process is useless - shutting down\n");
2175 check_own_socket_running--;
2180 /* Check whether we are still listening on our own socket. In case
2181 another gpg-agent process started after us has taken ownership of
2182 our socket, we woul linger around without any real taks. Thus we
2183 better check once in a while whether we are really needed. */
2185 check_own_socket (void)
2190 if (!opt.use_standard_socket)
2191 return; /* This check makes only sense in standard socket mode. */
2193 if (check_own_socket_running || shutdown_pending)
2194 return; /* Still running or already shutting down. */
2196 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2198 return; /* Out of memory. */
2200 tattr = pth_attr_new();
2201 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2202 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2203 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2205 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2206 log_error ("error spawning check_own_socket_thread: %s\n",
2208 pth_attr_destroy (tattr);
2213 /* Figure out whether an agent is available and running. Prints an
2214 error if not. If SILENT is true, no messages are printed. Usually
2215 started with MODE 0. Returns 0 if the agent is running. */
2217 check_for_running_agent (int silent, int mode)
2221 assuan_context_t ctx = NULL;
2226 infostr = getenv ("GPG_AGENT_INFO");
2227 if (!infostr || !*infostr)
2229 if (!check_for_running_agent (silent, 1))
2230 return 0; /* Okay, its running on the standard socket. */
2232 log_error (_("no gpg-agent running in this session\n"));
2236 infostr = xstrdup (infostr);
2237 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2240 if (!check_for_running_agent (silent, 1))
2241 return 0; /* Okay, its running on the standard socket. */
2243 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2249 while (*p && *p != PATHSEP_C)
2251 prot = *p? atoi (p+1) : 0;
2256 log_error (_("gpg-agent protocol version %d is not supported\n"),
2258 if (!check_for_running_agent (silent, 1))
2259 return 0; /* Okay, its running on the standard socket. */
2263 else /* MODE != 0 */
2265 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2269 rc = assuan_new (&ctx);
2271 rc = assuan_socket_connect (ctx, infostr, pid, 0);
2275 if (!mode && !check_for_running_agent (silent, 1))
2276 return 0; /* Okay, its running on the standard socket. */
2278 if (!mode && !silent)
2279 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2282 assuan_release (ctx);
2286 if (!opt.quiet && !silent)
2287 log_info ("gpg-agent running and available\n");
2289 assuan_release (ctx);