Move password repetition from gpg to gpg-agent.
[gnupg.git] / agent / gpg-agent.c
blob6cb08409e757d954e865c4620ff66d2ae0c5727d
1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2009 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/>.
21 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <time.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #ifndef HAVE_W32_SYSTEM
34 # include <sys/socket.h>
35 # include <sys/un.h>
36 #endif /*!HAVE_W32_SYSTEM*/
37 #include <unistd.h>
38 #include <signal.h>
39 #include <pth.h>
41 #define JNLIB_NEED_LOG_LOGV
42 #include "agent.h"
43 #include <assuan.h> /* Malloc hooks and socket wrappers. */
45 #include "i18n.h"
46 #include "mkdtemp.h" /* Gnulib replacement. */
47 #include "sysutils.h"
48 #include "setenv.h"
49 #include "gc-opt-flags.h"
52 enum cmd_and_opt_values
53 { aNull = 0,
54 oCsh = 'c',
55 oQuiet = 'q',
56 oSh = 's',
57 oVerbose = 'v',
59 oNoVerbose = 500,
60 aGPGConfList,
61 aGPGConfTest,
62 oOptions,
63 oDebug,
64 oDebugAll,
65 oDebugLevel,
66 oDebugWait,
67 oNoGreeting,
68 oNoOptions,
69 oHomedir,
70 oNoDetach,
71 oNoGrab,
72 oLogFile,
73 oServer,
74 oDaemon,
75 oBatch,
77 oPinentryProgram,
78 oPinentryTouchFile,
79 oDisplay,
80 oTTYname,
81 oTTYtype,
82 oLCctype,
83 oLCmessages,
84 oXauthority,
85 oScdaemonProgram,
86 oDefCacheTTL,
87 oDefCacheTTLSSH,
88 oMaxCacheTTL,
89 oMaxCacheTTLSSH,
90 oEnforcePassphraseConstraints,
91 oMinPassphraseLen,
92 oMinPassphraseNonalpha,
93 oCheckPassphrasePattern,
94 oMaxPassphraseDays,
95 oEnablePassphraseHistory,
96 oUseStandardSocket,
97 oNoUseStandardSocket,
98 oFakedSystemTime,
100 oIgnoreCacheForSigning,
101 oAllowMarkTrusted,
102 oAllowPresetPassphrase,
103 oKeepTTY,
104 oKeepDISPLAY,
105 oSSHSupport,
106 oDisableScdaemon,
107 oWriteEnvFile
112 static ARGPARSE_OPTS opts[] = {
114 { aGPGConfList, "gpgconf-list", 256, "@" },
115 { aGPGConfTest, "gpgconf-test", 256, "@" },
117 { 301, NULL, 0, N_("@Options:\n ") },
119 { oServer, "server", 0, N_("run in server mode (foreground)") },
120 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
121 { oVerbose, "verbose", 0, N_("verbose") },
122 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
123 { oSh, "sh", 0, N_("sh-style command output") },
124 { oCsh, "csh", 0, N_("csh-style command output") },
125 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
126 { oDebug, "debug" ,4|16, "@"},
127 { oDebugAll, "debug-all" ,0, "@"},
128 { oDebugLevel, "debug-level" ,2, "@"},
129 { oDebugWait,"debug-wait",1, "@"},
130 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
131 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
132 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
133 { oUseStandardSocket, "use-standard-socket", 0,
134 N_("use a standard location for the socket")},
135 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
136 { oPinentryProgram, "pinentry-program", 2 ,
137 N_("|PGM|use PGM as the PIN-Entry program") },
138 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
139 { oScdaemonProgram, "scdaemon-program", 2 ,
140 N_("|PGM|use PGM as the SCdaemon program") },
141 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
142 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
144 { oBatch, "batch", 0, "@" },
145 { oHomedir, "homedir", 2, "@"},
147 { oDisplay, "display", 2, "@" },
148 { oTTYname, "ttyname", 2, "@" },
149 { oTTYtype, "ttytype", 2, "@" },
150 { oLCctype, "lc-ctype", 2, "@" },
151 { oLCmessages, "lc-messages", 2, "@" },
152 { oXauthority, "xauthority", 2, "@" },
153 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
154 { oKeepDISPLAY, "keep-display",
155 0, N_("ignore requests to change the X display")},
157 { oDefCacheTTL, "default-cache-ttl", 4,
158 N_("|N|expire cached PINs after N seconds")},
159 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
160 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
161 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
163 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
164 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
165 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
166 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
167 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
168 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
170 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
171 N_("do not use the PIN cache when signing")},
172 { oAllowMarkTrusted, "allow-mark-trusted", 0,
173 N_("allow clients to mark keys as \"trusted\"")},
174 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
175 N_("allow presetting passphrase")},
176 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
177 { oWriteEnvFile, "write-env-file", 2|8,
178 N_("|FILE|write environment settings also to FILE")},
183 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
184 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
185 #define MAX_CACHE_TTL (120*60) /* 2 hours */
186 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
187 #define MIN_PASSPHRASE_LEN (8)
188 #define MIN_PASSPHRASE_NONALPHA (1)
189 #define MAX_PASSPHRASE_DAYS (0)
191 /* The timer tick used for housekeeping stuff. For Windows we use a
192 longer period as the SetWaitableTimer seems to signal earlier than
193 the 2 seconds. */
194 #ifdef HAVE_W32_SYSTEM
195 #define TIMERTICK_INTERVAL (4)
196 #else
197 #define TIMERTICK_INTERVAL (2) /* Seconds. */
198 #endif
200 /* Flag to indicate that a shutdown was requested. */
201 static int shutdown_pending;
203 /* Counter for the currently running own socket checks. */
204 static int check_own_socket_running;
206 /* True if we are listening on the standard socket. */
207 static int use_standard_socket;
209 /* It is possible that we are currently running under setuid permissions */
210 static int maybe_setuid = 1;
212 /* Name of the communication socket used for native gpg-agent requests. */
213 static char *socket_name;
215 /* Name of the communication socket used for ssh-agent-emulation. */
216 static char *socket_name_ssh;
218 /* We need to keep track of the server's nonces (these are dummies for
219 POSIX systems). */
220 static assuan_sock_nonce_t socket_nonce;
221 static assuan_sock_nonce_t socket_nonce_ssh;
224 /* Default values for options passed to the pinentry. */
225 static char *default_display;
226 static char *default_ttyname;
227 static char *default_ttytype;
228 static char *default_lc_ctype;
229 static char *default_lc_messages;
230 static char *default_xauthority;
232 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
233 static char *config_filename;
235 /* Helper to implement --debug-level */
236 static const char *debug_level;
238 /* Keep track of the current log file so that we can avoid updating
239 the log file after a SIGHUP if it didn't changed. Malloced. */
240 static char *current_logfile;
242 /* The handle_tick() function may test whether a parent is still
243 running. We record the PID of the parent here or -1 if it should be
244 watched. */
245 static pid_t parent_pid = (pid_t)(-1);
249 Local prototypes.
252 static char *create_socket_name (char *standard_name, char *template);
253 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
254 assuan_sock_nonce_t *nonce);
255 static void create_directories (void);
257 static void agent_init_default_ctrl (ctrl_t ctrl);
258 static void agent_deinit_default_ctrl (ctrl_t ctrl);
260 static void handle_connections (gnupg_fd_t listen_fd,
261 gnupg_fd_t listen_fd_ssh);
262 static void check_own_socket (void);
263 static int check_for_running_agent (int silent, int mode);
265 /* Pth wrapper function definitions. */
266 GCRY_THREAD_OPTION_PTH_IMPL;
267 static int fixed_gcry_pth_init (void)
269 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
273 #ifndef PTH_HAVE_PTH_THREAD_ID
274 static unsigned long pth_thread_id (void)
276 return (unsigned long)pth_self ();
278 #endif
283 Functions.
286 static char *
287 make_libversion (const char *libname, const char *(*getfnc)(const char*))
289 const char *s;
290 char *result;
292 if (maybe_setuid)
294 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
295 maybe_setuid = 0;
297 s = getfnc (NULL);
298 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
299 strcpy (stpcpy (stpcpy (result, libname), " "), s);
300 return result;
304 static const char *
305 my_strusage (int level)
307 static char *ver_gcry;
308 const char *p;
310 switch (level)
312 case 11: p = "gpg-agent (GnuPG)";
313 break;
314 case 13: p = VERSION; break;
315 case 17: p = PRINTABLE_OS_NAME; break;
316 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
317 break;
318 case 20:
319 if (!ver_gcry)
320 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
321 p = ver_gcry;
322 break;
324 case 1:
325 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
326 break;
327 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
328 "Secret key management for GnuPG\n");
329 break;
331 default: p = NULL;
333 return p;
338 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
339 only the active debug flags are propagated to the subsystems. With
340 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
341 all flags already set. Note that we don't fail here, because it is
342 important to keep gpg-agent running even after re-reading the
343 options due to a SIGHUP. */
344 static void
345 set_debug (void)
347 if (!debug_level)
349 else if (!strcmp (debug_level, "none"))
350 opt.debug = 0;
351 else if (!strcmp (debug_level, "basic"))
352 opt.debug = DBG_ASSUAN_VALUE;
353 else if (!strcmp (debug_level, "advanced"))
354 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
355 else if (!strcmp (debug_level, "expert"))
356 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
357 |DBG_CACHE_VALUE);
358 else if (!strcmp (debug_level, "guru"))
359 opt.debug = ~0;
360 else
362 log_error (_("invalid debug-level `%s' given\n"), debug_level);
363 opt.debug = 0; /* Reset debugging, so that prior debug
364 statements won't have an undesired effect. */
367 if (opt.debug && !opt.verbose)
368 opt.verbose = 1;
369 if (opt.debug && opt.quiet)
370 opt.quiet = 0;
372 if (opt.debug & DBG_MPI_VALUE)
373 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
374 if (opt.debug & DBG_CRYPTO_VALUE )
375 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
376 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
380 /* Helper for cleanup to remove one socket with NAME. */
381 static void
382 remove_socket (char *name)
384 if (name && *name)
386 char *p;
388 remove (name);
389 p = strrchr (name, '/');
390 if (p)
392 *p = 0;
393 rmdir (name);
394 *p = '/';
396 *name = 0;
400 static void
401 cleanup (void)
403 remove_socket (socket_name);
404 remove_socket (socket_name_ssh);
409 /* Handle options which are allowed to be reset after program start.
410 Return true when the current option in PARGS could be handled and
411 false if not. As a special feature, passing a value of NULL for
412 PARGS, resets the options to the default. REREAD should be set
413 true if it is not the initial option parsing. */
414 static int
415 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
417 if (!pargs)
418 { /* reset mode */
419 opt.quiet = 0;
420 opt.verbose = 0;
421 opt.debug = 0;
422 opt.no_grab = 0;
423 opt.pinentry_program = NULL;
424 opt.pinentry_touch_file = NULL;
425 opt.scdaemon_program = NULL;
426 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
427 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
428 opt.max_cache_ttl = MAX_CACHE_TTL;
429 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
430 opt.enforce_passphrase_constraints = 0;
431 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
432 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
433 opt.check_passphrase_pattern = NULL;
434 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
435 opt.enable_passhrase_history = 0;
436 opt.ignore_cache_for_signing = 0;
437 opt.allow_mark_trusted = 0;
438 opt.disable_scdaemon = 0;
439 return 1;
442 switch (pargs->r_opt)
444 case oQuiet: opt.quiet = 1; break;
445 case oVerbose: opt.verbose++; break;
447 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
448 case oDebugAll: opt.debug = ~0; break;
449 case oDebugLevel: debug_level = pargs->r.ret_str; break;
451 case oLogFile:
452 if (!reread)
453 return 0; /* not handeld */
454 if (!current_logfile || !pargs->r.ret_str
455 || strcmp (current_logfile, pargs->r.ret_str))
457 log_set_file (pargs->r.ret_str);
458 xfree (current_logfile);
459 current_logfile = xtrystrdup (pargs->r.ret_str);
461 break;
463 case oNoGrab: opt.no_grab = 1; break;
465 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
466 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
467 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
468 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
470 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
471 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
472 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
473 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
475 case oEnforcePassphraseConstraints:
476 opt.enforce_passphrase_constraints=1;
477 break;
478 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
479 case oMinPassphraseNonalpha:
480 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
481 break;
482 case oCheckPassphrasePattern:
483 opt.check_passphrase_pattern = pargs->r.ret_str;
484 break;
485 case oMaxPassphraseDays:
486 opt.max_passphrase_days = pargs->r.ret_ulong;
487 break;
488 case oEnablePassphraseHistory:
489 opt.enable_passhrase_history = 1;
490 break;
492 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
494 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
496 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
498 default:
499 return 0; /* not handled */
502 return 1; /* handled */
506 /* The main entry point. */
508 main (int argc, char **argv )
510 ARGPARSE_ARGS pargs;
511 int orig_argc;
512 int may_coredump;
513 char **orig_argv;
514 FILE *configfp = NULL;
515 char *configname = NULL;
516 const char *shell;
517 unsigned configlineno;
518 int parse_debug = 0;
519 int default_config =1;
520 int greeting = 0;
521 int nogreeting = 0;
522 int pipe_server = 0;
523 int is_daemon = 0;
524 int nodetach = 0;
525 int csh_style = 0;
526 char *logfile = NULL;
527 int debug_wait = 0;
528 int gpgconf_list = 0;
529 gpg_error_t err;
530 const char *env_file_name = NULL;
533 set_strusage (my_strusage);
534 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
535 /* Please note that we may running SUID(ROOT), so be very CAREFUL
536 when adding any stuff between here and the call to INIT_SECMEM()
537 somewhere after the option parsing */
538 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
540 /* Make sure that our subsystems are ready. */
541 i18n_init ();
542 init_common_subsystems ();
545 /* Libgcrypt requires us to register the threading model first.
546 Note that this will also do the pth_init. */
547 gcry_threads_pth.init = fixed_gcry_pth_init;
548 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
549 if (err)
551 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
552 gpg_strerror (err));
556 /* Check that the libraries are suitable. Do it here because
557 the option parsing may need services of the library. */
558 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
560 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
561 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
564 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
565 assuan_set_assuan_log_stream (log_get_stream ());
566 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
567 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
569 setup_libgcrypt_logging ();
570 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
572 may_coredump = disable_core_dumps ();
574 /* Set default options. */
575 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
576 #ifdef HAVE_W32_SYSTEM
577 use_standard_socket = 1; /* Under Windows we always use a standard
578 socket. */
579 #endif
581 shell = getenv ("SHELL");
582 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
583 csh_style = 1;
585 opt.homedir = default_homedir ();
587 /* Record some of the original environment strings. */
588 opt.startup_display = getenv ("DISPLAY");
589 if (opt.startup_display)
590 opt.startup_display = xstrdup (opt.startup_display);
591 opt.startup_ttyname = ttyname (0);
592 if (opt.startup_ttyname)
593 opt.startup_ttyname = xstrdup (opt.startup_ttyname);
594 opt.startup_ttytype = getenv ("TERM");
595 if (opt.startup_ttytype)
596 opt.startup_ttytype = xstrdup (opt.startup_ttytype);
597 /* Fixme: Better use the locale function here. */
598 opt.startup_lc_ctype = getenv ("LC_CTYPE");
599 if (opt.startup_lc_ctype)
600 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
601 opt.startup_lc_messages = getenv ("LC_MESSAGES");
602 if (opt.startup_lc_messages)
603 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
604 opt.startup_xauthority = getenv ("XAUTHORITY");
605 if (opt.startup_xauthority)
606 opt.startup_xauthority = xstrdup (opt.startup_xauthority);
607 opt.startup_pinentry_user_data = getenv ("PINENTRY_USER_DATA");
608 if (opt.startup_pinentry_user_data)
609 opt.startup_pinentry_user_data = xstrdup (opt.startup_pinentry_user_data);
611 /* Check whether we have a config file on the commandline */
612 orig_argc = argc;
613 orig_argv = argv;
614 pargs.argc = &argc;
615 pargs.argv = &argv;
616 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
617 while (arg_parse( &pargs, opts))
619 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
620 parse_debug++;
621 else if (pargs.r_opt == oOptions)
622 { /* yes there is one, so we do not try the default one, but
623 read the option file when it is encountered at the
624 commandline */
625 default_config = 0;
627 else if (pargs.r_opt == oNoOptions)
628 default_config = 0; /* --no-options */
629 else if (pargs.r_opt == oHomedir)
630 opt.homedir = pargs.r.ret_str;
633 /* Initialize the secure memory. */
634 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
635 maybe_setuid = 0;
638 Now we are now working under our real uid
641 if (default_config)
642 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
644 argc = orig_argc;
645 argv = orig_argv;
646 pargs.argc = &argc;
647 pargs.argv = &argv;
648 pargs.flags= 1; /* do not remove the args */
649 next_pass:
650 if (configname)
652 configlineno = 0;
653 configfp = fopen (configname, "r");
654 if (!configfp)
656 if (default_config)
658 if( parse_debug )
659 log_info (_("NOTE: no default option file `%s'\n"),
660 configname );
662 else
664 log_error (_("option file `%s': %s\n"),
665 configname, strerror(errno) );
666 exit(2);
668 xfree (configname);
669 configname = NULL;
671 if (parse_debug && configname )
672 log_info (_("reading options from `%s'\n"), configname );
673 default_config = 0;
676 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
678 if (parse_rereadable_options (&pargs, 0))
679 continue; /* Already handled */
680 switch (pargs.r_opt)
682 case aGPGConfList: gpgconf_list = 1; break;
683 case aGPGConfTest: gpgconf_list = 2; break;
684 case oBatch: opt.batch=1; break;
686 case oDebugWait: debug_wait = pargs.r.ret_int; break;
688 case oOptions:
689 /* config files may not be nested (silently ignore them) */
690 if (!configfp)
692 xfree(configname);
693 configname = xstrdup(pargs.r.ret_str);
694 goto next_pass;
696 break;
697 case oNoGreeting: nogreeting = 1; break;
698 case oNoVerbose: opt.verbose = 0; break;
699 case oNoOptions: break; /* no-options */
700 case oHomedir: opt.homedir = pargs.r.ret_str; break;
701 case oNoDetach: nodetach = 1; break;
702 case oLogFile: logfile = pargs.r.ret_str; break;
703 case oCsh: csh_style = 1; break;
704 case oSh: csh_style = 0; break;
705 case oServer: pipe_server = 1; break;
706 case oDaemon: is_daemon = 1; break;
708 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
709 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
710 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
711 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
712 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
713 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
714 break;
716 case oUseStandardSocket: use_standard_socket = 1; break;
717 case oNoUseStandardSocket: use_standard_socket = 0; break;
719 case oFakedSystemTime:
721 time_t faked_time = isotime2epoch (pargs.r.ret_str);
722 if (faked_time == (time_t)(-1))
723 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
724 gnupg_set_time (faked_time, 0);
726 break;
728 case oKeepTTY: opt.keep_tty = 1; break;
729 case oKeepDISPLAY: opt.keep_display = 1; break;
731 case oSSHSupport: opt.ssh_support = 1; break;
732 case oWriteEnvFile:
733 if (pargs.r_type)
734 env_file_name = pargs.r.ret_str;
735 else
736 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
737 break;
739 default : pargs.err = configfp? 1:2; break;
742 if (configfp)
744 fclose( configfp );
745 configfp = NULL;
746 /* Keep a copy of the name so that it can be read on SIGHUP. */
747 config_filename = configname;
748 configname = NULL;
749 goto next_pass;
751 xfree (configname);
752 configname = NULL;
753 if (log_get_errorcount(0))
754 exit(2);
755 if (nogreeting )
756 greeting = 0;
758 if (greeting)
760 fprintf (stderr, "%s %s; %s\n",
761 strusage(11), strusage(13), strusage(14) );
762 fprintf (stderr, "%s\n", strusage(15) );
764 #ifdef IS_DEVELOPMENT_VERSION
765 /* We don't want to print it here because gpg-agent is useful of its
766 own and quite matured. */
767 /*log_info ("NOTE: this is a development version!\n");*/
768 #endif
770 set_debug ();
772 if (atexit (cleanup))
774 log_error ("atexit failed\n");
775 cleanup ();
776 exit (1);
779 initialize_module_call_pinentry ();
780 initialize_module_call_scd ();
781 initialize_module_trustlist ();
783 /* Try to create missing directories. */
784 create_directories ();
786 if (debug_wait && pipe_server)
788 log_debug ("waiting for debugger - my pid is %u .....\n",
789 (unsigned int)getpid());
790 gnupg_sleep (debug_wait);
791 log_debug ("... okay\n");
794 if (gpgconf_list == 2)
795 agent_exit (0);
796 if (gpgconf_list)
798 char *filename;
799 char *filename_esc;
801 /* List options and default values in the GPG Conf format. */
802 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
803 filename_esc = percent_escape (filename, NULL);
805 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
806 GC_OPT_FLAG_DEFAULT, filename_esc);
807 xfree (filename);
808 xfree (filename_esc);
810 printf ("verbose:%lu:\n"
811 "quiet:%lu:\n"
812 "debug-level:%lu:\"none:\n"
813 "log-file:%lu:\n",
814 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
815 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
816 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
817 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
818 printf ("default-cache-ttl:%lu:%d:\n",
819 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
820 printf ("default-cache-ttl-ssh:%lu:%d:\n",
821 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
822 printf ("max-cache-ttl:%lu:%d:\n",
823 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
824 printf ("max-cache-ttl-ssh:%lu:%d:\n",
825 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
826 printf ("enforce-passphrase-constraints:%lu:\n",
827 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
828 printf ("min-passphrase-len:%lu:%d:\n",
829 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
830 printf ("min-passphrase-nonalpha:%lu:%d:\n",
831 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
832 MIN_PASSPHRASE_NONALPHA);
833 printf ("check-passphrase-pattern:%lu:\n",
834 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
835 printf ("max-passphrase-days:%lu:%d:\n",
836 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
837 MAX_PASSPHRASE_DAYS);
838 printf ("enable-passphrase-history:%lu:\n",
839 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
840 printf ("no-grab:%lu:\n",
841 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
842 printf ("ignore-cache-for-signing:%lu:\n",
843 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
844 printf ("allow-mark-trusted:%lu:\n",
845 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
846 printf ("disable-scdaemon:%lu:\n",
847 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
849 agent_exit (0);
852 /* If this has been called without any options, we merely check
853 whether an agent is already running. We do this here so that we
854 don't clobber a logfile but print it directly to stderr. */
855 if (!pipe_server && !is_daemon)
857 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
858 check_for_running_agent (0, 0);
859 agent_exit (0);
862 #ifdef ENABLE_NLS
863 /* gpg-agent usually does not output any messages because it runs in
864 the background. For log files it is acceptable to have messages
865 always encoded in utf-8. We switch here to utf-8, so that
866 commands like --help still give native messages. It is far
867 easier to switch only once instead of for every message and it
868 actually helps when more then one thread is active (avoids an
869 extra copy step). */
870 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
871 #endif
873 /* Now start with logging to a file if this is desired. */
874 if (logfile)
876 log_set_file (logfile);
877 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
878 |JNLIB_LOG_WITH_TIME
879 |JNLIB_LOG_WITH_PID));
880 current_logfile = xstrdup (logfile);
881 assuan_set_assuan_log_stream (log_get_stream ());
884 /* Make sure that we have a default ttyname. */
885 if (!default_ttyname && ttyname (1))
886 default_ttyname = xstrdup (ttyname (1));
887 if (!default_ttytype && getenv ("TERM"))
888 default_ttytype = xstrdup (getenv ("TERM"));
891 if (pipe_server)
893 /* This is the simple pipe based server */
894 ctrl_t ctrl;
896 ctrl = xtrycalloc (1, sizeof *ctrl);
897 if (!ctrl)
899 log_error ("error allocating connection control data: %s\n",
900 strerror (errno) );
901 agent_exit (1);
903 agent_init_default_ctrl (ctrl);
904 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
905 agent_deinit_default_ctrl (ctrl);
906 xfree (ctrl);
908 else if (!is_daemon)
909 ; /* NOTREACHED */
910 else
911 { /* Regular server mode */
912 gnupg_fd_t fd;
913 gnupg_fd_t fd_ssh;
914 pid_t pid;
916 /* Remove the DISPLAY variable so that a pinentry does not
917 default to a specific display. There is still a default
918 display when gpg-agent was started using --display or a
919 client requested this using an OPTION command. Note, that we
920 don't do this when running in reverse daemon mode (i.e. when
921 exec the program given as arguments). */
922 #ifndef HAVE_W32_SYSTEM
923 if (!opt.keep_display && !argc)
924 unsetenv ("DISPLAY");
925 #endif
928 /* Create the sockets. */
929 socket_name = create_socket_name
930 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
931 if (opt.ssh_support)
932 socket_name_ssh = create_socket_name
933 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
935 fd = create_server_socket (socket_name, 0, &socket_nonce);
936 if (opt.ssh_support)
937 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
938 else
939 fd_ssh = GNUPG_INVALID_FD;
941 /* If we are going to exec a program in the parent, we record
942 the PID, so that the child may check whether the program is
943 still alive. */
944 if (argc)
945 parent_pid = getpid ();
947 fflush (NULL);
948 #ifdef HAVE_W32_SYSTEM
949 pid = getpid ();
950 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
951 #else /*!HAVE_W32_SYSTEM*/
952 pid = fork ();
953 if (pid == (pid_t)-1)
955 log_fatal ("fork failed: %s\n", strerror (errno) );
956 exit (1);
958 else if (pid)
959 { /* We are the parent */
960 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
962 close (fd);
964 /* Create the info string: <name>:<pid>:<protocol_version> */
965 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
966 socket_name, (ulong)pid ) < 0)
968 log_error ("out of core\n");
969 kill (pid, SIGTERM);
970 exit (1);
972 if (opt.ssh_support)
974 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
975 socket_name_ssh) < 0)
977 log_error ("out of core\n");
978 kill (pid, SIGTERM);
979 exit (1);
981 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
982 pid) < 0)
984 log_error ("out of core\n");
985 kill (pid, SIGTERM);
986 exit (1);
990 *socket_name = 0; /* Don't let cleanup() remove the socket -
991 the child should do this from now on */
992 if (opt.ssh_support)
993 *socket_name_ssh = 0;
995 if (env_file_name)
997 FILE *fp;
999 fp = fopen (env_file_name, "w");
1000 if (!fp)
1001 log_error (_("error creating `%s': %s\n"),
1002 env_file_name, strerror (errno));
1003 else
1005 fputs (infostr, fp);
1006 putc ('\n', fp);
1007 if (opt.ssh_support)
1009 fputs (infostr_ssh_sock, fp);
1010 putc ('\n', fp);
1011 fputs (infostr_ssh_pid, fp);
1012 putc ('\n', fp);
1014 fclose (fp);
1019 if (argc)
1020 { /* Run the program given on the commandline. */
1021 if (putenv (infostr))
1023 log_error ("failed to set environment: %s\n",
1024 strerror (errno) );
1025 kill (pid, SIGTERM );
1026 exit (1);
1028 if (opt.ssh_support && putenv (infostr_ssh_sock))
1030 log_error ("failed to set environment: %s\n",
1031 strerror (errno) );
1032 kill (pid, SIGTERM );
1033 exit (1);
1035 if (opt.ssh_support && putenv (infostr_ssh_pid))
1037 log_error ("failed to set environment: %s\n",
1038 strerror (errno) );
1039 kill (pid, SIGTERM );
1040 exit (1);
1042 execvp (argv[0], argv);
1043 log_error ("failed to run the command: %s\n", strerror (errno));
1044 kill (pid, SIGTERM);
1045 exit (1);
1047 else
1049 /* Print the environment string, so that the caller can use
1050 shell's eval to set it */
1051 if (csh_style)
1053 *strchr (infostr, '=') = ' ';
1054 printf ("setenv %s\n", infostr);
1055 if (opt.ssh_support)
1057 *strchr (infostr_ssh_sock, '=') = ' ';
1058 printf ("setenv %s\n", infostr_ssh_sock);
1059 *strchr (infostr_ssh_pid, '=') = ' ';
1060 printf ("setenv %s\n", infostr_ssh_pid);
1063 else
1065 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1066 if (opt.ssh_support)
1068 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1069 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1072 xfree (infostr);
1073 if (opt.ssh_support)
1075 xfree (infostr_ssh_sock);
1076 xfree (infostr_ssh_pid);
1078 exit (0);
1080 /*NOTREACHED*/
1081 } /* End parent */
1084 This is the child
1087 /* Detach from tty and put process into a new session */
1088 if (!nodetach )
1090 int i;
1091 unsigned int oldflags;
1093 /* Close stdin, stdout and stderr unless it is the log stream */
1094 for (i=0; i <= 2; i++)
1096 if (!log_test_fd (i) && i != fd )
1098 if ( ! close (i)
1099 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1101 log_error ("failed to open `%s': %s\n",
1102 "/dev/null", strerror (errno));
1103 cleanup ();
1104 exit (1);
1108 if (setsid() == -1)
1110 log_error ("setsid() failed: %s\n", strerror(errno) );
1111 cleanup ();
1112 exit (1);
1115 log_get_prefix (&oldflags);
1116 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1117 opt.running_detached = 1;
1120 if (chdir("/"))
1122 log_error ("chdir to / failed: %s\n", strerror (errno));
1123 exit (1);
1127 struct sigaction sa;
1129 sa.sa_handler = SIG_IGN;
1130 sigemptyset (&sa.sa_mask);
1131 sa.sa_flags = 0;
1132 sigaction (SIGPIPE, &sa, NULL);
1134 #endif /*!HAVE_W32_SYSTEM*/
1136 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1137 assuan_sock_close (fd);
1140 return 0;
1144 void
1145 agent_exit (int rc)
1147 /*FIXME: update_random_seed_file();*/
1148 #if 1
1149 /* at this time a bit annoying */
1150 if (opt.debug & DBG_MEMSTAT_VALUE)
1152 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1153 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1155 if (opt.debug)
1156 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1157 #endif
1158 gcry_control (GCRYCTL_TERM_SECMEM );
1159 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1160 exit (rc);
1163 static void
1164 agent_init_default_ctrl (ctrl_t ctrl)
1166 /* Note we ignore malloc errors because we can't do much about it
1167 and the request will fail anyway shortly after this
1168 initialization. */
1169 if (ctrl->display)
1170 xfree (ctrl->display);
1171 ctrl->display = default_display? xtrystrdup (default_display) : NULL;
1173 if (ctrl->ttyname)
1174 xfree (ctrl->ttyname);
1175 ctrl->ttyname = default_ttyname? xtrystrdup (default_ttyname) : NULL;
1177 if (ctrl->ttytype)
1178 xfree (ctrl->ttytype);
1179 ctrl->ttytype = default_ttytype? xtrystrdup (default_ttytype) : NULL;
1181 if (ctrl->lc_ctype)
1182 xfree (ctrl->lc_ctype);
1183 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1185 if (ctrl->lc_messages)
1186 xfree (ctrl->lc_messages);
1187 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1188 /**/ : NULL;
1190 if (ctrl->xauthority)
1191 xfree (ctrl->xauthority);
1192 ctrl->xauthority = default_xauthority? xtrystrdup (default_xauthority)
1193 /**/: NULL;
1195 if (ctrl->pinentry_user_data)
1196 xfree (ctrl->pinentry_user_data);
1197 ctrl->pinentry_user_data = NULL;
1201 static void
1202 agent_deinit_default_ctrl (ctrl_t ctrl)
1204 if (ctrl->display)
1205 xfree (ctrl->display);
1206 if (ctrl->ttyname)
1207 xfree (ctrl->ttyname);
1208 if (ctrl->ttytype)
1209 xfree (ctrl->ttytype);
1210 if (ctrl->lc_ctype)
1211 xfree (ctrl->lc_ctype);
1212 if (ctrl->lc_messages)
1213 xfree (ctrl->lc_messages);
1214 if (ctrl->xauthority)
1215 xfree (ctrl->xauthority);
1216 if (ctrl->pinentry_user_data)
1217 xfree (ctrl->pinentry_user_data);
1220 /* Reread parts of the configuration. Note, that this function is
1221 obviously not thread-safe and should only be called from the PTH
1222 signal handler.
1224 Fixme: Due to the way the argument parsing works, we create a
1225 memory leak here for all string type arguments. There is currently
1226 no clean way to tell whether the memory for the argument has been
1227 allocated or points into the process' original arguments. Unless
1228 we have a mechanism to tell this, we need to live on with this. */
1229 static void
1230 reread_configuration (void)
1232 ARGPARSE_ARGS pargs;
1233 FILE *fp;
1234 unsigned int configlineno = 0;
1235 int dummy;
1237 if (!config_filename)
1238 return; /* No config file. */
1240 fp = fopen (config_filename, "r");
1241 if (!fp)
1243 log_error (_("option file `%s': %s\n"),
1244 config_filename, strerror(errno) );
1245 return;
1248 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1250 memset (&pargs, 0, sizeof pargs);
1251 dummy = 0;
1252 pargs.argc = &dummy;
1253 pargs.flags = 1; /* do not remove the args */
1254 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1256 if (pargs.r_opt < -1)
1257 pargs.err = 1; /* Print a warning. */
1258 else /* Try to parse this option - ignore unchangeable ones. */
1259 parse_rereadable_options (&pargs, 1);
1261 fclose (fp);
1262 set_debug ();
1266 /* Return the file name of the socket we are using for native
1267 requests. */
1268 const char *
1269 get_agent_socket_name (void)
1271 const char *s = socket_name;
1273 return (s && *s)? s : NULL;
1276 /* Return the file name of the socket we are using for SSH
1277 requests. */
1278 const char *
1279 get_agent_ssh_socket_name (void)
1281 const char *s = socket_name_ssh;
1283 return (s && *s)? s : NULL;
1287 /* Under W32, this function returns the handle of the scdaemon
1288 notification event. Calling it the first time creates that
1289 event. */
1290 #ifdef HAVE_W32_SYSTEM
1291 void *
1292 get_agent_scd_notify_event (void)
1294 static HANDLE the_event;
1296 if (!the_event)
1298 HANDLE h, h2;
1299 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1301 /* We need to use manual reset evet object due to the way our
1302 w32-pth wait function works: If we would use an automatic
1303 reset event we are not able to figure out which handle has
1304 been signaled because at the time we single out the signaled
1305 handles using WFSO the event has already been reset due to
1306 the WFMO. */
1307 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1308 if (!h)
1309 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1310 else if (!DuplicateHandle (GetCurrentProcess(), h,
1311 GetCurrentProcess(), &h2,
1312 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1314 log_error ("setting syncronize for scd notify event failed: %s\n",
1315 w32_strerror (-1) );
1316 CloseHandle (h);
1318 else
1320 CloseHandle (h);
1321 the_event = h2;
1325 log_debug ("returning notify handle %p\n", the_event);
1326 return the_event;
1328 #endif /*HAVE_W32_SYSTEM*/
1332 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1333 true using STANDARD_NAME in the home directory or if given as
1334 false from the mkdir type name TEMPLATE. In the latter case a
1335 unique name in a unique new directory will be created. In both
1336 cases check for valid characters as well as against a maximum
1337 allowed length for a unix domain socket is done. The function
1338 terminates the process in case of an error. Returns: Pointer to an
1339 allocated string with the absolute name of the socket used. */
1340 static char *
1341 create_socket_name (char *standard_name, char *template)
1343 char *name, *p;
1345 if (use_standard_socket)
1346 name = make_filename (opt.homedir, standard_name, NULL);
1347 else
1349 name = xstrdup (template);
1350 p = strrchr (name, '/');
1351 if (!p)
1352 BUG ();
1353 *p = 0;
1354 if (!mkdtemp (name))
1356 log_error (_("can't create directory `%s': %s\n"),
1357 name, strerror (errno));
1358 agent_exit (2);
1360 *p = '/';
1363 if (strchr (name, PATHSEP_C))
1365 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1366 agent_exit (2);
1368 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1370 log_error (_("name of socket too long\n"));
1371 agent_exit (2);
1373 return name;
1378 /* Create a Unix domain socket with NAME. Returns the file descriptor
1379 or terminates the process in case of an error. Not that this
1380 function needs to be used for the regular socket first and only
1381 then for the ssh socket. */
1382 static gnupg_fd_t
1383 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1385 struct sockaddr_un *serv_addr;
1386 socklen_t len;
1387 gnupg_fd_t fd;
1388 int rc;
1390 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1391 if (fd == ASSUAN_INVALID_FD)
1393 log_error (_("can't create socket: %s\n"), strerror (errno));
1394 agent_exit (2);
1397 serv_addr = xmalloc (sizeof (*serv_addr));
1398 memset (serv_addr, 0, sizeof *serv_addr);
1399 serv_addr->sun_family = AF_UNIX;
1400 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1402 log_error (_("socket name `%s' is too long\n"), name);
1403 agent_exit (2);
1405 strcpy (serv_addr->sun_path, name);
1406 len = (offsetof (struct sockaddr_un, sun_path)
1407 + strlen (serv_addr->sun_path) + 1);
1409 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1410 if (use_standard_socket && rc == -1 && errno == EADDRINUSE)
1412 /* Check whether a gpg-agent is already running on the standard
1413 socket. We do this test only if this is not the ssh socket.
1414 For ssh we assume that a test for gpg-agent has already been
1415 done and reuse the requested ssh socket. Testing the
1416 ssh-socket is not possible because at this point, though we
1417 know the new Assuan socket, the Assuan server and thus the
1418 ssh-agent server is not yet operational. This would lead to
1419 a hang. */
1420 if (!is_ssh && !check_for_running_agent (1, 1))
1422 log_error (_("a gpg-agent is already running - "
1423 "not starting a new one\n"));
1424 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1425 assuan_sock_close (fd);
1426 agent_exit (2);
1428 remove (name);
1429 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1431 if (rc != -1
1432 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1433 log_error (_("error getting nonce for the socket\n"));
1434 if (rc == -1)
1436 /* We use gpg_strerror here because it allows us to get strings
1437 for some W32 socket error codes. */
1438 log_error (_("error binding socket to `%s': %s\n"),
1439 serv_addr->sun_path,
1440 gpg_strerror (gpg_error_from_errno (errno)));
1442 assuan_sock_close (fd);
1443 if (use_standard_socket)
1444 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1445 agent_exit (2);
1448 if (listen (FD2INT(fd), 5 ) == -1)
1450 log_error (_("listen() failed: %s\n"), strerror (errno));
1451 assuan_sock_close (fd);
1452 agent_exit (2);
1455 if (opt.verbose)
1456 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1458 return fd;
1462 /* Check that the directory for storing the private keys exists and
1463 create it if not. This function won't fail as it is only a
1464 convenience function and not strictly necessary. */
1465 static void
1466 create_private_keys_directory (const char *home)
1468 char *fname;
1469 struct stat statbuf;
1471 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1472 if (stat (fname, &statbuf) && errno == ENOENT)
1474 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1475 if (!CreateDirectory (fname, NULL))
1476 log_error (_("can't create directory `%s': %s\n"),
1477 fname, w32_strerror (-1) );
1478 #else
1479 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1480 log_error (_("can't create directory `%s': %s\n"),
1481 fname, strerror (errno) );
1482 #endif
1483 else if (!opt.quiet)
1484 log_info (_("directory `%s' created\n"), fname);
1486 xfree (fname);
1489 /* Create the directory only if the supplied directory name is the
1490 same as the default one. This way we avoid to create arbitrary
1491 directories when a non-default home directory is used. To cope
1492 with HOME, we compare only the suffix if we see that the default
1493 homedir does start with a tilde. We don't stop here in case of
1494 problems because other functions will throw an error anyway.*/
1495 static void
1496 create_directories (void)
1498 struct stat statbuf;
1499 const char *defhome = standard_homedir ();
1500 char *home;
1502 home = make_filename (opt.homedir, NULL);
1503 if ( stat (home, &statbuf) )
1505 if (errno == ENOENT)
1507 if (
1508 #ifdef HAVE_W32_SYSTEM
1509 ( !compare_filenames (home, defhome) )
1510 #else
1511 (*defhome == '~'
1512 && (strlen (home) >= strlen (defhome+1)
1513 && !strcmp (home + strlen(home)
1514 - strlen (defhome+1), defhome+1)))
1515 || (*defhome != '~' && !strcmp (home, defhome) )
1516 #endif
1519 #ifdef HAVE_W32_SYSTEM
1520 if (!CreateDirectory (home, NULL))
1521 log_error (_("can't create directory `%s': %s\n"),
1522 home, w32_strerror (-1) );
1523 #else
1524 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1525 log_error (_("can't create directory `%s': %s\n"),
1526 home, strerror (errno) );
1527 #endif
1528 else
1530 if (!opt.quiet)
1531 log_info (_("directory `%s' created\n"), home);
1532 create_private_keys_directory (home);
1536 else
1537 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1539 else if ( !S_ISDIR(statbuf.st_mode))
1541 log_error (_("can't use `%s' as home directory\n"), home);
1543 else /* exists and is a directory. */
1545 create_private_keys_directory (home);
1547 xfree (home);
1552 /* This is the worker for the ticker. It is called every few seconds
1553 and may only do fast operations. */
1554 static void
1555 handle_tick (void)
1557 static time_t last_minute;
1559 if (!last_minute)
1560 last_minute = time (NULL);
1562 /* Check whether the scdaemon has died and cleanup in this case. */
1563 agent_scd_check_aliveness ();
1565 /* If we are running as a child of another process, check whether
1566 the parent is still alive and shutdown if not. */
1567 #ifndef HAVE_W32_SYSTEM
1568 if (parent_pid != (pid_t)(-1))
1570 if (kill (parent_pid, 0))
1572 shutdown_pending = 2;
1573 log_info ("parent process died - shutting down\n");
1574 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1575 cleanup ();
1576 agent_exit (0);
1579 #endif /*HAVE_W32_SYSTEM*/
1581 /* Code to be run every minute. */
1582 if (last_minute + 60 <= time (NULL))
1584 check_own_socket ();
1585 last_minute = time (NULL);
1591 /* A global function which allows us to call the reload stuff from
1592 other places too. This is only used when build for W32. */
1593 void
1594 agent_sighup_action (void)
1596 log_info ("SIGHUP received - "
1597 "re-reading configuration and flushing cache\n");
1598 agent_flush_cache ();
1599 reread_configuration ();
1600 agent_reload_trustlist ();
1604 static void
1605 agent_sigusr2_action (void)
1607 if (opt.verbose)
1608 log_info ("SIGUSR2 received - updating card event counter\n");
1609 /* Nothing to check right now. We only increment a counter. */
1610 bump_card_eventcounter ();
1614 static void
1615 handle_signal (int signo)
1617 switch (signo)
1619 #ifndef HAVE_W32_SYSTEM
1620 case SIGHUP:
1621 agent_sighup_action ();
1622 break;
1624 case SIGUSR1:
1625 log_info ("SIGUSR1 received - printing internal information:\n");
1626 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1627 agent_query_dump_state ();
1628 agent_scd_dump_state ();
1629 break;
1631 case SIGUSR2:
1632 agent_sigusr2_action ();
1633 break;
1635 case SIGTERM:
1636 if (!shutdown_pending)
1637 log_info ("SIGTERM received - shutting down ...\n");
1638 else
1639 log_info ("SIGTERM received - still %ld running threads\n",
1640 pth_ctrl( PTH_CTRL_GETTHREADS ));
1641 shutdown_pending++;
1642 if (shutdown_pending > 2)
1644 log_info ("shutdown forced\n");
1645 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1646 cleanup ();
1647 agent_exit (0);
1649 break;
1651 case SIGINT:
1652 log_info ("SIGINT received - immediate shutdown\n");
1653 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1654 cleanup ();
1655 agent_exit (0);
1656 break;
1657 #endif
1658 default:
1659 log_info ("signal %d received - no action defined\n", signo);
1664 /* Check the nonce on a new connection. This is a NOP unless we we
1665 are using our Unix domain socket emulation under Windows. */
1666 static int
1667 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1669 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1671 log_info (_("error reading nonce on fd %d: %s\n"),
1672 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1673 assuan_sock_close (ctrl->thread_startup.fd);
1674 xfree (ctrl);
1675 return -1;
1677 else
1678 return 0;
1682 /* This is the standard connection thread's main function. */
1683 static void *
1684 start_connection_thread (void *arg)
1686 ctrl_t ctrl = arg;
1688 if (check_nonce (ctrl, &socket_nonce))
1689 return NULL;
1691 agent_init_default_ctrl (ctrl);
1692 if (opt.verbose)
1693 log_info (_("handler 0x%lx for fd %d started\n"),
1694 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1696 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1697 if (opt.verbose)
1698 log_info (_("handler 0x%lx for fd %d terminated\n"),
1699 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1701 agent_deinit_default_ctrl (ctrl);
1702 xfree (ctrl);
1703 return NULL;
1707 /* This is the ssh connection thread's main function. */
1708 static void *
1709 start_connection_thread_ssh (void *arg)
1711 ctrl_t ctrl = arg;
1713 if (check_nonce (ctrl, &socket_nonce_ssh))
1714 return NULL;
1716 agent_init_default_ctrl (ctrl);
1717 if (opt.verbose)
1718 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1719 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1721 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1722 if (opt.verbose)
1723 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1724 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1726 agent_deinit_default_ctrl (ctrl);
1727 xfree (ctrl);
1728 return NULL;
1732 /* Connection handler loop. Wait for connection requests and spawn a
1733 thread after accepting a connection. */
1734 static void
1735 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1737 pth_attr_t tattr;
1738 pth_event_t ev, time_ev;
1739 sigset_t sigs;
1740 int signo;
1741 struct sockaddr_un paddr;
1742 socklen_t plen;
1743 fd_set fdset, read_fdset;
1744 int ret;
1745 gnupg_fd_t fd;
1746 int nfd;
1748 tattr = pth_attr_new();
1749 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1750 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1752 #ifndef HAVE_W32_SYSTEM /* fixme */
1753 /* Make sure that the signals we are going to handle are not blocked
1754 and create an event object for them. We also set the default
1755 action to ignore because we use an Pth event to get notified
1756 about signals. This avoids that the default action is taken in
1757 case soemthing goes wrong within Pth. The problem might also be
1758 a Pth bug. */
1759 sigemptyset (&sigs );
1761 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1762 struct sigaction sa;
1763 int i;
1765 for (i=0; i < DIM (mysigs); i++)
1767 sigemptyset (&sa.sa_mask);
1768 sa.sa_handler = SIG_IGN;
1769 sa.sa_flags = 0;
1770 sigaction (mysigs[i], &sa, NULL);
1772 sigaddset (&sigs, mysigs[i]);
1776 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1777 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1778 #else
1779 # ifdef PTH_EVENT_HANDLE
1780 sigs = 0;
1781 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1782 signo = 0;
1783 # else
1784 /* Use a dummy event. */
1785 sigs = 0;
1786 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1787 # endif
1788 #endif
1789 time_ev = NULL;
1791 FD_ZERO (&fdset);
1792 FD_SET (FD2INT (listen_fd), &fdset);
1793 nfd = FD2INT (listen_fd);
1794 if (listen_fd_ssh != GNUPG_INVALID_FD)
1796 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1797 if (FD2INT (listen_fd_ssh) > nfd)
1798 nfd = FD2INT (listen_fd_ssh);
1801 for (;;)
1803 /* Make sure that our signals are not blocked. */
1804 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1806 /* Shutdown test. */
1807 if (shutdown_pending)
1809 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1810 break; /* ready */
1812 /* Do not accept new connections but keep on running the
1813 loop to cope with the timer events. */
1814 FD_ZERO (&fdset);
1817 /* Create a timeout event if needed. To help with power saving
1818 we syncronize the ticks to the next full second. */
1819 if (!time_ev)
1821 pth_time_t nexttick;
1823 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1824 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
1826 nexttick.tv_sec++;
1827 nexttick.tv_usec = 0;
1829 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1832 /* POSIX says that fd_set should be implemented as a structure,
1833 thus a simple assignment is fine to copy the entire set. */
1834 read_fdset = fdset;
1836 if (time_ev)
1837 pth_event_concat (ev, time_ev, NULL);
1838 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1839 if (time_ev)
1840 pth_event_isolate (time_ev);
1842 if (ret == -1)
1844 if (pth_event_occurred (ev)
1845 || (time_ev && pth_event_occurred (time_ev)))
1847 if (pth_event_occurred (ev))
1849 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1850 agent_sigusr2_action ();
1851 #else
1852 handle_signal (signo);
1853 #endif
1855 if (time_ev && pth_event_occurred (time_ev))
1857 pth_event_free (time_ev, PTH_FREE_ALL);
1858 time_ev = NULL;
1859 handle_tick ();
1861 continue;
1863 log_error (_("pth_select failed: %s - waiting 1s\n"),
1864 strerror (errno));
1865 pth_sleep (1);
1866 continue;
1869 if (pth_event_occurred (ev))
1871 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1872 agent_sigusr2_action ();
1873 #else
1874 handle_signal (signo);
1875 #endif
1878 if (time_ev && pth_event_occurred (time_ev))
1880 pth_event_free (time_ev, PTH_FREE_ALL);
1881 time_ev = NULL;
1882 handle_tick ();
1886 /* We now might create new threads and because we don't want any
1887 signals (as we are handling them here) to be delivered to a
1888 new thread. Thus we need to block those signals. */
1889 pth_sigmask (SIG_BLOCK, &sigs, NULL);
1891 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
1893 ctrl_t ctrl;
1895 plen = sizeof paddr;
1896 fd = INT2FD (pth_accept (FD2INT(listen_fd),
1897 (struct sockaddr *)&paddr, &plen));
1898 if (fd == GNUPG_INVALID_FD)
1900 log_error ("accept failed: %s\n", strerror (errno));
1902 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1904 log_error ("error allocating connection control data: %s\n",
1905 strerror (errno) );
1906 assuan_sock_close (fd);
1908 else
1910 char threadname[50];
1912 snprintf (threadname, sizeof threadname-1,
1913 "conn fd=%d (gpg)", FD2INT(fd));
1914 threadname[sizeof threadname -1] = 0;
1915 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1916 ctrl->thread_startup.fd = fd;
1917 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1919 log_error ("error spawning connection handler: %s\n",
1920 strerror (errno) );
1921 assuan_sock_close (fd);
1922 xfree (ctrl);
1925 fd = GNUPG_INVALID_FD;
1928 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
1929 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
1931 ctrl_t ctrl;
1933 plen = sizeof paddr;
1934 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
1935 (struct sockaddr *)&paddr, &plen));
1936 if (fd == GNUPG_INVALID_FD)
1938 log_error ("accept failed for ssh: %s\n", strerror (errno));
1940 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1942 log_error ("error allocating connection control data: %s\n",
1943 strerror (errno) );
1944 assuan_sock_close (fd);
1946 else
1948 char threadname[50];
1950 agent_init_default_ctrl (ctrl);
1951 snprintf (threadname, sizeof threadname-1,
1952 "conn fd=%d (ssh)", FD2INT(fd));
1953 threadname[sizeof threadname -1] = 0;
1954 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1955 ctrl->thread_startup.fd = fd;
1956 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
1958 log_error ("error spawning ssh connection handler: %s\n",
1959 strerror (errno) );
1960 assuan_sock_close (fd);
1961 xfree (ctrl);
1964 fd = GNUPG_INVALID_FD;
1968 pth_event_free (ev, PTH_FREE_ALL);
1969 if (time_ev)
1970 pth_event_free (time_ev, PTH_FREE_ALL);
1971 cleanup ();
1972 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1977 /* Helper for check_own_socket. */
1978 static int
1979 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
1981 membuf_t *mb = opaque;
1982 put_membuf (mb, buffer, length);
1983 return 0;
1987 /* The thread running the actual check. We need to run this in a
1988 separate thread so that check_own_thread can be called from the
1989 timer tick. */
1990 static void *
1991 check_own_socket_thread (void *arg)
1993 int rc;
1994 char *sockname = arg;
1995 assuan_context_t ctx;
1996 membuf_t mb;
1997 char *buffer;
1999 check_own_socket_running++;
2001 rc = assuan_socket_connect (&ctx, sockname, (pid_t)(-1));
2002 xfree (sockname);
2003 if (rc)
2005 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2006 goto leave;
2009 init_membuf (&mb, 100);
2010 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2011 NULL, NULL, NULL, NULL);
2012 put_membuf (&mb, "", 1);
2013 buffer = get_membuf (&mb, NULL);
2014 if (rc || !buffer)
2016 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2017 "GETINFO pid", gpg_strerror (rc));
2018 rc = 1;
2020 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2022 log_error ("socket is now serviced by another server\n");
2023 rc = 1;
2025 else if (opt.verbose > 1)
2026 log_error ("socket is still served by this server\n");
2028 xfree (buffer);
2029 assuan_disconnect (ctx);
2031 leave:
2032 if (rc)
2034 /* We may not remove the socket as it is now in use by another
2035 server. Setting the name to empty does this. */
2036 if (socket_name)
2037 *socket_name = 0;
2038 if (socket_name_ssh)
2039 *socket_name_ssh = 0;
2040 shutdown_pending = 2;
2041 log_info ("this process is useless - shutting down\n");
2043 check_own_socket_running--;
2044 return NULL;
2048 /* Check whether we are still listening on our own socket. In case
2049 another gpg-agent process started after us has taken ownership of
2050 our socket, we woul linger around without any real taks. Thus we
2051 better check once in a while whether we are really needed. */
2052 static void
2053 check_own_socket (void)
2055 char *sockname;
2056 pth_attr_t tattr;
2058 if (!use_standard_socket)
2059 return; /* This check makes only sense in standard socket mode. */
2061 if (check_own_socket_running || shutdown_pending)
2062 return; /* Still running or already shutting down. */
2064 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2065 if (!sockname)
2066 return; /* Out of memory. */
2068 tattr = pth_attr_new();
2069 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2070 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2071 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2073 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2074 log_error ("error spawning check_own_socket_thread: %s\n",
2075 strerror (errno) );
2076 pth_attr_destroy (tattr);
2081 /* Figure out whether an agent is available and running. Prints an
2082 error if not. If SILENT is true, no messages are printed. Usually
2083 started with MODE 0. Returns 0 if the agent is running. */
2084 static int
2085 check_for_running_agent (int silent, int mode)
2087 int rc;
2088 char *infostr, *p;
2089 assuan_context_t ctx;
2090 int prot, pid;
2092 if (!mode)
2094 infostr = getenv ("GPG_AGENT_INFO");
2095 if (!infostr || !*infostr)
2097 if (!check_for_running_agent (silent, 1))
2098 return 0; /* Okay, its running on the standard socket. */
2099 if (!silent)
2100 log_error (_("no gpg-agent running in this session\n"));
2101 return -1;
2104 infostr = xstrdup (infostr);
2105 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2107 xfree (infostr);
2108 if (!check_for_running_agent (silent, 1))
2109 return 0; /* Okay, its running on the standard socket. */
2110 if (!silent)
2111 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2112 return -1;
2115 *p++ = 0;
2116 pid = atoi (p);
2117 while (*p && *p != PATHSEP_C)
2118 p++;
2119 prot = *p? atoi (p+1) : 0;
2120 if (prot != 1)
2122 xfree (infostr);
2123 if (!silent)
2124 log_error (_("gpg-agent protocol version %d is not supported\n"),
2125 prot);
2126 if (!check_for_running_agent (silent, 1))
2127 return 0; /* Okay, its running on the standard socket. */
2128 return -1;
2131 else /* MODE != 0 */
2133 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2134 pid = (pid_t)(-1);
2138 rc = assuan_socket_connect (&ctx, infostr, pid);
2139 xfree (infostr);
2140 if (rc)
2142 if (!mode && !check_for_running_agent (silent, 1))
2143 return 0; /* Okay, its running on the standard socket. */
2145 if (!mode && !silent)
2146 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2147 return -1;
2150 if (!opt.quiet && !silent)
2151 log_info ("gpg-agent running and available\n");
2153 assuan_disconnect (ctx);
2154 return 0;