2008-02-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / agent / gpg-agent.c
blob5ac951c23a6a107b6277520e6f01944c3e156258
1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007 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 { oDisplay, "display", 2, "@" },
145 { oTTYname, "ttyname", 2, "@" },
146 { oTTYtype, "ttytype", 2, "@" },
147 { oLCctype, "lc-ctype", 2, "@" },
148 { oLCmessages, "lc-messages", 2, "@" },
149 { oXauthority, "xauthority", 2, "@" },
150 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
151 { oKeepDISPLAY, "keep-display",
152 0, N_("ignore requests to change the X display")},
154 { oDefCacheTTL, "default-cache-ttl", 4,
155 N_("|N|expire cached PINs after N seconds")},
156 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
157 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
158 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
160 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
161 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
162 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
163 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
164 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
165 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
167 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
168 N_("do not use the PIN cache when signing")},
169 { oAllowMarkTrusted, "allow-mark-trusted", 0,
170 N_("allow clients to mark keys as \"trusted\"")},
171 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
172 N_("allow presetting passphrase")},
173 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
174 { oWriteEnvFile, "write-env-file", 2|8,
175 N_("|FILE|write environment settings also to FILE")},
180 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
181 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
182 #define MAX_CACHE_TTL (120*60) /* 2 hours */
183 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
184 #define MIN_PASSPHRASE_LEN (8)
185 #define MIN_PASSPHRASE_NONALPHA (1)
186 #define MAX_PASSPHRASE_DAYS (0)
188 /* The timer tick used for housekeeping stuff. For Windows we use a
189 longer period as the SetWaitableTimer seems to signal earlier than
190 the 2 seconds. */
191 #ifdef HAVE_W32_SYSTEM
192 #define TIMERTICK_INTERVAL (4)
193 #else
194 #define TIMERTICK_INTERVAL (2) /* Seconds. */
195 #endif
197 /* flag to indicate that a shutdown was requested */
198 static int shutdown_pending;
201 /* It is possible that we are currently running under setuid permissions */
202 static int maybe_setuid = 1;
204 /* Name of the communication socket used for native gpg-agent requests. */
205 static char *socket_name;
207 /* Name of the communication socket used for ssh-agent-emulation. */
208 static char *socket_name_ssh;
210 /* We need to keep track of the server's nonces (these are dummies for
211 POSIX systems). */
212 static assuan_sock_nonce_t socket_nonce;
213 static assuan_sock_nonce_t socket_nonce_ssh;
216 /* Default values for options passed to the pinentry. */
217 static char *default_display;
218 static char *default_ttyname;
219 static char *default_ttytype;
220 static char *default_lc_ctype;
221 static char *default_lc_messages;
222 static char *default_xauthority;
224 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
225 static char *config_filename;
227 /* Helper to implement --debug-level */
228 static const char *debug_level;
230 /* Keep track of the current log file so that we can avoid updating
231 the log file after a SIGHUP if it didn't changed. Malloced. */
232 static char *current_logfile;
234 /* The handle_tick() function may test whether a parent is still
235 running. We record the PID of the parent here or -1 if it should be
236 watched. */
237 static pid_t parent_pid = (pid_t)(-1);
241 Local prototypes.
244 static char *create_socket_name (int use_standard_socket,
245 char *standard_name, char *template);
246 static gnupg_fd_t create_server_socket (int is_standard_name, char *name,
247 int is_ssh,
248 assuan_sock_nonce_t *nonce);
249 static void create_directories (void);
251 static void agent_init_default_ctrl (ctrl_t ctrl);
252 static void agent_deinit_default_ctrl (ctrl_t ctrl);
254 static void handle_connections (gnupg_fd_t listen_fd,
255 gnupg_fd_t listen_fd_ssh);
256 static int check_for_running_agent (int silent, int mode);
258 /* Pth wrapper function definitions. */
259 GCRY_THREAD_OPTION_PTH_IMPL;
260 static int fixed_gcry_pth_init (void)
262 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
269 Functions.
273 static const char *
274 my_strusage (int level)
276 const char *p;
277 switch (level)
279 case 11: p = "gpg-agent (GnuPG)";
280 break;
281 case 13: p = VERSION; break;
282 case 17: p = PRINTABLE_OS_NAME; break;
283 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
284 break;
285 case 1:
286 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
287 break;
288 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
289 "Secret key management for GnuPG\n");
290 break;
292 default: p = NULL;
294 return p;
299 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
300 only the active debug flags are propagated to the subsystems. With
301 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
302 all flags already set. Note that we don't fail here, because it is
303 important to keep gpg-agent running even after re-reading the
304 options due to a SIGHUP. */
305 static void
306 set_debug (void)
308 if (!debug_level)
310 else if (!strcmp (debug_level, "none"))
311 opt.debug = 0;
312 else if (!strcmp (debug_level, "basic"))
313 opt.debug = DBG_ASSUAN_VALUE;
314 else if (!strcmp (debug_level, "advanced"))
315 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
316 else if (!strcmp (debug_level, "expert"))
317 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
318 |DBG_CACHE_VALUE);
319 else if (!strcmp (debug_level, "guru"))
320 opt.debug = ~0;
321 else
323 log_error (_("invalid debug-level `%s' given\n"), debug_level);
324 opt.debug = 0; /* Reset debugging, so that prior debug
325 statements won't have an undesired effect. */
328 if (opt.debug && !opt.verbose)
329 opt.verbose = 1;
330 if (opt.debug && opt.quiet)
331 opt.quiet = 0;
333 if (opt.debug & DBG_MPI_VALUE)
334 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
335 if (opt.debug & DBG_CRYPTO_VALUE )
336 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
337 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
341 /* Helper for cleanup to remove one socket with NAME. */
342 static void
343 remove_socket (char *name)
345 if (name && *name)
347 char *p;
349 remove (name);
350 p = strrchr (name, '/');
351 if (p)
353 *p = 0;
354 rmdir (name);
355 *p = '/';
357 *name = 0;
361 static void
362 cleanup (void)
364 remove_socket (socket_name);
365 remove_socket (socket_name_ssh);
370 /* Handle options which are allowed to be reset after program start.
371 Return true when the current option in PARGS could be handled and
372 false if not. As a special feature, passing a value of NULL for
373 PARGS, resets the options to the default. REREAD should be set
374 true if it is not the initial option parsing. */
375 static int
376 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
378 if (!pargs)
379 { /* reset mode */
380 opt.quiet = 0;
381 opt.verbose = 0;
382 opt.debug = 0;
383 opt.no_grab = 0;
384 opt.pinentry_program = NULL;
385 opt.pinentry_touch_file = NULL;
386 opt.scdaemon_program = NULL;
387 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
388 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
389 opt.max_cache_ttl = MAX_CACHE_TTL;
390 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
391 opt.enforce_passphrase_constraints = 0;
392 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
393 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
394 opt.check_passphrase_pattern = NULL;
395 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
396 opt.enable_passhrase_history = 0;
397 opt.ignore_cache_for_signing = 0;
398 opt.allow_mark_trusted = 0;
399 opt.disable_scdaemon = 0;
400 return 1;
403 switch (pargs->r_opt)
405 case oQuiet: opt.quiet = 1; break;
406 case oVerbose: opt.verbose++; break;
408 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
409 case oDebugAll: opt.debug = ~0; break;
410 case oDebugLevel: debug_level = pargs->r.ret_str; break;
412 case oLogFile:
413 if (!reread)
414 return 0; /* not handeld */
415 if (!current_logfile || !pargs->r.ret_str
416 || strcmp (current_logfile, pargs->r.ret_str))
418 log_set_file (pargs->r.ret_str);
419 xfree (current_logfile);
420 current_logfile = xtrystrdup (pargs->r.ret_str);
422 break;
424 case oNoGrab: opt.no_grab = 1; break;
426 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
427 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
428 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
429 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
431 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
432 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
433 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
434 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
436 case oEnforcePassphraseConstraints:
437 opt.enforce_passphrase_constraints=1;
438 break;
439 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
440 case oMinPassphraseNonalpha:
441 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
442 break;
443 case oCheckPassphrasePattern:
444 opt.check_passphrase_pattern = pargs->r.ret_str;
445 break;
446 case oMaxPassphraseDays:
447 opt.max_passphrase_days = pargs->r.ret_ulong;
448 break;
449 case oEnablePassphraseHistory:
450 opt.enable_passhrase_history = 1;
451 break;
453 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
455 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
457 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
459 default:
460 return 0; /* not handled */
463 return 1; /* handled */
467 /* The main entry point. */
469 main (int argc, char **argv )
471 ARGPARSE_ARGS pargs;
472 int orig_argc;
473 int may_coredump;
474 char **orig_argv;
475 FILE *configfp = NULL;
476 char *configname = NULL;
477 const char *shell;
478 unsigned configlineno;
479 int parse_debug = 0;
480 int default_config =1;
481 int greeting = 0;
482 int nogreeting = 0;
483 int pipe_server = 0;
484 int is_daemon = 0;
485 int nodetach = 0;
486 int csh_style = 0;
487 char *logfile = NULL;
488 int debug_wait = 0;
489 int gpgconf_list = 0;
490 int use_standard_socket = 0;
491 gpg_error_t err;
492 const char *env_file_name = NULL;
495 set_strusage (my_strusage);
496 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
497 /* Please note that we may running SUID(ROOT), so be very CAREFUL
498 when adding any stuff between here and the call to INIT_SECMEM()
499 somewhere after the option parsing */
500 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
502 /* Make sure that our subsystems are ready. */
503 init_common_subsystems ();
505 i18n_init ();
507 /* Libgcrypt requires us to register the threading model first.
508 Note that this will also do the pth_init. */
509 gcry_threads_pth.init = fixed_gcry_pth_init;
510 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
511 if (err)
513 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
514 gpg_strerror (err));
518 /* Check that the libraries are suitable. Do it here because
519 the option parsing may need services of the library. */
520 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
522 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
523 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
526 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
527 assuan_set_assuan_log_stream (log_get_stream ());
528 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
529 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
531 setup_libgcrypt_logging ();
532 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
534 may_coredump = disable_core_dumps ();
536 /* Set default options. */
537 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
538 #ifdef HAVE_W32_SYSTEM
539 use_standard_socket = 1; /* Under Windows we always use a standard
540 socket. */
541 #endif
543 shell = getenv ("SHELL");
544 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
545 csh_style = 1;
547 opt.homedir = default_homedir ();
549 /* Record some of the original environment strings. */
550 opt.startup_display = getenv ("DISPLAY");
551 if (opt.startup_display)
552 opt.startup_display = xstrdup (opt.startup_display);
553 opt.startup_ttyname = ttyname (0);
554 if (opt.startup_ttyname)
555 opt.startup_ttyname = xstrdup (opt.startup_ttyname);
556 opt.startup_ttytype = getenv ("TERM");
557 if (opt.startup_ttytype)
558 opt.startup_ttytype = xstrdup (opt.startup_ttytype);
559 /* Fixme: Better use the locale function here. */
560 opt.startup_lc_ctype = getenv ("LC_CTYPE");
561 if (opt.startup_lc_ctype)
562 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
563 opt.startup_lc_messages = getenv ("LC_MESSAGES");
564 if (opt.startup_lc_messages)
565 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
566 opt.startup_xauthority = getenv ("XAUTHORITY");
567 if (opt.startup_xauthority)
568 opt.startup_xauthority = xstrdup (opt.startup_xauthority);
569 opt.startup_pinentry_user_data = getenv ("PINENTRY_USER_DATA");
570 if (opt.startup_pinentry_user_data)
571 opt.startup_pinentry_user_data = xstrdup (opt.startup_pinentry_user_data);
573 /* Check whether we have a config file on the commandline */
574 orig_argc = argc;
575 orig_argv = argv;
576 pargs.argc = &argc;
577 pargs.argv = &argv;
578 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
579 while (arg_parse( &pargs, opts))
581 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
582 parse_debug++;
583 else if (pargs.r_opt == oOptions)
584 { /* yes there is one, so we do not try the default one, but
585 read the option file when it is encountered at the
586 commandline */
587 default_config = 0;
589 else if (pargs.r_opt == oNoOptions)
590 default_config = 0; /* --no-options */
591 else if (pargs.r_opt == oHomedir)
592 opt.homedir = pargs.r.ret_str;
595 /* Initialize the secure memory. */
596 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
597 maybe_setuid = 0;
600 Now we are now working under our real uid
603 if (default_config)
604 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
606 argc = orig_argc;
607 argv = orig_argv;
608 pargs.argc = &argc;
609 pargs.argv = &argv;
610 pargs.flags= 1; /* do not remove the args */
611 next_pass:
612 if (configname)
614 configlineno = 0;
615 configfp = fopen (configname, "r");
616 if (!configfp)
618 if (default_config)
620 if( parse_debug )
621 log_info (_("NOTE: no default option file `%s'\n"),
622 configname );
624 else
626 log_error (_("option file `%s': %s\n"),
627 configname, strerror(errno) );
628 exit(2);
630 xfree (configname);
631 configname = NULL;
633 if (parse_debug && configname )
634 log_info (_("reading options from `%s'\n"), configname );
635 default_config = 0;
638 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
640 if (parse_rereadable_options (&pargs, 0))
641 continue; /* Already handled */
642 switch (pargs.r_opt)
644 case aGPGConfList: gpgconf_list = 1; break;
645 case aGPGConfTest: gpgconf_list = 2; break;
646 case oBatch: opt.batch=1; break;
648 case oDebugWait: debug_wait = pargs.r.ret_int; break;
650 case oOptions:
651 /* config files may not be nested (silently ignore them) */
652 if (!configfp)
654 xfree(configname);
655 configname = xstrdup(pargs.r.ret_str);
656 goto next_pass;
658 break;
659 case oNoGreeting: nogreeting = 1; break;
660 case oNoVerbose: opt.verbose = 0; break;
661 case oNoOptions: break; /* no-options */
662 case oHomedir: opt.homedir = pargs.r.ret_str; break;
663 case oNoDetach: nodetach = 1; break;
664 case oLogFile: logfile = pargs.r.ret_str; break;
665 case oCsh: csh_style = 1; break;
666 case oSh: csh_style = 0; break;
667 case oServer: pipe_server = 1; break;
668 case oDaemon: is_daemon = 1; break;
670 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
671 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
672 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
673 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
674 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
675 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
676 break;
678 case oUseStandardSocket: use_standard_socket = 1; break;
679 case oNoUseStandardSocket: use_standard_socket = 0; break;
681 case oFakedSystemTime:
683 time_t faked_time = isotime2epoch (pargs.r.ret_str);
684 if (faked_time == (time_t)(-1))
685 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
686 gnupg_set_time (faked_time, 0);
688 break;
690 case oKeepTTY: opt.keep_tty = 1; break;
691 case oKeepDISPLAY: opt.keep_display = 1; break;
693 case oSSHSupport: opt.ssh_support = 1; break;
694 case oWriteEnvFile:
695 if (pargs.r_type)
696 env_file_name = pargs.r.ret_str;
697 else
698 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
699 break;
701 default : pargs.err = configfp? 1:2; break;
704 if (configfp)
706 fclose( configfp );
707 configfp = NULL;
708 /* Keep a copy of the name so that it can be read on SIGHUP. */
709 config_filename = configname;
710 configname = NULL;
711 goto next_pass;
713 xfree (configname);
714 configname = NULL;
715 if (log_get_errorcount(0))
716 exit(2);
717 if (nogreeting )
718 greeting = 0;
720 if (greeting)
722 fprintf (stderr, "%s %s; %s\n",
723 strusage(11), strusage(13), strusage(14) );
724 fprintf (stderr, "%s\n", strusage(15) );
726 #ifdef IS_DEVELOPMENT_VERSION
727 /* We don't want to print it here because gpg-agent is useful of its
728 own and quite matured. */
729 /*log_info ("NOTE: this is a development version!\n");*/
730 #endif
732 set_debug ();
734 if (atexit (cleanup))
736 log_error ("atexit failed\n");
737 cleanup ();
738 exit (1);
741 initialize_module_call_pinentry ();
742 initialize_module_call_scd ();
743 initialize_module_trustlist ();
745 /* Try to create missing directories. */
746 create_directories ();
748 if (debug_wait && pipe_server)
750 log_debug ("waiting for debugger - my pid is %u .....\n",
751 (unsigned int)getpid());
752 gnupg_sleep (debug_wait);
753 log_debug ("... okay\n");
756 if (gpgconf_list == 2)
757 agent_exit (0);
758 if (gpgconf_list)
760 char *filename;
761 char *filename_esc;
763 /* List options and default values in the GPG Conf format. */
764 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
765 filename_esc = percent_escape (filename, NULL);
767 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
768 GC_OPT_FLAG_DEFAULT, filename_esc);
769 xfree (filename);
770 xfree (filename_esc);
772 printf ("verbose:%lu:\n"
773 "quiet:%lu:\n"
774 "debug-level:%lu:\"none:\n"
775 "log-file:%lu:\n",
776 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
777 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
778 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
779 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
780 printf ("default-cache-ttl:%lu:%d:\n",
781 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
782 printf ("default-cache-ttl-ssh:%lu:%d:\n",
783 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
784 printf ("max-cache-ttl:%lu:%d:\n",
785 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
786 printf ("max-cache-ttl-ssh:%lu:%d:\n",
787 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
788 printf ("enforce-passphrase-constraints:%lu:\n",
789 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
790 printf ("min-passphrase-len:%lu:%d:\n",
791 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
792 printf ("min-passphrase-nonalpha:%lu:%d:\n",
793 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
794 MIN_PASSPHRASE_NONALPHA);
795 printf ("check-passphrase-pattern:%lu:\n",
796 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
797 printf ("max-passphrase-days:%lu:%d:\n",
798 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
799 MAX_PASSPHRASE_DAYS);
800 printf ("enable-passphrase-history:%lu:\n",
801 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
802 printf ("no-grab:%lu:\n",
803 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
804 printf ("ignore-cache-for-signing:%lu:\n",
805 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
806 printf ("allow-mark-trusted:%lu:\n",
807 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
808 printf ("disable-scdaemon:%lu:\n",
809 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
811 agent_exit (0);
814 /* If this has been called without any options, we merely check
815 whether an agent is already running. We do this here so that we
816 don't clobber a logfile but print it directly to stderr. */
817 if (!pipe_server && !is_daemon)
819 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
820 check_for_running_agent (0, 0);
821 agent_exit (0);
824 #ifdef ENABLE_NLS
825 /* gpg-agent usually does not output any messages because it runs in
826 the background. For log files it is acceptable to have messages
827 always encoded in utf-8. We switch here to utf-8, so that
828 commands like --help still give native messages. It is far
829 easier to switch only once instead of for every message and it
830 actually helps when more then one thread is active (avoids an
831 extra copy step). */
832 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
833 #endif
835 /* Now start with logging to a file if this is desired. */
836 if (logfile)
838 log_set_file (logfile);
839 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
840 |JNLIB_LOG_WITH_TIME
841 |JNLIB_LOG_WITH_PID));
842 current_logfile = xstrdup (logfile);
845 /* Make sure that we have a default ttyname. */
846 if (!default_ttyname && ttyname (1))
847 default_ttyname = xstrdup (ttyname (1));
848 if (!default_ttytype && getenv ("TERM"))
849 default_ttytype = xstrdup (getenv ("TERM"));
852 if (pipe_server)
854 /* This is the simple pipe based server */
855 ctrl_t ctrl;
857 ctrl = xtrycalloc (1, sizeof *ctrl);
858 if (!ctrl)
860 log_error ("error allocating connection control data: %s\n",
861 strerror (errno) );
862 agent_exit (1);
864 agent_init_default_ctrl (ctrl);
865 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
866 agent_deinit_default_ctrl (ctrl);
867 xfree (ctrl);
869 else if (!is_daemon)
870 ; /* NOTREACHED */
871 else
872 { /* Regular server mode */
873 gnupg_fd_t fd;
874 gnupg_fd_t fd_ssh;
875 pid_t pid;
877 /* Remove the DISPLAY variable so that a pinentry does not
878 default to a specific display. There is still a default
879 display when gpg-agent was started using --display or a
880 client requested this using an OPTION command. Note, that we
881 don't do this when running in reverse daemon mode (i.e. when
882 exec the program given as arguments). */
883 #ifndef HAVE_W32_SYSTEM
884 if (!opt.keep_display && !argc)
885 unsetenv ("DISPLAY");
886 #endif
889 /* Create the sockets. */
890 socket_name = create_socket_name (use_standard_socket,
891 "S.gpg-agent",
892 "/tmp/gpg-XXXXXX/S.gpg-agent");
893 if (opt.ssh_support)
894 socket_name_ssh = create_socket_name (use_standard_socket,
895 "S.gpg-agent.ssh",
896 "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
898 fd = create_server_socket (use_standard_socket, socket_name, 0,
899 &socket_nonce);
900 if (opt.ssh_support)
901 fd_ssh = create_server_socket (use_standard_socket, socket_name_ssh, 1,
902 &socket_nonce_ssh);
903 else
904 fd_ssh = GNUPG_INVALID_FD;
906 /* If we are going to exec a program in the parent, we record
907 the PID, so that the child may check whether the program is
908 still alive. */
909 if (argc)
910 parent_pid = getpid ();
912 fflush (NULL);
913 #ifdef HAVE_W32_SYSTEM
914 pid = getpid ();
915 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
916 #else /*!HAVE_W32_SYSTEM*/
917 pid = fork ();
918 if (pid == (pid_t)-1)
920 log_fatal ("fork failed: %s\n", strerror (errno) );
921 exit (1);
923 else if (pid)
924 { /* We are the parent */
925 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
927 close (fd);
929 /* Create the info string: <name>:<pid>:<protocol_version> */
930 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
931 socket_name, (ulong)pid ) < 0)
933 log_error ("out of core\n");
934 kill (pid, SIGTERM);
935 exit (1);
937 if (opt.ssh_support)
939 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
940 socket_name_ssh) < 0)
942 log_error ("out of core\n");
943 kill (pid, SIGTERM);
944 exit (1);
946 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
947 pid) < 0)
949 log_error ("out of core\n");
950 kill (pid, SIGTERM);
951 exit (1);
955 *socket_name = 0; /* Don't let cleanup() remove the socket -
956 the child should do this from now on */
957 if (opt.ssh_support)
958 *socket_name_ssh = 0;
960 if (env_file_name)
962 FILE *fp;
964 fp = fopen (env_file_name, "w");
965 if (!fp)
966 log_error (_("error creating `%s': %s\n"),
967 env_file_name, strerror (errno));
968 else
970 fputs (infostr, fp);
971 putc ('\n', fp);
972 if (opt.ssh_support)
974 fputs (infostr_ssh_sock, fp);
975 putc ('\n', fp);
976 fputs (infostr_ssh_pid, fp);
977 putc ('\n', fp);
979 fclose (fp);
984 if (argc)
985 { /* Run the program given on the commandline. */
986 if (putenv (infostr))
988 log_error ("failed to set environment: %s\n",
989 strerror (errno) );
990 kill (pid, SIGTERM );
991 exit (1);
993 if (opt.ssh_support && putenv (infostr_ssh_sock))
995 log_error ("failed to set environment: %s\n",
996 strerror (errno) );
997 kill (pid, SIGTERM );
998 exit (1);
1000 if (opt.ssh_support && putenv (infostr_ssh_pid))
1002 log_error ("failed to set environment: %s\n",
1003 strerror (errno) );
1004 kill (pid, SIGTERM );
1005 exit (1);
1007 execvp (argv[0], argv);
1008 log_error ("failed to run the command: %s\n", strerror (errno));
1009 kill (pid, SIGTERM);
1010 exit (1);
1012 else
1014 /* Print the environment string, so that the caller can use
1015 shell's eval to set it */
1016 if (csh_style)
1018 *strchr (infostr, '=') = ' ';
1019 printf ("setenv %s\n", infostr);
1020 if (opt.ssh_support)
1022 *strchr (infostr_ssh_sock, '=') = ' ';
1023 printf ("setenv %s\n", infostr_ssh_sock);
1024 *strchr (infostr_ssh_pid, '=') = ' ';
1025 printf ("setenv %s\n", infostr_ssh_pid);
1028 else
1030 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1031 if (opt.ssh_support)
1033 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1034 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1037 free (infostr); /* (Note that a vanilla free is here correct.) */
1038 if (opt.ssh_support)
1040 free (infostr_ssh_sock);
1041 free (infostr_ssh_pid);
1043 exit (0);
1045 /*NOTREACHED*/
1046 } /* End parent */
1049 This is the child
1052 /* Detach from tty and put process into a new session */
1053 if (!nodetach )
1055 int i;
1056 unsigned int oldflags;
1058 /* Close stdin, stdout and stderr unless it is the log stream */
1059 for (i=0; i <= 2; i++)
1061 if (!log_test_fd (i) && i != fd )
1063 if ( ! close (i)
1064 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1066 log_error ("failed to open `%s': %s\n",
1067 "/dev/null", strerror (errno));
1068 cleanup ();
1069 exit (1);
1073 if (setsid() == -1)
1075 log_error ("setsid() failed: %s\n", strerror(errno) );
1076 cleanup ();
1077 exit (1);
1080 log_get_prefix (&oldflags);
1081 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1082 opt.running_detached = 1;
1085 if (chdir("/"))
1087 log_error ("chdir to / failed: %s\n", strerror (errno));
1088 exit (1);
1092 struct sigaction sa;
1094 sa.sa_handler = SIG_IGN;
1095 sigemptyset (&sa.sa_mask);
1096 sa.sa_flags = 0;
1097 sigaction (SIGPIPE, &sa, NULL);
1099 #endif /*!HAVE_W32_SYSTEM*/
1101 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1102 assuan_sock_close (fd);
1105 return 0;
1109 void
1110 agent_exit (int rc)
1112 /*FIXME: update_random_seed_file();*/
1113 #if 1
1114 /* at this time a bit annoying */
1115 if (opt.debug & DBG_MEMSTAT_VALUE)
1117 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1118 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1120 if (opt.debug)
1121 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1122 #endif
1123 gcry_control (GCRYCTL_TERM_SECMEM );
1124 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1125 exit (rc);
1128 static void
1129 agent_init_default_ctrl (ctrl_t ctrl)
1131 /* Note we ignore malloc errors because we can't do much about it
1132 and the request will fail anyway shortly after this
1133 initialization. */
1134 if (ctrl->display)
1135 free (ctrl->display);
1136 ctrl->display = default_display? strdup (default_display) : NULL;
1138 if (ctrl->ttyname)
1139 free (ctrl->ttyname);
1140 ctrl->ttyname = default_ttyname? strdup (default_ttyname) : NULL;
1142 if (ctrl->ttytype)
1143 free (ctrl->ttytype);
1144 ctrl->ttytype = default_ttytype? strdup (default_ttytype) : NULL;
1146 if (ctrl->lc_ctype)
1147 free (ctrl->lc_ctype);
1148 ctrl->lc_ctype = default_lc_ctype? strdup (default_lc_ctype) : NULL;
1150 if (ctrl->lc_messages)
1151 free (ctrl->lc_messages);
1152 ctrl->lc_messages = default_lc_messages? strdup (default_lc_messages) : NULL;
1154 if (ctrl->xauthority)
1155 free (ctrl->xauthority);
1156 ctrl->xauthority = default_xauthority? strdup (default_xauthority) : NULL;
1158 if (ctrl->pinentry_user_data)
1159 free (ctrl->pinentry_user_data);
1160 ctrl->pinentry_user_data = NULL;
1164 static void
1165 agent_deinit_default_ctrl (ctrl_t ctrl)
1167 if (ctrl->display)
1168 free (ctrl->display);
1169 if (ctrl->ttyname)
1170 free (ctrl->ttyname);
1171 if (ctrl->ttytype)
1172 free (ctrl->ttytype);
1173 if (ctrl->lc_ctype)
1174 free (ctrl->lc_ctype);
1175 if (ctrl->lc_messages)
1176 free (ctrl->lc_messages);
1177 if (ctrl->xauthority)
1178 free (ctrl->xauthority);
1179 if (ctrl->pinentry_user_data)
1180 free (ctrl->pinentry_user_data);
1183 /* Reread parts of the configuration. Note, that this function is
1184 obviously not thread-safe and should only be called from the PTH
1185 signal handler.
1187 Fixme: Due to the way the argument parsing works, we create a
1188 memory leak here for all string type arguments. There is currently
1189 no clean way to tell whether the memory for the argument has been
1190 allocated or points into the process' original arguments. Unless
1191 we have a mechanism to tell this, we need to live on with this. */
1192 static void
1193 reread_configuration (void)
1195 ARGPARSE_ARGS pargs;
1196 FILE *fp;
1197 unsigned int configlineno = 0;
1198 int dummy;
1200 if (!config_filename)
1201 return; /* No config file. */
1203 fp = fopen (config_filename, "r");
1204 if (!fp)
1206 log_error (_("option file `%s': %s\n"),
1207 config_filename, strerror(errno) );
1208 return;
1211 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1213 memset (&pargs, 0, sizeof pargs);
1214 dummy = 0;
1215 pargs.argc = &dummy;
1216 pargs.flags = 1; /* do not remove the args */
1217 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1219 if (pargs.r_opt < -1)
1220 pargs.err = 1; /* Print a warning. */
1221 else /* Try to parse this option - ignore unchangeable ones. */
1222 parse_rereadable_options (&pargs, 1);
1224 fclose (fp);
1225 set_debug ();
1229 /* Return the file name of the socket we are using for native
1230 requests. */
1231 const char *
1232 get_agent_socket_name (void)
1234 const char *s = socket_name;
1236 return (s && *s)? s : NULL;
1239 /* Return the file name of the socket we are using for SSH
1240 requests. */
1241 const char *
1242 get_agent_ssh_socket_name (void)
1244 const char *s = socket_name_ssh;
1246 return (s && *s)? s : NULL;
1250 /* Under W32, this function returns the handle of the scdaemon
1251 notification event. Calling it the first time creates that
1252 event. */
1253 #ifdef HAVE_W32_SYSTEM
1254 void *
1255 get_agent_scd_notify_event (void)
1257 static HANDLE the_event;
1259 if (!the_event)
1261 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1263 the_event = CreateEvent ( &sa, FALSE, FALSE, NULL);
1264 if (!the_event)
1265 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1267 return the_event;
1269 #endif /*HAVE_W32_SYSTEM*/
1273 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1274 true using STANDARD_NAME in the home directory or if given as
1275 false from the mkdir type name TEMPLATE. In the latter case a
1276 unique name in a unique new directory will be created. In both
1277 cases check for valid characters as well as against a maximum
1278 allowed length for a unix domain socket is done. The function
1279 terminates the process in case of an error. Returns: Pointer to an
1280 allocated string with the absolute name of the socket used. */
1281 static char *
1282 create_socket_name (int use_standard_socket,
1283 char *standard_name, char *template)
1285 char *name, *p;
1287 if (use_standard_socket)
1288 name = make_filename (opt.homedir, standard_name, NULL);
1289 else
1291 name = xstrdup (template);
1292 p = strrchr (name, '/');
1293 if (!p)
1294 BUG ();
1295 *p = 0;
1296 if (!mkdtemp (name))
1298 log_error (_("can't create directory `%s': %s\n"),
1299 name, strerror (errno));
1300 agent_exit (2);
1302 *p = '/';
1305 if (strchr (name, PATHSEP_C))
1307 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1308 agent_exit (2);
1310 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1312 log_error (_("name of socket too long\n"));
1313 agent_exit (2);
1315 return name;
1320 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1321 whether a non-random socket is used. Returns the file descriptor
1322 or terminates the process in case of an error. Not that this
1323 function needs to be used for the regular socket first and only then
1324 for the ssh socket. */
1325 static gnupg_fd_t
1326 create_server_socket (int is_standard_name, char *name, int is_ssh,
1327 assuan_sock_nonce_t *nonce)
1329 struct sockaddr_un *serv_addr;
1330 socklen_t len;
1331 gnupg_fd_t fd;
1332 int rc;
1334 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1335 if (fd == ASSUAN_INVALID_FD)
1337 log_error (_("can't create socket: %s\n"), strerror (errno));
1338 agent_exit (2);
1341 serv_addr = xmalloc (sizeof (*serv_addr));
1342 memset (serv_addr, 0, sizeof *serv_addr);
1343 serv_addr->sun_family = AF_UNIX;
1344 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1346 log_error (_("socket name `%s' is too long\n"), name);
1347 agent_exit (2);
1349 strcpy (serv_addr->sun_path, name);
1350 len = (offsetof (struct sockaddr_un, sun_path)
1351 + strlen (serv_addr->sun_path) + 1);
1353 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1354 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
1356 /* Check whether a gpg-agent is already running on the standard
1357 socket. We do this test only if this is not the ssh socket.
1358 For ssh we assume that a test for gpg-agent has already been
1359 done and reuse the requested ssh socket. Testing the
1360 ssh-socket is not possible because at this point, though we
1361 know the new Assuan socket, the Assuan server and thus the
1362 ssh-agent server is not yet operational. This would lead to
1363 a hang. */
1364 if (!is_ssh && !check_for_running_agent (1, 1))
1366 log_error (_("a gpg-agent is already running - "
1367 "not starting a new one\n"));
1368 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1369 assuan_sock_close (fd);
1370 agent_exit (2);
1372 remove (name);
1373 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1375 if (rc != -1
1376 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1377 log_error (_("error getting nonce for the socket\n"));
1378 if (rc == -1)
1380 /* We use gpg_strerror here because it allows us to get strings
1381 for some W32 socket error codes. */
1382 log_error (_("error binding socket to `%s': %s\n"),
1383 serv_addr->sun_path,
1384 gpg_strerror (gpg_error_from_errno (errno)));
1386 assuan_sock_close (fd);
1387 if (is_standard_name)
1388 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1389 agent_exit (2);
1392 if (listen (FD2INT(fd), 5 ) == -1)
1394 log_error (_("listen() failed: %s\n"), strerror (errno));
1395 assuan_sock_close (fd);
1396 agent_exit (2);
1399 if (opt.verbose)
1400 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1402 return fd;
1406 /* Check that the directory for storing the private keys exists and
1407 create it if not. This function won't fail as it is only a
1408 convenience function and not strictly necessary. */
1409 static void
1410 create_private_keys_directory (const char *home)
1412 char *fname;
1413 struct stat statbuf;
1415 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1416 if (stat (fname, &statbuf) && errno == ENOENT)
1418 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1419 if (!CreateDirectory (fname, NULL))
1420 log_error (_("can't create directory `%s': %s\n"),
1421 fname, w32_strerror (-1) );
1422 #else
1423 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1424 log_error (_("can't create directory `%s': %s\n"),
1425 fname, strerror (errno) );
1426 #endif
1427 else if (!opt.quiet)
1428 log_info (_("directory `%s' created\n"), fname);
1430 xfree (fname);
1433 /* Create the directory only if the supplied directory name is the
1434 same as the default one. This way we avoid to create arbitrary
1435 directories when a non-default home directory is used. To cope
1436 with HOME, we compare only the suffix if we see that the default
1437 homedir does start with a tilde. We don't stop here in case of
1438 problems because other functions will throw an error anyway.*/
1439 static void
1440 create_directories (void)
1442 struct stat statbuf;
1443 const char *defhome = standard_homedir ();
1444 char *home;
1446 home = make_filename (opt.homedir, NULL);
1447 if ( stat (home, &statbuf) )
1449 if (errno == ENOENT)
1451 if (
1452 #ifdef HAVE_W32_SYSTEM
1453 ( !compare_filenames (home, defhome) )
1454 #else
1455 (*defhome == '~'
1456 && (strlen (home) >= strlen (defhome+1)
1457 && !strcmp (home + strlen(home)
1458 - strlen (defhome+1), defhome+1)))
1459 || (*defhome != '~' && !strcmp (home, defhome) )
1460 #endif
1463 #ifdef HAVE_W32_SYSTEM
1464 if (!CreateDirectory (home, NULL))
1465 log_error (_("can't create directory `%s': %s\n"),
1466 home, w32_strerror (-1) );
1467 #else
1468 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1469 log_error (_("can't create directory `%s': %s\n"),
1470 home, strerror (errno) );
1471 #endif
1472 else
1474 if (!opt.quiet)
1475 log_info (_("directory `%s' created\n"), home);
1476 create_private_keys_directory (home);
1480 else
1481 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1483 else if ( !S_ISDIR(statbuf.st_mode))
1485 log_error (_("can't use `%s' as home directory\n"), home);
1487 else /* exists and is a directory. */
1489 create_private_keys_directory (home);
1491 xfree (home);
1496 /* This is the worker for the ticker. It is called every few seconds
1497 and may only do fast operations. */
1498 static void
1499 handle_tick (void)
1501 /* Check whether the scdaemon has died and cleanup in this case. */
1502 agent_scd_check_aliveness ();
1504 /* If we are running as a child of another process, check whether
1505 the parent is still alive and shutdown if not. */
1506 #ifndef HAVE_W32_SYSTEM
1507 if (parent_pid != (pid_t)(-1))
1509 if (kill (parent_pid, 0))
1511 shutdown_pending = 2;
1512 log_info ("parent process died - shutting down\n");
1513 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1514 cleanup ();
1515 agent_exit (0);
1518 #endif /*HAVE_W32_SYSTEM*/
1522 /* A global function which allows us to call the reload stuff from
1523 other places too. This is only used when build for W32. */
1524 void
1525 agent_sighup_action (void)
1527 log_info ("SIGHUP received - "
1528 "re-reading configuration and flushing cache\n");
1529 agent_flush_cache ();
1530 reread_configuration ();
1531 agent_reload_trustlist ();
1535 static void
1536 agent_sigusr2_action (void)
1538 if (opt.verbose)
1539 log_info ("SIGUSR2 received - checking smartcard status\n");
1540 /* Nothing to check right now. We only increment a counter. */
1541 bump_card_eventcounter ();
1545 static void
1546 handle_signal (int signo)
1548 switch (signo)
1550 #ifndef HAVE_W32_SYSTEM
1551 case SIGHUP:
1552 agent_sighup_action ();
1553 break;
1555 case SIGUSR1:
1556 log_info ("SIGUSR1 received - printing internal information:\n");
1557 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1558 agent_query_dump_state ();
1559 agent_scd_dump_state ();
1560 break;
1562 case SIGUSR2:
1563 agent_sigusr2_action ();
1564 break;
1566 case SIGTERM:
1567 if (!shutdown_pending)
1568 log_info ("SIGTERM received - shutting down ...\n");
1569 else
1570 log_info ("SIGTERM received - still %ld running threads\n",
1571 pth_ctrl( PTH_CTRL_GETTHREADS ));
1572 shutdown_pending++;
1573 if (shutdown_pending > 2)
1575 log_info ("shutdown forced\n");
1576 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1577 cleanup ();
1578 agent_exit (0);
1580 break;
1582 case SIGINT:
1583 log_info ("SIGINT received - immediate shutdown\n");
1584 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1585 cleanup ();
1586 agent_exit (0);
1587 break;
1588 #endif
1589 default:
1590 log_info ("signal %d received - no action defined\n", signo);
1595 /* Check the nonce on a new connection. This is a NOP unless we we
1596 are using our Unix domain socket emulation under Windows. */
1597 static int
1598 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1600 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1602 log_info (_("error reading nonce on fd %d: %s\n"),
1603 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1604 assuan_sock_close (ctrl->thread_startup.fd);
1605 xfree (ctrl);
1606 return -1;
1608 else
1609 return 0;
1613 /* This is the standard connection thread's main function. */
1614 static void *
1615 start_connection_thread (void *arg)
1617 ctrl_t ctrl = arg;
1619 if (check_nonce (ctrl, &socket_nonce))
1620 return NULL;
1622 agent_init_default_ctrl (ctrl);
1623 if (opt.verbose)
1624 log_info (_("handler 0x%lx for fd %d started\n"),
1625 (long)pth_self (), FD2INT(ctrl->thread_startup.fd));
1627 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1628 if (opt.verbose)
1629 log_info (_("handler 0x%lx for fd %d terminated\n"),
1630 (long)pth_self (), FD2INT(ctrl->thread_startup.fd));
1632 agent_deinit_default_ctrl (ctrl);
1633 xfree (ctrl);
1634 return NULL;
1638 /* This is the ssh connection thread's main function. */
1639 static void *
1640 start_connection_thread_ssh (void *arg)
1642 ctrl_t ctrl = arg;
1644 if (check_nonce (ctrl, &socket_nonce_ssh))
1645 return NULL;
1647 agent_init_default_ctrl (ctrl);
1648 if (opt.verbose)
1649 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1650 (long)pth_self (), FD2INT(ctrl->thread_startup.fd));
1652 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1653 if (opt.verbose)
1654 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1655 (long)pth_self (), FD2INT(ctrl->thread_startup.fd));
1657 agent_deinit_default_ctrl (ctrl);
1658 xfree (ctrl);
1659 return NULL;
1663 /* Connection handler loop. Wait for connection requests and spawn a
1664 thread after accepting a connection. */
1665 static void
1666 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1668 pth_attr_t tattr;
1669 pth_event_t ev, time_ev;
1670 sigset_t sigs;
1671 int signo;
1672 struct sockaddr_un paddr;
1673 socklen_t plen;
1674 fd_set fdset, read_fdset;
1675 int ret;
1676 gnupg_fd_t fd;
1677 int nfd;
1679 tattr = pth_attr_new();
1680 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1681 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1683 #ifndef HAVE_W32_SYSTEM /* fixme */
1684 /* Make sure that the signals we are going to handle are not blocked
1685 and create an event object for them. */
1686 sigemptyset (&sigs );
1687 sigaddset (&sigs, SIGHUP);
1688 sigaddset (&sigs, SIGUSR1);
1689 sigaddset (&sigs, SIGUSR2);
1690 sigaddset (&sigs, SIGINT);
1691 sigaddset (&sigs, SIGTERM);
1692 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1693 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1694 #else
1695 # ifdef PTH_EVENT_HANDLE
1696 sigs = 0;
1697 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1698 signo = 0;
1699 # else
1700 /* Use a dummy event. */
1701 sigs = 0;
1702 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1703 # endif
1704 #endif
1705 time_ev = NULL;
1707 FD_ZERO (&fdset);
1708 FD_SET (FD2INT (listen_fd), &fdset);
1709 nfd = FD2INT (listen_fd);
1710 if (listen_fd_ssh != GNUPG_INVALID_FD)
1712 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1713 if (FD2INT (listen_fd_ssh) > nfd)
1714 nfd = FD2INT (listen_fd_ssh);
1717 for (;;)
1719 sigset_t oldsigs;
1721 if (shutdown_pending)
1723 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1724 break; /* ready */
1726 /* Do not accept anymore connections and wait for existing
1727 connections to terminate */
1728 signo = 0;
1729 pth_wait (ev);
1730 if (pth_event_occurred (ev) && signo)
1731 handle_signal (signo);
1732 continue;
1735 /* Create a timeout event if needed. */
1736 if (!time_ev)
1737 time_ev = pth_event (PTH_EVENT_TIME,
1738 pth_timeout (TIMERTICK_INTERVAL, 0));
1740 /* POSIX says that fd_set should be implemented as a structure,
1741 thus a simple assignment is fine to copy the entire set. */
1742 read_fdset = fdset;
1744 if (time_ev)
1745 pth_event_concat (ev, time_ev, NULL);
1746 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1747 if (time_ev)
1748 pth_event_isolate (time_ev);
1750 if (ret == -1)
1752 if (pth_event_occurred (ev)
1753 || (time_ev && pth_event_occurred (time_ev)))
1755 if (pth_event_occurred (ev))
1757 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1758 agent_sigusr2_action ();
1759 #else
1760 handle_signal (signo);
1761 #endif
1763 if (time_ev && pth_event_occurred (time_ev))
1765 pth_event_free (time_ev, PTH_FREE_ALL);
1766 time_ev = NULL;
1767 handle_tick ();
1769 continue;
1771 log_error (_("pth_select failed: %s - waiting 1s\n"),
1772 strerror (errno));
1773 pth_sleep (1);
1774 continue;
1777 if (pth_event_occurred (ev))
1779 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1780 agent_sigusr2_action ();
1781 #else
1782 handle_signal (signo);
1783 #endif
1786 if (time_ev && pth_event_occurred (time_ev))
1788 pth_event_free (time_ev, PTH_FREE_ALL);
1789 time_ev = NULL;
1790 handle_tick ();
1794 /* We now might create new threads and because we don't want any
1795 signals (as we are handling them here) to be delivered to a
1796 new thread. Thus we need to block those signals. */
1797 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1799 if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
1801 ctrl_t ctrl;
1803 plen = sizeof paddr;
1804 fd = INT2FD (pth_accept (FD2INT(listen_fd),
1805 (struct sockaddr *)&paddr, &plen));
1806 if (fd == GNUPG_INVALID_FD)
1808 log_error ("accept failed: %s\n", strerror (errno));
1810 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1812 log_error ("error allocating connection control data: %s\n",
1813 strerror (errno) );
1814 assuan_sock_close (fd);
1816 else
1818 char threadname[50];
1820 snprintf (threadname, sizeof threadname-1,
1821 "conn fd=%d (gpg)", FD2INT(fd));
1822 threadname[sizeof threadname -1] = 0;
1823 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1824 ctrl->thread_startup.fd = fd;
1825 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1827 log_error ("error spawning connection handler: %s\n",
1828 strerror (errno) );
1829 assuan_sock_close (fd);
1830 xfree (ctrl);
1833 fd = GNUPG_INVALID_FD;
1836 if (listen_fd_ssh != GNUPG_INVALID_FD
1837 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
1839 ctrl_t ctrl;
1841 plen = sizeof paddr;
1842 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
1843 (struct sockaddr *)&paddr, &plen));
1844 if (fd == GNUPG_INVALID_FD)
1846 log_error ("accept failed for ssh: %s\n", strerror (errno));
1848 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1850 log_error ("error allocating connection control data: %s\n",
1851 strerror (errno) );
1852 assuan_sock_close (fd);
1854 else
1856 char threadname[50];
1858 agent_init_default_ctrl (ctrl);
1859 snprintf (threadname, sizeof threadname-1,
1860 "conn fd=%d (ssh)", FD2INT(fd));
1861 threadname[sizeof threadname -1] = 0;
1862 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1863 ctrl->thread_startup.fd = fd;
1864 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
1866 log_error ("error spawning ssh connection handler: %s\n",
1867 strerror (errno) );
1868 assuan_sock_close (fd);
1869 xfree (ctrl);
1872 fd = GNUPG_INVALID_FD;
1875 /* Restore the signal mask. */
1876 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1880 pth_event_free (ev, PTH_FREE_ALL);
1881 if (time_ev)
1882 pth_event_free (time_ev, PTH_FREE_ALL);
1883 cleanup ();
1884 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1888 /* Figure out whether an agent is available and running. Prints an
1889 error if not. If SILENT is true, no messages are printed. Usually
1890 started with MODE 0. Returns 0 if the agent is running. */
1891 static int
1892 check_for_running_agent (int silent, int mode)
1894 int rc;
1895 char *infostr, *p;
1896 assuan_context_t ctx;
1897 int prot, pid;
1899 if (!mode)
1901 infostr = getenv ("GPG_AGENT_INFO");
1902 if (!infostr || !*infostr)
1904 if (!check_for_running_agent (silent, 1))
1905 return 0; /* Okay, its running on the standard socket. */
1906 if (!silent)
1907 log_error (_("no gpg-agent running in this session\n"));
1908 return -1;
1911 infostr = xstrdup (infostr);
1912 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
1914 xfree (infostr);
1915 if (!check_for_running_agent (silent, 1))
1916 return 0; /* Okay, its running on the standard socket. */
1917 if (!silent)
1918 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
1919 return -1;
1922 *p++ = 0;
1923 pid = atoi (p);
1924 while (*p && *p != PATHSEP_C)
1925 p++;
1926 prot = *p? atoi (p+1) : 0;
1927 if (prot != 1)
1929 xfree (infostr);
1930 if (!silent)
1931 log_error (_("gpg-agent protocol version %d is not supported\n"),
1932 prot);
1933 if (!check_for_running_agent (silent, 1))
1934 return 0; /* Okay, its running on the standard socket. */
1935 return -1;
1938 else /* MODE != 0 */
1940 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
1941 pid = (pid_t)(-1);
1945 rc = assuan_socket_connect (&ctx, infostr, pid);
1946 xfree (infostr);
1947 if (rc)
1949 if (!mode && !check_for_running_agent (silent, 1))
1950 return 0; /* Okay, its running on the standard socket. */
1952 if (!mode && !silent)
1953 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
1954 return -1;
1957 if (!opt.quiet && !silent)
1958 log_info ("gpg-agent running and available\n");
1960 assuan_disconnect (ctx);
1961 return 0;