1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2009,
3 * 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*/
43 #define JNLIB_NEED_LOG_LOGV
44 #define JNLIB_NEED_AFLOCAL
46 #include <assuan.h> /* Malloc hooks and socket wrappers. */
49 #include "mkdtemp.h" /* Gnulib replacement. */
51 #include "gc-opt-flags.h"
55 enum cmd_and_opt_values
94 oEnforcePassphraseConstraints,
96 oMinPassphraseNonalpha,
97 oCheckPassphrasePattern,
99 oEnablePassphraseHistory,
101 oNoUseStandardSocket,
104 oIgnoreCacheForSigning,
106 oAllowPresetPassphrase,
116 static ARGPARSE_OPTS opts[] = {
118 { aGPGConfList, "gpgconf-list", 256, "@" },
119 { aGPGConfTest, "gpgconf-test", 256, "@" },
120 { aUseStandardSocketP, "use-standard-socket-p", 256, "@" },
122 { 301, NULL, 0, N_("@Options:\n ") },
124 { oServer, "server", 0, N_("run in server mode (foreground)") },
125 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
126 { oVerbose, "verbose", 0, N_("verbose") },
127 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
128 { oSh, "sh", 0, N_("sh-style command output") },
129 { oCsh, "csh", 0, N_("csh-style command output") },
130 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
131 { oDebug, "debug" ,4|16, "@"},
132 { oDebugAll, "debug-all" ,0, "@"},
133 { oDebugLevel, "debug-level" ,2, "@"},
134 { oDebugWait,"debug-wait",1, "@"},
135 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
136 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
137 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
138 { oUseStandardSocket, "use-standard-socket", 0,
139 N_("use a standard location for the socket")},
140 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
141 { oPinentryProgram, "pinentry-program", 2 ,
142 N_("|PGM|use PGM as the PIN-Entry program") },
143 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
144 { oScdaemonProgram, "scdaemon-program", 2 ,
145 N_("|PGM|use PGM as the SCdaemon program") },
146 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
147 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
149 { oBatch, "batch", 0, "@" },
150 { oHomedir, "homedir", 2, "@"},
152 { oDisplay, "display", 2, "@" },
153 { oTTYname, "ttyname", 2, "@" },
154 { oTTYtype, "ttytype", 2, "@" },
155 { oLCctype, "lc-ctype", 2, "@" },
156 { oLCmessages, "lc-messages", 2, "@" },
157 { oXauthority, "xauthority", 2, "@" },
158 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
159 { oKeepDISPLAY, "keep-display",
160 0, N_("ignore requests to change the X display")},
162 { oDefCacheTTL, "default-cache-ttl", 4,
163 N_("|N|expire cached PINs after N seconds")},
164 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
165 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
166 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
168 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
169 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
170 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
171 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
172 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
173 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
175 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
176 N_("do not use the PIN cache when signing")},
177 { oAllowMarkTrusted, "allow-mark-trusted", 0,
178 N_("allow clients to mark keys as \"trusted\"")},
179 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
180 N_("allow presetting passphrase")},
181 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
182 { oWriteEnvFile, "write-env-file", 2|8,
183 N_("|FILE|write environment settings also to FILE")},
188 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
189 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
190 #define MAX_CACHE_TTL (120*60) /* 2 hours */
191 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
192 #define MIN_PASSPHRASE_LEN (8)
193 #define MIN_PASSPHRASE_NONALPHA (1)
194 #define MAX_PASSPHRASE_DAYS (0)
196 /* The timer tick used for housekeeping stuff. For Windows we use a
197 longer period as the SetWaitableTimer seems to signal earlier than
199 #ifdef HAVE_W32_SYSTEM
200 #define TIMERTICK_INTERVAL (4)
202 #define TIMERTICK_INTERVAL (2) /* Seconds. */
206 /* The list of open file descriptors at startup. Note that this list
207 has been allocated using the standard malloc. */
208 static int *startup_fd_list;
210 /* The signal mask at startup and a flag telling whether it is valid. */
211 #ifdef HAVE_SIGPROCMASK
212 static sigset_t startup_signal_mask;
213 static int startup_signal_mask_valid;
216 /* Flag to indicate that a shutdown was requested. */
217 static int shutdown_pending;
219 /* Counter for the currently running own socket checks. */
220 static int check_own_socket_running;
222 /* It is possible that we are currently running under setuid permissions */
223 static int maybe_setuid = 1;
225 /* Name of the communication socket used for native gpg-agent requests. */
226 static char *socket_name;
228 /* Name of the communication socket used for ssh-agent-emulation. */
229 static char *socket_name_ssh;
231 /* We need to keep track of the server's nonces (these are dummies for
233 static assuan_sock_nonce_t socket_nonce;
234 static assuan_sock_nonce_t socket_nonce_ssh;
237 /* Default values for options passed to the pinentry. */
238 static char *default_display;
239 static char *default_ttyname;
240 static char *default_ttytype;
241 static char *default_lc_ctype;
242 static char *default_lc_messages;
243 static char *default_xauthority;
245 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
246 static char *config_filename;
248 /* Helper to implement --debug-level */
249 static const char *debug_level;
251 /* Keep track of the current log file so that we can avoid updating
252 the log file after a SIGHUP if it didn't changed. Malloced. */
253 static char *current_logfile;
255 /* The handle_tick() function may test whether a parent is still
256 running. We record the PID of the parent here or -1 if it should be
258 static pid_t parent_pid = (pid_t)(-1);
265 static char *create_socket_name (char *standard_name, char *template);
266 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
267 assuan_sock_nonce_t *nonce);
268 static void create_directories (void);
270 static void agent_init_default_ctrl (ctrl_t ctrl);
271 static void agent_deinit_default_ctrl (ctrl_t ctrl);
273 static void handle_connections (gnupg_fd_t listen_fd,
274 gnupg_fd_t listen_fd_ssh);
275 static void check_own_socket (void);
276 static int check_for_running_agent (int silent, int mode);
278 /* Pth wrapper function definitions. */
279 ASSUAN_SYSTEM_PTH_IMPL;
281 GCRY_THREAD_OPTION_PTH_IMPL;
282 static int fixed_gcry_pth_init (void)
284 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
288 #ifndef PTH_HAVE_PTH_THREAD_ID
289 static unsigned long pth_thread_id (void)
291 return (unsigned long)pth_self ();
302 make_libversion (const char *libname, const char *(*getfnc)(const char*))
309 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
313 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
314 strcpy (stpcpy (stpcpy (result, libname), " "), s);
320 my_strusage (int level)
322 static char *ver_gcry;
327 case 11: p = "gpg-agent (GnuPG)";
329 case 13: p = VERSION; break;
330 case 17: p = PRINTABLE_OS_NAME; break;
331 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
332 reporting address. This is so that we can change the
333 reporting address without breaking the translations. */
334 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
338 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
343 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
345 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
346 "Secret key management for GnuPG\n");
356 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
357 only the active debug flags are propagated to the subsystems. With
358 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
359 all flags already set. Note that we don't fail here, because it is
360 important to keep gpg-agent running even after re-reading the
361 options due to a SIGHUP. */
365 int numok = (debug_level && digitp (debug_level));
366 int numlvl = numok? atoi (debug_level) : 0;
370 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
372 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
373 opt.debug = DBG_ASSUAN_VALUE;
374 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
375 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
376 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
377 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
379 else if (!strcmp (debug_level, "guru") || numok)
382 /* Unless the "guru" string has been used we don't want to allow
383 hashing debugging. The rationale is that people tend to
384 select the highest debug value and would then clutter their
385 disk with debug files which may reveal confidential data. */
387 opt.debug &= ~(DBG_HASHING_VALUE);
391 log_error (_("invalid debug-level `%s' given\n"), debug_level);
392 opt.debug = 0; /* Reset debugging, so that prior debug
393 statements won't have an undesired effect. */
396 if (opt.debug && !opt.verbose)
398 if (opt.debug && opt.quiet)
401 if (opt.debug & DBG_MPI_VALUE)
402 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
403 if (opt.debug & DBG_CRYPTO_VALUE )
404 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
405 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
408 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s\n",
409 (opt.debug & DBG_COMMAND_VALUE)? " command":"",
410 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
411 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
412 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
413 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
414 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
415 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
416 (opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
420 /* Helper for cleanup to remove one socket with NAME. */
422 remove_socket (char *name)
429 p = strrchr (name, '/');
448 deinitialize_module_cache ();
449 remove_socket (socket_name);
450 remove_socket (socket_name_ssh);
455 /* Handle options which are allowed to be reset after program start.
456 Return true when the current option in PARGS could be handled and
457 false if not. As a special feature, passing a value of NULL for
458 PARGS, resets the options to the default. REREAD should be set
459 true if it is not the initial option parsing. */
461 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
469 opt.pinentry_program = NULL;
470 opt.pinentry_touch_file = NULL;
471 opt.scdaemon_program = NULL;
472 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
473 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
474 opt.max_cache_ttl = MAX_CACHE_TTL;
475 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
476 opt.enforce_passphrase_constraints = 0;
477 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
478 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
479 opt.check_passphrase_pattern = NULL;
480 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
481 opt.enable_passhrase_history = 0;
482 opt.ignore_cache_for_signing = 0;
483 opt.allow_mark_trusted = 0;
484 opt.disable_scdaemon = 0;
488 switch (pargs->r_opt)
490 case oQuiet: opt.quiet = 1; break;
491 case oVerbose: opt.verbose++; break;
493 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
494 case oDebugAll: opt.debug = ~0; break;
495 case oDebugLevel: debug_level = pargs->r.ret_str; break;
499 return 0; /* not handeld */
500 if (!current_logfile || !pargs->r.ret_str
501 || strcmp (current_logfile, pargs->r.ret_str))
503 log_set_file (pargs->r.ret_str);
504 xfree (current_logfile);
505 current_logfile = xtrystrdup (pargs->r.ret_str);
509 case oNoGrab: opt.no_grab = 1; break;
511 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
512 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
513 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
514 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
516 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
517 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
518 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
519 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
521 case oEnforcePassphraseConstraints:
522 opt.enforce_passphrase_constraints=1;
524 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
525 case oMinPassphraseNonalpha:
526 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
528 case oCheckPassphrasePattern:
529 opt.check_passphrase_pattern = pargs->r.ret_str;
531 case oMaxPassphraseDays:
532 opt.max_passphrase_days = pargs->r.ret_ulong;
534 case oEnablePassphraseHistory:
535 opt.enable_passhrase_history = 1;
538 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
540 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
542 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
545 return 0; /* not handled */
548 return 1; /* handled */
552 /* The main entry point. */
554 main (int argc, char **argv )
560 FILE *configfp = NULL;
561 char *configname = NULL;
563 unsigned configlineno;
565 int default_config =1;
572 char *logfile = NULL;
574 int gpgconf_list = 0;
576 const char *env_file_name = NULL;
577 struct assuan_malloc_hooks malloc_hooks;
579 /* Before we do anything else we save the list of currently open
580 file descriptors and the signal mask. This info is required to
581 do the exec call properly. */
582 startup_fd_list = get_all_open_fds ();
583 #ifdef HAVE_SIGPROCMASK
584 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
585 startup_signal_mask_valid = 1;
586 #endif /*HAVE_SIGPROCMASK*/
588 /* Set program name etc. */
589 set_strusage (my_strusage);
590 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
591 /* Please note that we may running SUID(ROOT), so be very CAREFUL
592 when adding any stuff between here and the call to INIT_SECMEM()
593 somewhere after the option parsing */
594 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
596 /* Make sure that our subsystems are ready. */
598 init_common_subsystems (&argc, &argv);
601 /* Libgcrypt requires us to register the threading model first.
602 Note that this will also do the pth_init. */
603 gcry_threads_pth.init = fixed_gcry_pth_init;
604 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
607 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
612 /* Check that the libraries are suitable. Do it here because
613 the option parsing may need services of the library. */
614 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
616 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
617 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
620 malloc_hooks.malloc = gcry_malloc;
621 malloc_hooks.realloc = gcry_realloc;
622 malloc_hooks.free = gcry_free;
623 assuan_set_malloc_hooks (&malloc_hooks);
624 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
625 assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
627 setup_libassuan_logging (&opt.debug);
629 setup_libgcrypt_logging ();
630 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
632 may_coredump = disable_core_dumps ();
634 /* Set default options. */
635 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
636 #ifdef USE_STANDARD_SOCKET
637 opt.use_standard_socket = 1;
640 shell = getenv ("SHELL");
641 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
644 opt.homedir = default_homedir ();
646 /* Record some of the original environment strings. */
650 static const char *names[] =
651 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
654 opt.startup_env = session_env_new ();
655 if (!opt.startup_env)
656 err = gpg_error_from_syserror ();
657 for (idx=0; !err && names[idx]; idx++)
659 s = getenv (names[idx]);
661 err = session_env_setenv (opt.startup_env, names[idx], s);
667 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
670 log_fatal ("error recording startup environment: %s\n",
673 /* Fixme: Better use the locale function here. */
674 opt.startup_lc_ctype = getenv ("LC_CTYPE");
675 if (opt.startup_lc_ctype)
676 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
677 opt.startup_lc_messages = getenv ("LC_MESSAGES");
678 if (opt.startup_lc_messages)
679 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
682 /* Check whether we have a config file on the commandline */
687 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
688 while (arg_parse( &pargs, opts))
690 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
692 else if (pargs.r_opt == oOptions)
693 { /* yes there is one, so we do not try the default one, but
694 read the option file when it is encountered at the
698 else if (pargs.r_opt == oNoOptions)
699 default_config = 0; /* --no-options */
700 else if (pargs.r_opt == oHomedir)
701 opt.homedir = pargs.r.ret_str;
704 /* Initialize the secure memory. */
705 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
709 Now we are now working under our real uid
713 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
719 pargs.flags= 1; /* do not remove the args */
724 configfp = fopen (configname, "r");
730 log_info (_("NOTE: no default option file `%s'\n"),
732 /* Save the default conf file name so that
733 reread_configuration is able to test whether the
734 config file has been created in the meantime. */
735 xfree (config_filename);
736 config_filename = configname;
741 log_error (_("option file `%s': %s\n"),
742 configname, strerror(errno) );
748 if (parse_debug && configname )
749 log_info (_("reading options from `%s'\n"), configname );
753 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
755 if (parse_rereadable_options (&pargs, 0))
756 continue; /* Already handled */
759 case aGPGConfList: gpgconf_list = 1; break;
760 case aGPGConfTest: gpgconf_list = 2; break;
761 case aUseStandardSocketP: gpgconf_list = 3; break;
762 case oBatch: opt.batch=1; break;
764 case oDebugWait: debug_wait = pargs.r.ret_int; break;
767 /* config files may not be nested (silently ignore them) */
771 configname = xstrdup(pargs.r.ret_str);
775 case oNoGreeting: nogreeting = 1; break;
776 case oNoVerbose: opt.verbose = 0; break;
777 case oNoOptions: break; /* no-options */
778 case oHomedir: opt.homedir = pargs.r.ret_str; break;
779 case oNoDetach: nodetach = 1; break;
780 case oLogFile: logfile = pargs.r.ret_str; break;
781 case oCsh: csh_style = 1; break;
782 case oSh: csh_style = 0; break;
783 case oServer: pipe_server = 1; break;
784 case oDaemon: is_daemon = 1; break;
786 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
787 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
788 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
789 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
790 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
791 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
794 case oUseStandardSocket: opt.use_standard_socket = 1; break;
795 case oNoUseStandardSocket: opt.use_standard_socket = 0; break;
797 case oFakedSystemTime:
799 time_t faked_time = isotime2epoch (pargs.r.ret_str);
800 if (faked_time == (time_t)(-1))
801 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
802 gnupg_set_time (faked_time, 0);
806 case oKeepTTY: opt.keep_tty = 1; break;
807 case oKeepDISPLAY: opt.keep_display = 1; break;
809 case oSSHSupport: opt.ssh_support = 1; break;
812 env_file_name = pargs.r.ret_str;
814 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
817 default : pargs.err = configfp? 1:2; break;
824 /* Keep a copy of the name so that it can be read on SIGHUP. */
825 if (config_filename != configname)
827 xfree (config_filename);
828 config_filename = configname;
836 if (log_get_errorcount(0))
843 es_fprintf (es_stderr, "%s %s; %s\n",
844 strusage(11), strusage(13), strusage(14) );
845 es_fprintf (es_stderr, "%s\n", strusage(15) );
847 #ifdef IS_DEVELOPMENT_VERSION
848 /* We don't want to print it here because gpg-agent is useful of its
849 own and quite matured. */
850 /*log_info ("NOTE: this is a development version!\n");*/
855 if (atexit (cleanup))
857 log_error ("atexit failed\n");
862 initialize_module_cache ();
863 initialize_module_call_pinentry ();
864 initialize_module_call_scd ();
865 initialize_module_trustlist ();
867 /* Try to create missing directories. */
868 create_directories ();
870 if (debug_wait && pipe_server)
872 log_debug ("waiting for debugger - my pid is %u .....\n",
873 (unsigned int)getpid());
874 gnupg_sleep (debug_wait);
875 log_debug ("... okay\n");
878 if (gpgconf_list == 3)
880 if (opt.use_standard_socket && !opt.quiet)
881 log_info ("configured to use the standard socket\n");
882 agent_exit (!opt.use_standard_socket);
884 else if (gpgconf_list == 2)
886 else if (gpgconf_list)
891 /* List options and default values in the GPG Conf format. */
892 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
893 filename_esc = percent_escape (filename, NULL);
895 es_printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
896 GC_OPT_FLAG_DEFAULT, filename_esc);
898 xfree (filename_esc);
900 es_printf ("verbose:%lu:\n"
902 "debug-level:%lu:\"none:\n"
904 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
905 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
906 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
907 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
908 es_printf ("default-cache-ttl:%lu:%d:\n",
909 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
910 es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
911 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
912 es_printf ("max-cache-ttl:%lu:%d:\n",
913 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
914 es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
915 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
916 es_printf ("enforce-passphrase-constraints:%lu:\n",
917 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
918 es_printf ("min-passphrase-len:%lu:%d:\n",
919 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
920 es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
921 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
922 MIN_PASSPHRASE_NONALPHA);
923 es_printf ("check-passphrase-pattern:%lu:\n",
924 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
925 es_printf ("max-passphrase-days:%lu:%d:\n",
926 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
927 MAX_PASSPHRASE_DAYS);
928 es_printf ("enable-passphrase-history:%lu:\n",
929 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
930 es_printf ("no-grab:%lu:\n",
931 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
932 es_printf ("ignore-cache-for-signing:%lu:\n",
933 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
934 es_printf ("allow-mark-trusted:%lu:\n",
935 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
936 es_printf ("disable-scdaemon:%lu:\n",
937 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
942 /* If this has been called without any options, we merely check
943 whether an agent is already running. We do this here so that we
944 don't clobber a logfile but print it directly to stderr. */
945 if (!pipe_server && !is_daemon)
947 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
948 check_for_running_agent (0, 0);
953 /* gpg-agent usually does not output any messages because it runs in
954 the background. For log files it is acceptable to have messages
955 always encoded in utf-8. We switch here to utf-8, so that
956 commands like --help still give native messages. It is far
957 easier to switch only once instead of for every message and it
958 actually helps when more then one thread is active (avoids an
960 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
963 /* Now start with logging to a file if this is desired. */
966 log_set_file (logfile);
967 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
969 |JNLIB_LOG_WITH_PID));
970 current_logfile = xstrdup (logfile);
973 /* Make sure that we have a default ttyname. */
974 if (!default_ttyname && ttyname (1))
975 default_ttyname = xstrdup (ttyname (1));
976 if (!default_ttytype && getenv ("TERM"))
977 default_ttytype = xstrdup (getenv ("TERM"));
982 /* This is the simple pipe based server */
985 ctrl = xtrycalloc (1, sizeof *ctrl);
988 log_error ("error allocating connection control data: %s\n",
992 ctrl->session_env = session_env_new ();
993 if (!ctrl->session_env)
995 log_error ("error allocating session environment block: %s\n",
1000 agent_init_default_ctrl (ctrl);
1001 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1002 agent_deinit_default_ctrl (ctrl);
1005 else if (!is_daemon)
1008 { /* Regular server mode */
1013 /* Remove the DISPLAY variable so that a pinentry does not
1014 default to a specific display. There is still a default
1015 display when gpg-agent was started using --display or a
1016 client requested this using an OPTION command. Note, that we
1017 don't do this when running in reverse daemon mode (i.e. when
1018 exec the program given as arguments). */
1019 #ifndef HAVE_W32_SYSTEM
1020 if (!opt.keep_display && !argc)
1021 gnupg_unsetenv ("DISPLAY");
1025 /* Create the sockets. */
1026 socket_name = create_socket_name
1027 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
1028 if (opt.ssh_support)
1029 socket_name_ssh = create_socket_name
1030 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
1032 fd = create_server_socket (socket_name, 0, &socket_nonce);
1033 if (opt.ssh_support)
1034 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
1036 fd_ssh = GNUPG_INVALID_FD;
1038 /* If we are going to exec a program in the parent, we record
1039 the PID, so that the child may check whether the program is
1042 parent_pid = getpid ();
1045 #ifdef HAVE_W32_SYSTEM
1047 es_printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
1048 #else /*!HAVE_W32_SYSTEM*/
1050 if (pid == (pid_t)-1)
1052 log_fatal ("fork failed: %s\n", strerror (errno) );
1056 { /* We are the parent */
1057 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
1059 /* Close the socket FD. */
1062 /* Note that we used a standard fork so that Pth runs in
1063 both the parent and the child. The pth_fork would
1064 terminate Pth in the child but that is not the way we
1065 want it. Thus we use a plain fork and terminate Pth here
1066 in the parent. The pth_kill may or may not work reliable
1067 but it should not harm to call it. Because Pth fiddles
1068 with the signal mask the signal mask might not be correct
1069 right now and thus we restore it. That is not strictly
1070 necessary but some programs falsely assume a cleared
1073 log_error ("pth_kill failed in forked process\n");
1075 #ifdef HAVE_SIGPROCMASK
1076 if (startup_signal_mask_valid)
1078 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1079 log_error ("error restoring signal mask: %s\n",
1083 log_info ("no saved signal mask\n");
1084 #endif /*HAVE_SIGPROCMASK*/
1086 /* Create the info string: <name>:<pid>:<protocol_version> */
1087 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1088 socket_name, (ulong)pid ) < 0)
1090 log_error ("out of core\n");
1091 kill (pid, SIGTERM);
1094 if (opt.ssh_support)
1096 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1097 socket_name_ssh) < 0)
1099 log_error ("out of core\n");
1100 kill (pid, SIGTERM);
1103 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1106 log_error ("out of core\n");
1107 kill (pid, SIGTERM);
1112 *socket_name = 0; /* Don't let cleanup() remove the socket -
1113 the child should do this from now on */
1114 if (opt.ssh_support)
1115 *socket_name_ssh = 0;
1121 fp = es_fopen (env_file_name, "w,mode=-rw");
1123 log_error (_("error creating `%s': %s\n"),
1124 env_file_name, strerror (errno));
1127 es_fputs (infostr, fp);
1129 if (opt.ssh_support)
1131 es_fputs (infostr_ssh_sock, fp);
1133 es_fputs (infostr_ssh_pid, fp);
1142 { /* Run the program given on the commandline. */
1143 if (putenv (infostr))
1145 log_error ("failed to set environment: %s\n",
1147 kill (pid, SIGTERM );
1150 if (opt.ssh_support && putenv (infostr_ssh_sock))
1152 log_error ("failed to set environment: %s\n",
1154 kill (pid, SIGTERM );
1157 if (opt.ssh_support && putenv (infostr_ssh_pid))
1159 log_error ("failed to set environment: %s\n",
1161 kill (pid, SIGTERM );
1165 /* Close all the file descriptors except the standard
1166 ones and those open at startup. We explicitly don't
1167 close 0,1,2 in case something went wrong collecting
1169 close_all_fds (3, startup_fd_list);
1171 /* Run the command. */
1172 execvp (argv[0], argv);
1173 log_error ("failed to run the command: %s\n", strerror (errno));
1174 kill (pid, SIGTERM);
1179 /* Print the environment string, so that the caller can use
1180 shell's eval to set it */
1183 *strchr (infostr, '=') = ' ';
1184 es_printf ("setenv %s\n", infostr);
1185 if (opt.ssh_support)
1187 *strchr (infostr_ssh_sock, '=') = ' ';
1188 es_printf ("setenv %s\n", infostr_ssh_sock);
1189 *strchr (infostr_ssh_pid, '=') = ' ';
1190 es_printf ("setenv %s\n", infostr_ssh_pid);
1195 es_printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1196 if (opt.ssh_support)
1198 es_printf ("%s; export SSH_AUTH_SOCK;\n",
1200 es_printf ("%s; export SSH_AGENT_PID;\n",
1205 if (opt.ssh_support)
1207 xfree (infostr_ssh_sock);
1208 xfree (infostr_ssh_pid);
1219 /* Detach from tty and put process into a new session */
1223 unsigned int oldflags;
1225 /* Close stdin, stdout and stderr unless it is the log stream */
1226 for (i=0; i <= 2; i++)
1228 if (!log_test_fd (i) && i != fd )
1231 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1233 log_error ("failed to open `%s': %s\n",
1234 "/dev/null", strerror (errno));
1242 log_error ("setsid() failed: %s\n", strerror(errno) );
1247 log_get_prefix (&oldflags);
1248 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1249 opt.running_detached = 1;
1254 log_error ("chdir to / failed: %s\n", strerror (errno));
1259 struct sigaction sa;
1261 sa.sa_handler = SIG_IGN;
1262 sigemptyset (&sa.sa_mask);
1264 sigaction (SIGPIPE, &sa, NULL);
1266 #endif /*!HAVE_W32_SYSTEM*/
1268 log_info ("%s %s started\n", strusage(11), strusage(13) );
1269 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1270 assuan_sock_close (fd);
1280 /*FIXME: update_random_seed_file();*/
1282 /* We run our cleanup handler because that may close cipher contexts
1283 stored in secure memory and thus this needs to be done before we
1284 explicitly terminate secure memory. */
1288 /* at this time a bit annoying */
1289 if (opt.debug & DBG_MEMSTAT_VALUE)
1291 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1292 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1295 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1297 gcry_control (GCRYCTL_TERM_SECMEM );
1298 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1304 agent_init_default_ctrl (ctrl_t ctrl)
1306 /* Note we ignore malloc errors because we can't do much about it
1307 and the request will fail anyway shortly after this
1309 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1310 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1311 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1312 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1313 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1316 xfree (ctrl->lc_ctype);
1317 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1319 if (ctrl->lc_messages)
1320 xfree (ctrl->lc_messages);
1321 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1328 agent_deinit_default_ctrl (ctrl_t ctrl)
1330 session_env_release (ctrl->session_env);
1333 xfree (ctrl->lc_ctype);
1334 if (ctrl->lc_messages)
1335 xfree (ctrl->lc_messages);
1339 /* Reread parts of the configuration. Note, that this function is
1340 obviously not thread-safe and should only be called from the PTH
1343 Fixme: Due to the way the argument parsing works, we create a
1344 memory leak here for all string type arguments. There is currently
1345 no clean way to tell whether the memory for the argument has been
1346 allocated or points into the process' original arguments. Unless
1347 we have a mechanism to tell this, we need to live on with this. */
1349 reread_configuration (void)
1351 ARGPARSE_ARGS pargs;
1353 unsigned int configlineno = 0;
1356 if (!config_filename)
1357 return; /* No config file. */
1359 fp = fopen (config_filename, "r");
1362 log_info (_("option file `%s': %s\n"),
1363 config_filename, strerror(errno) );
1367 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1369 memset (&pargs, 0, sizeof pargs);
1371 pargs.argc = &dummy;
1372 pargs.flags = 1; /* do not remove the args */
1373 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1375 if (pargs.r_opt < -1)
1376 pargs.err = 1; /* Print a warning. */
1377 else /* Try to parse this option - ignore unchangeable ones. */
1378 parse_rereadable_options (&pargs, 1);
1385 /* Return the file name of the socket we are using for native
1388 get_agent_socket_name (void)
1390 const char *s = socket_name;
1392 return (s && *s)? s : NULL;
1395 /* Return the file name of the socket we are using for SSH
1398 get_agent_ssh_socket_name (void)
1400 const char *s = socket_name_ssh;
1402 return (s && *s)? s : NULL;
1406 /* Under W32, this function returns the handle of the scdaemon
1407 notification event. Calling it the first time creates that
1409 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1411 get_agent_scd_notify_event (void)
1413 static HANDLE the_event;
1418 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1420 /* We need to use a manual reset event object due to the way our
1421 w32-pth wait function works: If we would use an automatic
1422 reset event we are not able to figure out which handle has
1423 been signaled because at the time we single out the signaled
1424 handles using WFSO the event has already been reset due to
1426 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1428 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1429 else if (!DuplicateHandle (GetCurrentProcess(), h,
1430 GetCurrentProcess(), &h2,
1431 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1433 log_error ("setting syncronize for scd notify event failed: %s\n",
1434 w32_strerror (-1) );
1444 log_debug ("returning notify handle %p\n", the_event);
1447 #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
1451 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1452 true using STANDARD_NAME in the home directory or if given as
1453 false from the mkdir type name TEMPLATE. In the latter case a
1454 unique name in a unique new directory will be created. In both
1455 cases check for valid characters as well as against a maximum
1456 allowed length for a unix domain socket is done. The function
1457 terminates the process in case of an error. Returns: Pointer to an
1458 allocated string with the absolute name of the socket used. */
1460 create_socket_name (char *standard_name, char *template)
1464 if (opt.use_standard_socket)
1465 name = make_filename (opt.homedir, standard_name, NULL);
1468 name = xstrdup (template);
1469 p = strrchr (name, '/');
1473 if (!mkdtemp (name))
1475 log_error (_("can't create directory `%s': %s\n"),
1476 name, strerror (errno));
1482 if (strchr (name, PATHSEP_C))
1484 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1487 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1489 log_error (_("name of socket too long\n"));
1497 /* Create a Unix domain socket with NAME. Returns the file descriptor
1498 or terminates the process in case of an error. Not that this
1499 function needs to be used for the regular socket first and only
1500 then for the ssh socket. */
1502 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1504 struct sockaddr_un *serv_addr;
1509 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1510 if (fd == ASSUAN_INVALID_FD)
1512 log_error (_("can't create socket: %s\n"), strerror (errno));
1516 serv_addr = xmalloc (sizeof (*serv_addr));
1517 memset (serv_addr, 0, sizeof *serv_addr);
1518 serv_addr->sun_family = AF_UNIX;
1519 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1521 log_error (_("socket name `%s' is too long\n"), name);
1524 strcpy (serv_addr->sun_path, name);
1525 len = SUN_LEN (serv_addr);
1526 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1528 /* Our error code mapping on W32CE returns EEXIST thus we also test
1530 if (opt.use_standard_socket && rc == -1
1531 && (errno == EADDRINUSE
1532 #ifdef HAVE_W32_SYSTEM
1537 /* Check whether a gpg-agent is already running on the standard
1538 socket. We do this test only if this is not the ssh socket.
1539 For ssh we assume that a test for gpg-agent has already been
1540 done and reuse the requested ssh socket. Testing the
1541 ssh-socket is not possible because at this point, though we
1542 know the new Assuan socket, the Assuan server and thus the
1543 ssh-agent server is not yet operational. This would lead to
1545 if (!is_ssh && !check_for_running_agent (1, 1))
1547 log_error (_("a gpg-agent is already running - "
1548 "not starting a new one\n"));
1549 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1550 assuan_sock_close (fd);
1553 gnupg_remove (name);
1554 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1557 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1558 log_error (_("error getting nonce for the socket\n"));
1561 /* We use gpg_strerror here because it allows us to get strings
1562 for some W32 socket error codes. */
1563 log_error (_("error binding socket to `%s': %s\n"),
1564 serv_addr->sun_path,
1565 gpg_strerror (gpg_error_from_errno (errno)));
1567 assuan_sock_close (fd);
1568 if (opt.use_standard_socket)
1569 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1573 if (listen (FD2INT(fd), 5 ) == -1)
1575 log_error (_("listen() failed: %s\n"), strerror (errno));
1576 assuan_sock_close (fd);
1581 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1587 /* Check that the directory for storing the private keys exists and
1588 create it if not. This function won't fail as it is only a
1589 convenience function and not strictly necessary. */
1591 create_private_keys_directory (const char *home)
1594 struct stat statbuf;
1596 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1597 if (stat (fname, &statbuf) && errno == ENOENT)
1599 if (gnupg_mkdir (fname, "-rwx"))
1600 log_error (_("can't create directory `%s': %s\n"),
1601 fname, strerror (errno) );
1602 else if (!opt.quiet)
1603 log_info (_("directory `%s' created\n"), fname);
1608 /* Create the directory only if the supplied directory name is the
1609 same as the default one. This way we avoid to create arbitrary
1610 directories when a non-default home directory is used. To cope
1611 with HOME, we compare only the suffix if we see that the default
1612 homedir does start with a tilde. We don't stop here in case of
1613 problems because other functions will throw an error anyway.*/
1615 create_directories (void)
1617 struct stat statbuf;
1618 const char *defhome = standard_homedir ();
1621 home = make_filename (opt.homedir, NULL);
1622 if ( stat (home, &statbuf) )
1624 if (errno == ENOENT)
1627 #ifdef HAVE_W32_SYSTEM
1628 ( !compare_filenames (home, defhome) )
1631 && (strlen (home) >= strlen (defhome+1)
1632 && !strcmp (home + strlen(home)
1633 - strlen (defhome+1), defhome+1)))
1634 || (*defhome != '~' && !strcmp (home, defhome) )
1638 if (gnupg_mkdir (home, "-rwx"))
1639 log_error (_("can't create directory `%s': %s\n"),
1640 home, strerror (errno) );
1644 log_info (_("directory `%s' created\n"), home);
1645 create_private_keys_directory (home);
1650 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1652 else if ( !S_ISDIR(statbuf.st_mode))
1654 log_error (_("can't use `%s' as home directory\n"), home);
1656 else /* exists and is a directory. */
1658 create_private_keys_directory (home);
1665 /* This is the worker for the ticker. It is called every few seconds
1666 and may only do fast operations. */
1670 static time_t last_minute;
1673 last_minute = time (NULL);
1675 /* Check whether the scdaemon has died and cleanup in this case. */
1676 agent_scd_check_aliveness ();
1678 /* If we are running as a child of another process, check whether
1679 the parent is still alive and shutdown if not. */
1680 #ifndef HAVE_W32_SYSTEM
1681 if (parent_pid != (pid_t)(-1))
1683 if (kill (parent_pid, 0))
1685 shutdown_pending = 2;
1686 log_info ("parent process died - shutting down\n");
1687 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1692 #endif /*HAVE_W32_SYSTEM*/
1694 /* Code to be run every minute. */
1695 if (last_minute + 60 <= time (NULL))
1697 check_own_socket ();
1698 last_minute = time (NULL);
1704 /* A global function which allows us to call the reload stuff from
1705 other places too. This is only used when build for W32. */
1707 agent_sighup_action (void)
1709 log_info ("SIGHUP received - "
1710 "re-reading configuration and flushing cache\n");
1711 agent_flush_cache ();
1712 reread_configuration ();
1713 agent_reload_trustlist ();
1718 agent_sigusr2_action (void)
1721 log_info ("SIGUSR2 received - updating card event counter\n");
1722 /* Nothing to check right now. We only increment a counter. */
1723 bump_card_eventcounter ();
1728 handle_signal (int signo)
1732 #ifndef HAVE_W32_SYSTEM
1734 agent_sighup_action ();
1738 log_info ("SIGUSR1 received - printing internal information:\n");
1739 /* Fixme: We need to see how to integrate pth dumping into our
1741 /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
1742 agent_query_dump_state ();
1743 agent_scd_dump_state ();
1747 agent_sigusr2_action ();
1751 if (!shutdown_pending)
1752 log_info ("SIGTERM received - shutting down ...\n");
1754 log_info ("SIGTERM received - still %ld running threads\n",
1755 pth_ctrl( PTH_CTRL_GETTHREADS ));
1757 if (shutdown_pending > 2)
1759 log_info ("shutdown forced\n");
1760 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1767 log_info ("SIGINT received - immediate shutdown\n");
1768 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1774 log_info ("signal %d received - no action defined\n", signo);
1779 /* Check the nonce on a new connection. This is a NOP unless we we
1780 are using our Unix domain socket emulation under Windows. */
1782 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1784 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1786 log_info (_("error reading nonce on fd %d: %s\n"),
1787 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1788 assuan_sock_close (ctrl->thread_startup.fd);
1797 /* This is the standard connection thread's main function. */
1799 start_connection_thread (void *arg)
1803 if (check_nonce (ctrl, &socket_nonce))
1806 agent_init_default_ctrl (ctrl);
1808 log_info (_("handler 0x%lx for fd %d started\n"),
1809 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1811 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1813 log_info (_("handler 0x%lx for fd %d terminated\n"),
1814 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1816 agent_deinit_default_ctrl (ctrl);
1822 /* This is the ssh connection thread's main function. */
1824 start_connection_thread_ssh (void *arg)
1828 if (check_nonce (ctrl, &socket_nonce_ssh))
1831 agent_init_default_ctrl (ctrl);
1833 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1834 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1836 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1838 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1839 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1841 agent_deinit_default_ctrl (ctrl);
1847 /* Connection handler loop. Wait for connection requests and spawn a
1848 thread after accepting a connection. */
1850 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1853 pth_event_t ev, time_ev;
1856 struct sockaddr_un paddr;
1858 fd_set fdset, read_fdset;
1863 tattr = pth_attr_new();
1864 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1865 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1867 #ifndef HAVE_W32_SYSTEM /* fixme */
1868 /* Make sure that the signals we are going to handle are not blocked
1869 and create an event object for them. We also set the default
1870 action to ignore because we use an Pth event to get notified
1871 about signals. This avoids that the default action is taken in
1872 case soemthing goes wrong within Pth. The problem might also be
1874 sigemptyset (&sigs );
1876 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1877 struct sigaction sa;
1880 for (i=0; i < DIM (mysigs); i++)
1882 sigemptyset (&sa.sa_mask);
1883 sa.sa_handler = SIG_IGN;
1885 sigaction (mysigs[i], &sa, NULL);
1887 sigaddset (&sigs, mysigs[i]);
1891 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1892 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1894 # ifdef HAVE_W32CE_SYSTEM
1895 /* Use a dummy event. */
1897 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1900 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1907 FD_SET (FD2INT (listen_fd), &fdset);
1908 nfd = FD2INT (listen_fd);
1909 if (listen_fd_ssh != GNUPG_INVALID_FD)
1911 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1912 if (FD2INT (listen_fd_ssh) > nfd)
1913 nfd = FD2INT (listen_fd_ssh);
1918 /* Make sure that our signals are not blocked. */
1919 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1921 /* Shutdown test. */
1922 if (shutdown_pending)
1924 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1927 /* Do not accept new connections but keep on running the
1928 loop to cope with the timer events. */
1932 /* Create a timeout event if needed. To help with power saving
1933 we syncronize the ticks to the next full second. */
1936 pth_time_t nexttick;
1938 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1939 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
1942 nexttick.tv_usec = 0;
1944 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1947 /* POSIX says that fd_set should be implemented as a structure,
1948 thus a simple assignment is fine to copy the entire set. */
1952 pth_event_concat (ev, time_ev, NULL);
1953 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1955 pth_event_isolate (time_ev);
1959 if (pth_event_occurred (ev)
1960 || (time_ev && pth_event_occurred (time_ev)))
1962 if (pth_event_occurred (ev))
1964 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1965 agent_sigusr2_action ();
1967 handle_signal (signo);
1970 if (time_ev && pth_event_occurred (time_ev))
1972 pth_event_free (time_ev, PTH_FREE_ALL);
1978 log_error (_("pth_select failed: %s - waiting 1s\n"),
1984 if (pth_event_occurred (ev))
1986 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1987 agent_sigusr2_action ();
1989 handle_signal (signo);
1993 if (time_ev && pth_event_occurred (time_ev))
1995 pth_event_free (time_ev, PTH_FREE_ALL);
2001 /* We now might create new threads and because we don't want any
2002 signals (as we are handling them here) to be delivered to a
2003 new thread. Thus we need to block those signals. */
2004 pth_sigmask (SIG_BLOCK, &sigs, NULL);
2006 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
2010 plen = sizeof paddr;
2011 fd = INT2FD (pth_accept (FD2INT(listen_fd),
2012 (struct sockaddr *)&paddr, &plen));
2013 if (fd == GNUPG_INVALID_FD)
2015 log_error ("accept failed: %s\n", strerror (errno));
2017 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2019 log_error ("error allocating connection control data: %s\n",
2021 assuan_sock_close (fd);
2023 else if ( !(ctrl->session_env = session_env_new ()) )
2025 log_error ("error allocating session environment block: %s\n",
2028 assuan_sock_close (fd);
2032 char threadname[50];
2034 snprintf (threadname, sizeof threadname-1,
2035 "conn fd=%d (gpg)", FD2INT(fd));
2036 threadname[sizeof threadname -1] = 0;
2037 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2038 ctrl->thread_startup.fd = fd;
2039 if (!pth_spawn (tattr, start_connection_thread, ctrl))
2041 log_error ("error spawning connection handler: %s\n",
2043 assuan_sock_close (fd);
2047 fd = GNUPG_INVALID_FD;
2050 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
2051 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
2055 plen = sizeof paddr;
2056 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
2057 (struct sockaddr *)&paddr, &plen));
2058 if (fd == GNUPG_INVALID_FD)
2060 log_error ("accept failed for ssh: %s\n", strerror (errno));
2062 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2064 log_error ("error allocating connection control data: %s\n",
2066 assuan_sock_close (fd);
2068 else if ( !(ctrl->session_env = session_env_new ()) )
2070 log_error ("error allocating session environment block: %s\n",
2073 assuan_sock_close (fd);
2077 char threadname[50];
2079 agent_init_default_ctrl (ctrl);
2080 snprintf (threadname, sizeof threadname-1,
2081 "conn fd=%d (ssh)", FD2INT(fd));
2082 threadname[sizeof threadname -1] = 0;
2083 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2084 ctrl->thread_startup.fd = fd;
2085 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2087 log_error ("error spawning ssh connection handler: %s\n",
2089 assuan_sock_close (fd);
2093 fd = GNUPG_INVALID_FD;
2097 pth_event_free (ev, PTH_FREE_ALL);
2099 pth_event_free (time_ev, PTH_FREE_ALL);
2101 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2106 /* Helper for check_own_socket. */
2108 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2110 membuf_t *mb = opaque;
2111 put_membuf (mb, buffer, length);
2116 /* The thread running the actual check. We need to run this in a
2117 separate thread so that check_own_thread can be called from the
2120 check_own_socket_thread (void *arg)
2123 char *sockname = arg;
2124 assuan_context_t ctx = NULL;
2128 check_own_socket_running++;
2130 rc = assuan_new (&ctx);
2133 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2137 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2140 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2144 init_membuf (&mb, 100);
2145 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2146 NULL, NULL, NULL, NULL);
2147 put_membuf (&mb, "", 1);
2148 buffer = get_membuf (&mb, NULL);
2151 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2152 "GETINFO pid", gpg_strerror (rc));
2155 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2157 log_error ("socket is now serviced by another server\n");
2160 else if (opt.verbose > 1)
2161 log_error ("socket is still served by this server\n");
2168 assuan_release (ctx);
2171 /* We may not remove the socket as it is now in use by another
2172 server. Setting the name to empty does this. */
2175 if (socket_name_ssh)
2176 *socket_name_ssh = 0;
2177 shutdown_pending = 2;
2178 log_info ("this process is useless - shutting down\n");
2180 check_own_socket_running--;
2185 /* Check whether we are still listening on our own socket. In case
2186 another gpg-agent process started after us has taken ownership of
2187 our socket, we woulf linger around without any real task. Thus we
2188 better check once in a while whether we are really needed. */
2190 check_own_socket (void)
2195 if (!opt.use_standard_socket)
2196 return; /* This check makes only sense in standard socket mode. */
2198 if (check_own_socket_running || shutdown_pending)
2199 return; /* Still running or already shutting down. */
2201 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2203 return; /* Out of memory. */
2205 tattr = pth_attr_new();
2206 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2207 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2208 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2210 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2211 log_error ("error spawning check_own_socket_thread: %s\n",
2213 pth_attr_destroy (tattr);
2218 /* Figure out whether an agent is available and running. Prints an
2219 error if not. If SILENT is true, no messages are printed. Usually
2220 started with MODE 0. Returns 0 if the agent is running. */
2222 check_for_running_agent (int silent, int mode)
2226 assuan_context_t ctx = NULL;
2231 infostr = getenv ("GPG_AGENT_INFO");
2232 if (!infostr || !*infostr)
2234 if (!check_for_running_agent (silent, 1))
2235 return 0; /* Okay, its running on the standard socket. */
2237 log_error (_("no gpg-agent running in this session\n"));
2241 infostr = xstrdup (infostr);
2242 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2245 if (!check_for_running_agent (silent, 1))
2246 return 0; /* Okay, its running on the standard socket. */
2248 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2254 while (*p && *p != PATHSEP_C)
2256 prot = *p? atoi (p+1) : 0;
2261 log_error (_("gpg-agent protocol version %d is not supported\n"),
2263 if (!check_for_running_agent (silent, 1))
2264 return 0; /* Okay, its running on the standard socket. */
2268 else /* MODE != 0 */
2270 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2274 rc = assuan_new (&ctx);
2276 rc = assuan_socket_connect (ctx, infostr, pid, 0);
2280 if (!mode && !check_for_running_agent (silent, 1))
2281 return 0; /* Okay, its running on the standard socket. */
2283 if (!mode && !silent)
2284 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2287 assuan_release (ctx);
2291 if (!opt.quiet && !silent)
2292 log_info ("gpg-agent running and available\n");
2294 assuan_release (ctx);