agent/
[gnupg.git] / agent / gpg-agent.c
blobba72236342609be24d244ed385d5e55f8a90e3df
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 #define JNLIB_NEED_AFLOCAL
43 #include "agent.h"
44 #include <assuan.h> /* Malloc hooks and socket wrappers. */
46 #include "i18n.h"
47 #include "mkdtemp.h" /* Gnulib replacement. */
48 #include "sysutils.h"
49 #include "setenv.h"
50 #include "gc-opt-flags.h"
51 #include "exechelp.h"
53 enum cmd_and_opt_values
54 { aNull = 0,
55 oCsh = 'c',
56 oQuiet = 'q',
57 oSh = 's',
58 oVerbose = 'v',
60 oNoVerbose = 500,
61 aGPGConfList,
62 aGPGConfTest,
63 oOptions,
64 oDebug,
65 oDebugAll,
66 oDebugLevel,
67 oDebugWait,
68 oNoGreeting,
69 oNoOptions,
70 oHomedir,
71 oNoDetach,
72 oNoGrab,
73 oLogFile,
74 oServer,
75 oDaemon,
76 oBatch,
78 oPinentryProgram,
79 oPinentryTouchFile,
80 oDisplay,
81 oTTYname,
82 oTTYtype,
83 oLCctype,
84 oLCmessages,
85 oXauthority,
86 oScdaemonProgram,
87 oDefCacheTTL,
88 oDefCacheTTLSSH,
89 oMaxCacheTTL,
90 oMaxCacheTTLSSH,
91 oEnforcePassphraseConstraints,
92 oMinPassphraseLen,
93 oMinPassphraseNonalpha,
94 oCheckPassphrasePattern,
95 oMaxPassphraseDays,
96 oEnablePassphraseHistory,
97 oUseStandardSocket,
98 oNoUseStandardSocket,
99 oFakedSystemTime,
101 oIgnoreCacheForSigning,
102 oAllowMarkTrusted,
103 oAllowPresetPassphrase,
104 oKeepTTY,
105 oKeepDISPLAY,
106 oSSHSupport,
107 oDisableScdaemon,
108 oWriteEnvFile
113 static ARGPARSE_OPTS opts[] = {
115 { aGPGConfList, "gpgconf-list", 256, "@" },
116 { aGPGConfTest, "gpgconf-test", 256, "@" },
118 { 301, NULL, 0, N_("@Options:\n ") },
120 { oServer, "server", 0, N_("run in server mode (foreground)") },
121 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
122 { oVerbose, "verbose", 0, N_("verbose") },
123 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
124 { oSh, "sh", 0, N_("sh-style command output") },
125 { oCsh, "csh", 0, N_("csh-style command output") },
126 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
127 { oDebug, "debug" ,4|16, "@"},
128 { oDebugAll, "debug-all" ,0, "@"},
129 { oDebugLevel, "debug-level" ,2, "@"},
130 { oDebugWait,"debug-wait",1, "@"},
131 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
132 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
133 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
134 { oUseStandardSocket, "use-standard-socket", 0,
135 N_("use a standard location for the socket")},
136 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
137 { oPinentryProgram, "pinentry-program", 2 ,
138 N_("|PGM|use PGM as the PIN-Entry program") },
139 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
140 { oScdaemonProgram, "scdaemon-program", 2 ,
141 N_("|PGM|use PGM as the SCdaemon program") },
142 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
143 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
145 { oBatch, "batch", 0, "@" },
146 { oHomedir, "homedir", 2, "@"},
148 { oDisplay, "display", 2, "@" },
149 { oTTYname, "ttyname", 2, "@" },
150 { oTTYtype, "ttytype", 2, "@" },
151 { oLCctype, "lc-ctype", 2, "@" },
152 { oLCmessages, "lc-messages", 2, "@" },
153 { oXauthority, "xauthority", 2, "@" },
154 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
155 { oKeepDISPLAY, "keep-display",
156 0, N_("ignore requests to change the X display")},
158 { oDefCacheTTL, "default-cache-ttl", 4,
159 N_("|N|expire cached PINs after N seconds")},
160 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
161 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
162 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
164 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
165 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
166 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
167 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
168 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
169 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
171 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
172 N_("do not use the PIN cache when signing")},
173 { oAllowMarkTrusted, "allow-mark-trusted", 0,
174 N_("allow clients to mark keys as \"trusted\"")},
175 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
176 N_("allow presetting passphrase")},
177 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
178 { oWriteEnvFile, "write-env-file", 2|8,
179 N_("|FILE|write environment settings also to FILE")},
184 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
185 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
186 #define MAX_CACHE_TTL (120*60) /* 2 hours */
187 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
188 #define MIN_PASSPHRASE_LEN (8)
189 #define MIN_PASSPHRASE_NONALPHA (1)
190 #define MAX_PASSPHRASE_DAYS (0)
192 /* The timer tick used for housekeeping stuff. For Windows we use a
193 longer period as the SetWaitableTimer seems to signal earlier than
194 the 2 seconds. */
195 #ifdef HAVE_W32_SYSTEM
196 #define TIMERTICK_INTERVAL (4)
197 #else
198 #define TIMERTICK_INTERVAL (2) /* Seconds. */
199 #endif
202 /* The list of open file descriptors at startup. Note that this list
203 has been allocated using the standard malloc. */
204 static int *startup_fd_list;
206 /* The signal mask at startup and a flag telling whether it is valid. */
207 #ifdef HAVE_SIGPROCMASK
208 static sigset_t startup_signal_mask;
209 static int startup_signal_mask_valid;
210 #endif
212 /* Flag to indicate that a shutdown was requested. */
213 static int shutdown_pending;
215 /* Counter for the currently running own socket checks. */
216 static int check_own_socket_running;
218 /* True if we are listening on the standard socket. */
219 static int use_standard_socket;
221 /* It is possible that we are currently running under setuid permissions */
222 static int maybe_setuid = 1;
224 /* Name of the communication socket used for native gpg-agent requests. */
225 static char *socket_name;
227 /* Name of the communication socket used for ssh-agent-emulation. */
228 static char *socket_name_ssh;
230 /* We need to keep track of the server's nonces (these are dummies for
231 POSIX systems). */
232 static assuan_sock_nonce_t socket_nonce;
233 static assuan_sock_nonce_t socket_nonce_ssh;
236 /* Default values for options passed to the pinentry. */
237 static char *default_display;
238 static char *default_ttyname;
239 static char *default_ttytype;
240 static char *default_lc_ctype;
241 static char *default_lc_messages;
242 static char *default_xauthority;
244 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
245 static char *config_filename;
247 /* Helper to implement --debug-level */
248 static const char *debug_level;
250 /* Keep track of the current log file so that we can avoid updating
251 the log file after a SIGHUP if it didn't changed. Malloced. */
252 static char *current_logfile;
254 /* The handle_tick() function may test whether a parent is still
255 running. We record the PID of the parent here or -1 if it should be
256 watched. */
257 static pid_t parent_pid = (pid_t)(-1);
261 Local prototypes.
264 static char *create_socket_name (char *standard_name, char *template);
265 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
266 assuan_sock_nonce_t *nonce);
267 static void create_directories (void);
269 static void agent_init_default_ctrl (ctrl_t ctrl);
270 static void agent_deinit_default_ctrl (ctrl_t ctrl);
272 static void handle_connections (gnupg_fd_t listen_fd,
273 gnupg_fd_t listen_fd_ssh);
274 static void check_own_socket (void);
275 static int check_for_running_agent (int silent, int mode);
277 /* Pth wrapper function definitions. */
278 ASSUAN_SYSTEM_PTH_IMPL;
280 GCRY_THREAD_OPTION_PTH_IMPL;
281 static int fixed_gcry_pth_init (void)
283 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
287 #ifndef PTH_HAVE_PTH_THREAD_ID
288 static unsigned long pth_thread_id (void)
290 return (unsigned long)pth_self ();
292 #endif
297 Functions.
300 static char *
301 make_libversion (const char *libname, const char *(*getfnc)(const char*))
303 const char *s;
304 char *result;
306 if (maybe_setuid)
308 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
309 maybe_setuid = 0;
311 s = getfnc (NULL);
312 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
313 strcpy (stpcpy (stpcpy (result, libname), " "), s);
314 return result;
318 static const char *
319 my_strusage (int level)
321 static char *ver_gcry;
322 const char *p;
324 switch (level)
326 case 11: p = "gpg-agent (GnuPG)";
327 break;
328 case 13: p = VERSION; break;
329 case 17: p = PRINTABLE_OS_NAME; break;
330 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
331 reporting address. This is so that we can change the
332 reporting address without breaking the translations. */
333 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
335 case 20:
336 if (!ver_gcry)
337 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
338 p = ver_gcry;
339 break;
341 case 1:
342 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
343 break;
344 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
345 "Secret key management for GnuPG\n");
346 break;
348 default: p = NULL;
350 return p;
355 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
356 only the active debug flags are propagated to the subsystems. With
357 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
358 all flags already set. Note that we don't fail here, because it is
359 important to keep gpg-agent running even after re-reading the
360 options due to a SIGHUP. */
361 static void
362 set_debug (void)
364 if (!debug_level)
366 else if (!strcmp (debug_level, "none"))
367 opt.debug = 0;
368 else if (!strcmp (debug_level, "basic"))
369 opt.debug = DBG_ASSUAN_VALUE;
370 else if (!strcmp (debug_level, "advanced"))
371 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
372 else if (!strcmp (debug_level, "expert"))
373 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
374 |DBG_CACHE_VALUE);
375 else if (!strcmp (debug_level, "guru"))
376 opt.debug = ~0;
377 else
379 log_error (_("invalid debug-level `%s' given\n"), debug_level);
380 opt.debug = 0; /* Reset debugging, so that prior debug
381 statements won't have an undesired effect. */
384 if (opt.debug && !opt.verbose)
385 opt.verbose = 1;
386 if (opt.debug && opt.quiet)
387 opt.quiet = 0;
389 if (opt.debug & DBG_MPI_VALUE)
390 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
391 if (opt.debug & DBG_CRYPTO_VALUE )
392 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
393 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
397 /* Helper for cleanup to remove one socket with NAME. */
398 static void
399 remove_socket (char *name)
401 if (name && *name)
403 char *p;
405 remove (name);
406 p = strrchr (name, '/');
407 if (p)
409 *p = 0;
410 rmdir (name);
411 *p = '/';
413 *name = 0;
417 static void
418 cleanup (void)
420 remove_socket (socket_name);
421 remove_socket (socket_name_ssh);
426 /* Handle options which are allowed to be reset after program start.
427 Return true when the current option in PARGS could be handled and
428 false if not. As a special feature, passing a value of NULL for
429 PARGS, resets the options to the default. REREAD should be set
430 true if it is not the initial option parsing. */
431 static int
432 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
434 if (!pargs)
435 { /* reset mode */
436 opt.quiet = 0;
437 opt.verbose = 0;
438 opt.debug = 0;
439 opt.no_grab = 0;
440 opt.pinentry_program = NULL;
441 opt.pinentry_touch_file = NULL;
442 opt.scdaemon_program = NULL;
443 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
444 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
445 opt.max_cache_ttl = MAX_CACHE_TTL;
446 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
447 opt.enforce_passphrase_constraints = 0;
448 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
449 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
450 opt.check_passphrase_pattern = NULL;
451 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
452 opt.enable_passhrase_history = 0;
453 opt.ignore_cache_for_signing = 0;
454 opt.allow_mark_trusted = 0;
455 opt.disable_scdaemon = 0;
456 return 1;
459 switch (pargs->r_opt)
461 case oQuiet: opt.quiet = 1; break;
462 case oVerbose: opt.verbose++; break;
464 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
465 case oDebugAll: opt.debug = ~0; break;
466 case oDebugLevel: debug_level = pargs->r.ret_str; break;
468 case oLogFile:
469 if (!reread)
470 return 0; /* not handeld */
471 if (!current_logfile || !pargs->r.ret_str
472 || strcmp (current_logfile, pargs->r.ret_str))
474 log_set_file (pargs->r.ret_str);
475 xfree (current_logfile);
476 current_logfile = xtrystrdup (pargs->r.ret_str);
478 break;
480 case oNoGrab: opt.no_grab = 1; break;
482 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
483 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
484 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
485 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
487 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
488 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
489 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
490 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
492 case oEnforcePassphraseConstraints:
493 opt.enforce_passphrase_constraints=1;
494 break;
495 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
496 case oMinPassphraseNonalpha:
497 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
498 break;
499 case oCheckPassphrasePattern:
500 opt.check_passphrase_pattern = pargs->r.ret_str;
501 break;
502 case oMaxPassphraseDays:
503 opt.max_passphrase_days = pargs->r.ret_ulong;
504 break;
505 case oEnablePassphraseHistory:
506 opt.enable_passhrase_history = 1;
507 break;
509 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
511 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
513 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
515 default:
516 return 0; /* not handled */
519 return 1; /* handled */
523 /* The main entry point. */
525 main (int argc, char **argv )
527 ARGPARSE_ARGS pargs;
528 int orig_argc;
529 int may_coredump;
530 char **orig_argv;
531 FILE *configfp = NULL;
532 char *configname = NULL;
533 const char *shell;
534 unsigned configlineno;
535 int parse_debug = 0;
536 int default_config =1;
537 int greeting = 0;
538 int nogreeting = 0;
539 int pipe_server = 0;
540 int is_daemon = 0;
541 int nodetach = 0;
542 int csh_style = 0;
543 char *logfile = NULL;
544 int debug_wait = 0;
545 int gpgconf_list = 0;
546 gpg_error_t err;
547 const char *env_file_name = NULL;
548 struct assuan_malloc_hooks malloc_hooks;
550 /* Before we do anything else we save the list of currently open
551 file descriptors and the signal mask. This info is required to
552 do the exec call properly. */
553 startup_fd_list = get_all_open_fds ();
554 #ifdef HAVE_SIGPROCMASK
555 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
556 startup_signal_mask_valid = 1;
557 #endif /*HAVE_SIGPROCMASK*/
559 /* Set program name etc. */
560 set_strusage (my_strusage);
561 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
562 /* Please note that we may running SUID(ROOT), so be very CAREFUL
563 when adding any stuff between here and the call to INIT_SECMEM()
564 somewhere after the option parsing */
565 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
567 /* Make sure that our subsystems are ready. */
568 i18n_init ();
569 init_common_subsystems ();
572 /* Libgcrypt requires us to register the threading model first.
573 Note that this will also do the pth_init. */
574 gcry_threads_pth.init = fixed_gcry_pth_init;
575 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
576 if (err)
578 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
579 gpg_strerror (err));
583 /* Check that the libraries are suitable. Do it here because
584 the option parsing may need services of the library. */
585 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
587 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
588 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
591 malloc_hooks.malloc = gcry_malloc;
592 malloc_hooks.realloc = gcry_realloc;
593 malloc_hooks.free = gcry_free;
594 assuan_set_malloc_hooks (&malloc_hooks);
595 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
596 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
597 assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
598 assuan_sock_init ();
600 setup_libgcrypt_logging ();
601 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
603 may_coredump = disable_core_dumps ();
605 /* Set default options. */
606 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
607 #ifdef HAVE_W32_SYSTEM
608 use_standard_socket = 1; /* Under Windows we always use a standard
609 socket. */
610 #endif
612 shell = getenv ("SHELL");
613 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
614 csh_style = 1;
616 opt.homedir = default_homedir ();
618 /* Record some of the original environment strings. */
620 const char *s;
621 int idx;
622 static const char *names[] =
623 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
625 err = 0;
626 opt.startup_env = session_env_new ();
627 if (!opt.startup_env)
628 err = gpg_error_from_syserror ();
629 for (idx=0; !err && names[idx]; idx++)
631 s = getenv (names[idx]);
632 if (s)
633 err = session_env_setenv (opt.startup_env, names[idx], s);
635 if (!err)
637 s = ttyname (0);
638 if (s)
639 err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
641 if (err)
642 log_fatal ("error recording startup environment: %s\n",
643 gpg_strerror (err));
645 /* Fixme: Better use the locale function here. */
646 opt.startup_lc_ctype = getenv ("LC_CTYPE");
647 if (opt.startup_lc_ctype)
648 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
649 opt.startup_lc_messages = getenv ("LC_MESSAGES");
650 if (opt.startup_lc_messages)
651 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
654 /* Check whether we have a config file on the commandline */
655 orig_argc = argc;
656 orig_argv = argv;
657 pargs.argc = &argc;
658 pargs.argv = &argv;
659 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
660 while (arg_parse( &pargs, opts))
662 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
663 parse_debug++;
664 else if (pargs.r_opt == oOptions)
665 { /* yes there is one, so we do not try the default one, but
666 read the option file when it is encountered at the
667 commandline */
668 default_config = 0;
670 else if (pargs.r_opt == oNoOptions)
671 default_config = 0; /* --no-options */
672 else if (pargs.r_opt == oHomedir)
673 opt.homedir = pargs.r.ret_str;
676 /* Initialize the secure memory. */
677 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
678 maybe_setuid = 0;
681 Now we are now working under our real uid
684 if (default_config)
685 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
687 argc = orig_argc;
688 argv = orig_argv;
689 pargs.argc = &argc;
690 pargs.argv = &argv;
691 pargs.flags= 1; /* do not remove the args */
692 next_pass:
693 if (configname)
695 configlineno = 0;
696 configfp = fopen (configname, "r");
697 if (!configfp)
699 if (default_config)
701 if( parse_debug )
702 log_info (_("NOTE: no default option file `%s'\n"),
703 configname );
705 else
707 log_error (_("option file `%s': %s\n"),
708 configname, strerror(errno) );
709 exit(2);
711 xfree (configname);
712 configname = NULL;
714 if (parse_debug && configname )
715 log_info (_("reading options from `%s'\n"), configname );
716 default_config = 0;
719 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
721 if (parse_rereadable_options (&pargs, 0))
722 continue; /* Already handled */
723 switch (pargs.r_opt)
725 case aGPGConfList: gpgconf_list = 1; break;
726 case aGPGConfTest: gpgconf_list = 2; break;
727 case oBatch: opt.batch=1; break;
729 case oDebugWait: debug_wait = pargs.r.ret_int; break;
731 case oOptions:
732 /* config files may not be nested (silently ignore them) */
733 if (!configfp)
735 xfree(configname);
736 configname = xstrdup(pargs.r.ret_str);
737 goto next_pass;
739 break;
740 case oNoGreeting: nogreeting = 1; break;
741 case oNoVerbose: opt.verbose = 0; break;
742 case oNoOptions: break; /* no-options */
743 case oHomedir: opt.homedir = pargs.r.ret_str; break;
744 case oNoDetach: nodetach = 1; break;
745 case oLogFile: logfile = pargs.r.ret_str; break;
746 case oCsh: csh_style = 1; break;
747 case oSh: csh_style = 0; break;
748 case oServer: pipe_server = 1; break;
749 case oDaemon: is_daemon = 1; break;
751 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
752 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
753 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
754 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
755 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
756 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
757 break;
759 case oUseStandardSocket: use_standard_socket = 1; break;
760 case oNoUseStandardSocket: use_standard_socket = 0; break;
762 case oFakedSystemTime:
764 time_t faked_time = isotime2epoch (pargs.r.ret_str);
765 if (faked_time == (time_t)(-1))
766 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
767 gnupg_set_time (faked_time, 0);
769 break;
771 case oKeepTTY: opt.keep_tty = 1; break;
772 case oKeepDISPLAY: opt.keep_display = 1; break;
774 case oSSHSupport: opt.ssh_support = 1; break;
775 case oWriteEnvFile:
776 if (pargs.r_type)
777 env_file_name = pargs.r.ret_str;
778 else
779 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
780 break;
782 default : pargs.err = configfp? 1:2; break;
785 if (configfp)
787 fclose( configfp );
788 configfp = NULL;
789 /* Keep a copy of the name so that it can be read on SIGHUP. */
790 config_filename = configname;
791 configname = NULL;
792 goto next_pass;
794 xfree (configname);
795 configname = NULL;
796 if (log_get_errorcount(0))
797 exit(2);
798 if (nogreeting )
799 greeting = 0;
801 if (greeting)
803 fprintf (stderr, "%s %s; %s\n",
804 strusage(11), strusage(13), strusage(14) );
805 fprintf (stderr, "%s\n", strusage(15) );
807 #ifdef IS_DEVELOPMENT_VERSION
808 /* We don't want to print it here because gpg-agent is useful of its
809 own and quite matured. */
810 /*log_info ("NOTE: this is a development version!\n");*/
811 #endif
813 set_debug ();
815 if (atexit (cleanup))
817 log_error ("atexit failed\n");
818 cleanup ();
819 exit (1);
822 initialize_module_call_pinentry ();
823 initialize_module_call_scd ();
824 initialize_module_trustlist ();
826 /* Try to create missing directories. */
827 create_directories ();
829 if (debug_wait && pipe_server)
831 log_debug ("waiting for debugger - my pid is %u .....\n",
832 (unsigned int)getpid());
833 gnupg_sleep (debug_wait);
834 log_debug ("... okay\n");
837 if (gpgconf_list == 2)
838 agent_exit (0);
839 if (gpgconf_list)
841 char *filename;
842 char *filename_esc;
844 /* List options and default values in the GPG Conf format. */
845 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
846 filename_esc = percent_escape (filename, NULL);
848 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
849 GC_OPT_FLAG_DEFAULT, filename_esc);
850 xfree (filename);
851 xfree (filename_esc);
853 printf ("verbose:%lu:\n"
854 "quiet:%lu:\n"
855 "debug-level:%lu:\"none:\n"
856 "log-file:%lu:\n",
857 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
858 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
859 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
860 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
861 printf ("default-cache-ttl:%lu:%d:\n",
862 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
863 printf ("default-cache-ttl-ssh:%lu:%d:\n",
864 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
865 printf ("max-cache-ttl:%lu:%d:\n",
866 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
867 printf ("max-cache-ttl-ssh:%lu:%d:\n",
868 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
869 printf ("enforce-passphrase-constraints:%lu:\n",
870 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
871 printf ("min-passphrase-len:%lu:%d:\n",
872 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
873 printf ("min-passphrase-nonalpha:%lu:%d:\n",
874 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
875 MIN_PASSPHRASE_NONALPHA);
876 printf ("check-passphrase-pattern:%lu:\n",
877 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
878 printf ("max-passphrase-days:%lu:%d:\n",
879 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
880 MAX_PASSPHRASE_DAYS);
881 printf ("enable-passphrase-history:%lu:\n",
882 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
883 printf ("no-grab:%lu:\n",
884 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
885 printf ("ignore-cache-for-signing:%lu:\n",
886 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
887 printf ("allow-mark-trusted:%lu:\n",
888 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
889 printf ("disable-scdaemon:%lu:\n",
890 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
892 agent_exit (0);
895 /* If this has been called without any options, we merely check
896 whether an agent is already running. We do this here so that we
897 don't clobber a logfile but print it directly to stderr. */
898 if (!pipe_server && !is_daemon)
900 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
901 check_for_running_agent (0, 0);
902 agent_exit (0);
905 #ifdef ENABLE_NLS
906 /* gpg-agent usually does not output any messages because it runs in
907 the background. For log files it is acceptable to have messages
908 always encoded in utf-8. We switch here to utf-8, so that
909 commands like --help still give native messages. It is far
910 easier to switch only once instead of for every message and it
911 actually helps when more then one thread is active (avoids an
912 extra copy step). */
913 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
914 #endif
916 /* Now start with logging to a file if this is desired. */
917 if (logfile)
919 log_set_file (logfile);
920 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
921 |JNLIB_LOG_WITH_TIME
922 |JNLIB_LOG_WITH_PID));
923 current_logfile = xstrdup (logfile);
926 /* Make sure that we have a default ttyname. */
927 if (!default_ttyname && ttyname (1))
928 default_ttyname = xstrdup (ttyname (1));
929 if (!default_ttytype && getenv ("TERM"))
930 default_ttytype = xstrdup (getenv ("TERM"));
933 if (pipe_server)
935 /* This is the simple pipe based server */
936 ctrl_t ctrl;
938 ctrl = xtrycalloc (1, sizeof *ctrl);
939 if (!ctrl)
941 log_error ("error allocating connection control data: %s\n",
942 strerror (errno) );
943 agent_exit (1);
945 ctrl->session_env = session_env_new ();
946 if (!ctrl->session_env)
948 log_error ("error allocating session environment block: %s\n",
949 strerror (errno) );
950 xfree (ctrl);
951 agent_exit (1);
953 agent_init_default_ctrl (ctrl);
954 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
955 agent_deinit_default_ctrl (ctrl);
956 xfree (ctrl);
958 else if (!is_daemon)
959 ; /* NOTREACHED */
960 else
961 { /* Regular server mode */
962 gnupg_fd_t fd;
963 gnupg_fd_t fd_ssh;
964 pid_t pid;
966 /* Remove the DISPLAY variable so that a pinentry does not
967 default to a specific display. There is still a default
968 display when gpg-agent was started using --display or a
969 client requested this using an OPTION command. Note, that we
970 don't do this when running in reverse daemon mode (i.e. when
971 exec the program given as arguments). */
972 #ifndef HAVE_W32_SYSTEM
973 if (!opt.keep_display && !argc)
974 unsetenv ("DISPLAY");
975 #endif
978 /* Create the sockets. */
979 socket_name = create_socket_name
980 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
981 if (opt.ssh_support)
982 socket_name_ssh = create_socket_name
983 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
985 fd = create_server_socket (socket_name, 0, &socket_nonce);
986 if (opt.ssh_support)
987 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
988 else
989 fd_ssh = GNUPG_INVALID_FD;
991 /* If we are going to exec a program in the parent, we record
992 the PID, so that the child may check whether the program is
993 still alive. */
994 if (argc)
995 parent_pid = getpid ();
997 fflush (NULL);
998 #ifdef HAVE_W32_SYSTEM
999 pid = getpid ();
1000 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
1001 #else /*!HAVE_W32_SYSTEM*/
1002 pid = fork ();
1003 if (pid == (pid_t)-1)
1005 log_fatal ("fork failed: %s\n", strerror (errno) );
1006 exit (1);
1008 else if (pid)
1009 { /* We are the parent */
1010 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
1012 /* Close the socket FD. */
1013 close (fd);
1015 /* Note that we used a standard fork so that Pth runs in
1016 both the parent and the child. The pth_fork would
1017 terminate Pth in the child but that is not the way we
1018 want it. Thus we use a plain fork and terminate Pth here
1019 in the parent. The pth_kill may or may not work reliable
1020 but it should not harm to call it. Because Pth fiddles
1021 with the signal mask the signal mask might not be correct
1022 right now and thus we restore it. That is not strictly
1023 necessary but some programs falsely assume a cleared
1024 signal mask. */
1025 if ( !pth_kill () )
1026 log_error ("pth_kill failed in forked process\n");
1028 #ifdef HAVE_SIGPROCMASK
1029 if (startup_signal_mask_valid)
1031 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1032 log_error ("error restoring signal mask: %s\n",
1033 strerror (errno));
1035 else
1036 log_info ("no saved signal mask\n");
1037 #endif /*HAVE_SIGPROCMASK*/
1039 /* Create the info string: <name>:<pid>:<protocol_version> */
1040 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1041 socket_name, (ulong)pid ) < 0)
1043 log_error ("out of core\n");
1044 kill (pid, SIGTERM);
1045 exit (1);
1047 if (opt.ssh_support)
1049 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1050 socket_name_ssh) < 0)
1052 log_error ("out of core\n");
1053 kill (pid, SIGTERM);
1054 exit (1);
1056 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1057 pid) < 0)
1059 log_error ("out of core\n");
1060 kill (pid, SIGTERM);
1061 exit (1);
1065 *socket_name = 0; /* Don't let cleanup() remove the socket -
1066 the child should do this from now on */
1067 if (opt.ssh_support)
1068 *socket_name_ssh = 0;
1070 if (env_file_name)
1072 FILE *fp;
1074 fp = fopen (env_file_name, "w");
1075 if (!fp)
1076 log_error (_("error creating `%s': %s\n"),
1077 env_file_name, strerror (errno));
1078 else
1080 fputs (infostr, fp);
1081 putc ('\n', fp);
1082 if (opt.ssh_support)
1084 fputs (infostr_ssh_sock, fp);
1085 putc ('\n', fp);
1086 fputs (infostr_ssh_pid, fp);
1087 putc ('\n', fp);
1089 fclose (fp);
1094 if (argc)
1095 { /* Run the program given on the commandline. */
1096 if (putenv (infostr))
1098 log_error ("failed to set environment: %s\n",
1099 strerror (errno) );
1100 kill (pid, SIGTERM );
1101 exit (1);
1103 if (opt.ssh_support && putenv (infostr_ssh_sock))
1105 log_error ("failed to set environment: %s\n",
1106 strerror (errno) );
1107 kill (pid, SIGTERM );
1108 exit (1);
1110 if (opt.ssh_support && putenv (infostr_ssh_pid))
1112 log_error ("failed to set environment: %s\n",
1113 strerror (errno) );
1114 kill (pid, SIGTERM );
1115 exit (1);
1118 /* Close all the file descriptors except the standard
1119 ones and those open at startup. We explicitly don't
1120 close 0,1,2 in case something went wrong collecting
1121 them at startup. */
1122 close_all_fds (3, startup_fd_list);
1124 /* Run the command. */
1125 execvp (argv[0], argv);
1126 log_error ("failed to run the command: %s\n", strerror (errno));
1127 kill (pid, SIGTERM);
1128 exit (1);
1130 else
1132 /* Print the environment string, so that the caller can use
1133 shell's eval to set it */
1134 if (csh_style)
1136 *strchr (infostr, '=') = ' ';
1137 printf ("setenv %s\n", infostr);
1138 if (opt.ssh_support)
1140 *strchr (infostr_ssh_sock, '=') = ' ';
1141 printf ("setenv %s\n", infostr_ssh_sock);
1142 *strchr (infostr_ssh_pid, '=') = ' ';
1143 printf ("setenv %s\n", infostr_ssh_pid);
1146 else
1148 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1149 if (opt.ssh_support)
1151 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1152 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1155 xfree (infostr);
1156 if (opt.ssh_support)
1158 xfree (infostr_ssh_sock);
1159 xfree (infostr_ssh_pid);
1161 exit (0);
1163 /*NOTREACHED*/
1164 } /* End parent */
1167 This is the child
1170 /* Detach from tty and put process into a new session */
1171 if (!nodetach )
1173 int i;
1174 unsigned int oldflags;
1176 /* Close stdin, stdout and stderr unless it is the log stream */
1177 for (i=0; i <= 2; i++)
1179 if (!log_test_fd (i) && i != fd )
1181 if ( ! close (i)
1182 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1184 log_error ("failed to open `%s': %s\n",
1185 "/dev/null", strerror (errno));
1186 cleanup ();
1187 exit (1);
1191 if (setsid() == -1)
1193 log_error ("setsid() failed: %s\n", strerror(errno) );
1194 cleanup ();
1195 exit (1);
1198 log_get_prefix (&oldflags);
1199 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1200 opt.running_detached = 1;
1203 if (chdir("/"))
1205 log_error ("chdir to / failed: %s\n", strerror (errno));
1206 exit (1);
1210 struct sigaction sa;
1212 sa.sa_handler = SIG_IGN;
1213 sigemptyset (&sa.sa_mask);
1214 sa.sa_flags = 0;
1215 sigaction (SIGPIPE, &sa, NULL);
1217 #endif /*!HAVE_W32_SYSTEM*/
1219 log_info ("%s %s started\n", strusage(11), strusage(13) );
1220 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1221 assuan_sock_close (fd);
1224 return 0;
1228 void
1229 agent_exit (int rc)
1231 /*FIXME: update_random_seed_file();*/
1232 #if 1
1233 /* at this time a bit annoying */
1234 if (opt.debug & DBG_MEMSTAT_VALUE)
1236 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1237 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1239 if (opt.debug)
1240 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1241 #endif
1242 gcry_control (GCRYCTL_TERM_SECMEM );
1243 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1244 exit (rc);
1248 static void
1249 agent_init_default_ctrl (ctrl_t ctrl)
1251 /* Note we ignore malloc errors because we can't do much about it
1252 and the request will fail anyway shortly after this
1253 initialization. */
1254 session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1255 session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1256 session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1257 session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1258 session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1260 if (ctrl->lc_ctype)
1261 xfree (ctrl->lc_ctype);
1262 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1264 if (ctrl->lc_messages)
1265 xfree (ctrl->lc_messages);
1266 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1267 /**/ : NULL;
1272 static void
1273 agent_deinit_default_ctrl (ctrl_t ctrl)
1275 session_env_release (ctrl->session_env);
1277 if (ctrl->lc_ctype)
1278 xfree (ctrl->lc_ctype);
1279 if (ctrl->lc_messages)
1280 xfree (ctrl->lc_messages);
1284 /* Reread parts of the configuration. Note, that this function is
1285 obviously not thread-safe and should only be called from the PTH
1286 signal handler.
1288 Fixme: Due to the way the argument parsing works, we create a
1289 memory leak here for all string type arguments. There is currently
1290 no clean way to tell whether the memory for the argument has been
1291 allocated or points into the process' original arguments. Unless
1292 we have a mechanism to tell this, we need to live on with this. */
1293 static void
1294 reread_configuration (void)
1296 ARGPARSE_ARGS pargs;
1297 FILE *fp;
1298 unsigned int configlineno = 0;
1299 int dummy;
1301 if (!config_filename)
1302 return; /* No config file. */
1304 fp = fopen (config_filename, "r");
1305 if (!fp)
1307 log_error (_("option file `%s': %s\n"),
1308 config_filename, strerror(errno) );
1309 return;
1312 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1314 memset (&pargs, 0, sizeof pargs);
1315 dummy = 0;
1316 pargs.argc = &dummy;
1317 pargs.flags = 1; /* do not remove the args */
1318 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1320 if (pargs.r_opt < -1)
1321 pargs.err = 1; /* Print a warning. */
1322 else /* Try to parse this option - ignore unchangeable ones. */
1323 parse_rereadable_options (&pargs, 1);
1325 fclose (fp);
1326 set_debug ();
1330 /* Return the file name of the socket we are using for native
1331 requests. */
1332 const char *
1333 get_agent_socket_name (void)
1335 const char *s = socket_name;
1337 return (s && *s)? s : NULL;
1340 /* Return the file name of the socket we are using for SSH
1341 requests. */
1342 const char *
1343 get_agent_ssh_socket_name (void)
1345 const char *s = socket_name_ssh;
1347 return (s && *s)? s : NULL;
1351 /* Under W32, this function returns the handle of the scdaemon
1352 notification event. Calling it the first time creates that
1353 event. */
1354 #ifdef HAVE_W32_SYSTEM
1355 void *
1356 get_agent_scd_notify_event (void)
1358 static HANDLE the_event;
1360 if (!the_event)
1362 HANDLE h, h2;
1363 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1365 /* We need to use manual reset evet object due to the way our
1366 w32-pth wait function works: If we would use an automatic
1367 reset event we are not able to figure out which handle has
1368 been signaled because at the time we single out the signaled
1369 handles using WFSO the event has already been reset due to
1370 the WFMO. */
1371 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1372 if (!h)
1373 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1374 else if (!DuplicateHandle (GetCurrentProcess(), h,
1375 GetCurrentProcess(), &h2,
1376 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1378 log_error ("setting syncronize for scd notify event failed: %s\n",
1379 w32_strerror (-1) );
1380 CloseHandle (h);
1382 else
1384 CloseHandle (h);
1385 the_event = h2;
1389 log_debug ("returning notify handle %p\n", the_event);
1390 return the_event;
1392 #endif /*HAVE_W32_SYSTEM*/
1396 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1397 true using STANDARD_NAME in the home directory or if given as
1398 false from the mkdir type name TEMPLATE. In the latter case a
1399 unique name in a unique new directory will be created. In both
1400 cases check for valid characters as well as against a maximum
1401 allowed length for a unix domain socket is done. The function
1402 terminates the process in case of an error. Returns: Pointer to an
1403 allocated string with the absolute name of the socket used. */
1404 static char *
1405 create_socket_name (char *standard_name, char *template)
1407 char *name, *p;
1409 if (use_standard_socket)
1410 name = make_filename (opt.homedir, standard_name, NULL);
1411 else
1413 name = xstrdup (template);
1414 p = strrchr (name, '/');
1415 if (!p)
1416 BUG ();
1417 *p = 0;
1418 if (!mkdtemp (name))
1420 log_error (_("can't create directory `%s': %s\n"),
1421 name, strerror (errno));
1422 agent_exit (2);
1424 *p = '/';
1427 if (strchr (name, PATHSEP_C))
1429 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1430 agent_exit (2);
1432 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1434 log_error (_("name of socket too long\n"));
1435 agent_exit (2);
1437 return name;
1442 /* Create a Unix domain socket with NAME. Returns the file descriptor
1443 or terminates the process in case of an error. Not that this
1444 function needs to be used for the regular socket first and only
1445 then for the ssh socket. */
1446 static gnupg_fd_t
1447 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1449 struct sockaddr_un *serv_addr;
1450 socklen_t len;
1451 gnupg_fd_t fd;
1452 int rc;
1454 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1455 if (fd == ASSUAN_INVALID_FD)
1457 log_error (_("can't create socket: %s\n"), strerror (errno));
1458 agent_exit (2);
1461 serv_addr = xmalloc (sizeof (*serv_addr));
1462 memset (serv_addr, 0, sizeof *serv_addr);
1463 serv_addr->sun_family = AF_UNIX;
1464 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1466 log_error (_("socket name `%s' is too long\n"), name);
1467 agent_exit (2);
1469 strcpy (serv_addr->sun_path, name);
1470 len = SUN_LEN (serv_addr);
1471 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1472 if (use_standard_socket && rc == -1 && errno == EADDRINUSE)
1474 /* Check whether a gpg-agent is already running on the standard
1475 socket. We do this test only if this is not the ssh socket.
1476 For ssh we assume that a test for gpg-agent has already been
1477 done and reuse the requested ssh socket. Testing the
1478 ssh-socket is not possible because at this point, though we
1479 know the new Assuan socket, the Assuan server and thus the
1480 ssh-agent server is not yet operational. This would lead to
1481 a hang. */
1482 if (!is_ssh && !check_for_running_agent (1, 1))
1484 log_error (_("a gpg-agent is already running - "
1485 "not starting a new one\n"));
1486 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1487 assuan_sock_close (fd);
1488 agent_exit (2);
1490 remove (name);
1491 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1493 if (rc != -1
1494 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1495 log_error (_("error getting nonce for the socket\n"));
1496 if (rc == -1)
1498 /* We use gpg_strerror here because it allows us to get strings
1499 for some W32 socket error codes. */
1500 log_error (_("error binding socket to `%s': %s\n"),
1501 serv_addr->sun_path,
1502 gpg_strerror (gpg_error_from_errno (errno)));
1504 assuan_sock_close (fd);
1505 if (use_standard_socket)
1506 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1507 agent_exit (2);
1510 if (listen (FD2INT(fd), 5 ) == -1)
1512 log_error (_("listen() failed: %s\n"), strerror (errno));
1513 assuan_sock_close (fd);
1514 agent_exit (2);
1517 if (opt.verbose)
1518 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1520 return fd;
1524 /* Check that the directory for storing the private keys exists and
1525 create it if not. This function won't fail as it is only a
1526 convenience function and not strictly necessary. */
1527 static void
1528 create_private_keys_directory (const char *home)
1530 char *fname;
1531 struct stat statbuf;
1533 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1534 if (stat (fname, &statbuf) && errno == ENOENT)
1536 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1537 if (!CreateDirectory (fname, NULL))
1538 log_error (_("can't create directory `%s': %s\n"),
1539 fname, w32_strerror (-1) );
1540 #else
1541 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1542 log_error (_("can't create directory `%s': %s\n"),
1543 fname, strerror (errno) );
1544 #endif
1545 else if (!opt.quiet)
1546 log_info (_("directory `%s' created\n"), fname);
1548 xfree (fname);
1551 /* Create the directory only if the supplied directory name is the
1552 same as the default one. This way we avoid to create arbitrary
1553 directories when a non-default home directory is used. To cope
1554 with HOME, we compare only the suffix if we see that the default
1555 homedir does start with a tilde. We don't stop here in case of
1556 problems because other functions will throw an error anyway.*/
1557 static void
1558 create_directories (void)
1560 struct stat statbuf;
1561 const char *defhome = standard_homedir ();
1562 char *home;
1564 home = make_filename (opt.homedir, NULL);
1565 if ( stat (home, &statbuf) )
1567 if (errno == ENOENT)
1569 if (
1570 #ifdef HAVE_W32_SYSTEM
1571 ( !compare_filenames (home, defhome) )
1572 #else
1573 (*defhome == '~'
1574 && (strlen (home) >= strlen (defhome+1)
1575 && !strcmp (home + strlen(home)
1576 - strlen (defhome+1), defhome+1)))
1577 || (*defhome != '~' && !strcmp (home, defhome) )
1578 #endif
1581 #ifdef HAVE_W32_SYSTEM
1582 if (!CreateDirectory (home, NULL))
1583 log_error (_("can't create directory `%s': %s\n"),
1584 home, w32_strerror (-1) );
1585 #else
1586 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1587 log_error (_("can't create directory `%s': %s\n"),
1588 home, strerror (errno) );
1589 #endif
1590 else
1592 if (!opt.quiet)
1593 log_info (_("directory `%s' created\n"), home);
1594 create_private_keys_directory (home);
1598 else
1599 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1601 else if ( !S_ISDIR(statbuf.st_mode))
1603 log_error (_("can't use `%s' as home directory\n"), home);
1605 else /* exists and is a directory. */
1607 create_private_keys_directory (home);
1609 xfree (home);
1614 /* This is the worker for the ticker. It is called every few seconds
1615 and may only do fast operations. */
1616 static void
1617 handle_tick (void)
1619 static time_t last_minute;
1621 if (!last_minute)
1622 last_minute = time (NULL);
1624 /* Check whether the scdaemon has died and cleanup in this case. */
1625 agent_scd_check_aliveness ();
1627 /* If we are running as a child of another process, check whether
1628 the parent is still alive and shutdown if not. */
1629 #ifndef HAVE_W32_SYSTEM
1630 if (parent_pid != (pid_t)(-1))
1632 if (kill (parent_pid, 0))
1634 shutdown_pending = 2;
1635 log_info ("parent process died - shutting down\n");
1636 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1637 cleanup ();
1638 agent_exit (0);
1641 #endif /*HAVE_W32_SYSTEM*/
1643 /* Code to be run every minute. */
1644 if (last_minute + 60 <= time (NULL))
1646 check_own_socket ();
1647 last_minute = time (NULL);
1653 /* A global function which allows us to call the reload stuff from
1654 other places too. This is only used when build for W32. */
1655 void
1656 agent_sighup_action (void)
1658 log_info ("SIGHUP received - "
1659 "re-reading configuration and flushing cache\n");
1660 agent_flush_cache ();
1661 reread_configuration ();
1662 agent_reload_trustlist ();
1666 static void
1667 agent_sigusr2_action (void)
1669 if (opt.verbose)
1670 log_info ("SIGUSR2 received - updating card event counter\n");
1671 /* Nothing to check right now. We only increment a counter. */
1672 bump_card_eventcounter ();
1676 static void
1677 handle_signal (int signo)
1679 switch (signo)
1681 #ifndef HAVE_W32_SYSTEM
1682 case SIGHUP:
1683 agent_sighup_action ();
1684 break;
1686 case SIGUSR1:
1687 log_info ("SIGUSR1 received - printing internal information:\n");
1688 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1689 agent_query_dump_state ();
1690 agent_scd_dump_state ();
1691 break;
1693 case SIGUSR2:
1694 agent_sigusr2_action ();
1695 break;
1697 case SIGTERM:
1698 if (!shutdown_pending)
1699 log_info ("SIGTERM received - shutting down ...\n");
1700 else
1701 log_info ("SIGTERM received - still %ld running threads\n",
1702 pth_ctrl( PTH_CTRL_GETTHREADS ));
1703 shutdown_pending++;
1704 if (shutdown_pending > 2)
1706 log_info ("shutdown forced\n");
1707 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1708 cleanup ();
1709 agent_exit (0);
1711 break;
1713 case SIGINT:
1714 log_info ("SIGINT received - immediate shutdown\n");
1715 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1716 cleanup ();
1717 agent_exit (0);
1718 break;
1719 #endif
1720 default:
1721 log_info ("signal %d received - no action defined\n", signo);
1726 /* Check the nonce on a new connection. This is a NOP unless we we
1727 are using our Unix domain socket emulation under Windows. */
1728 static int
1729 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1731 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1733 log_info (_("error reading nonce on fd %d: %s\n"),
1734 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1735 assuan_sock_close (ctrl->thread_startup.fd);
1736 xfree (ctrl);
1737 return -1;
1739 else
1740 return 0;
1744 /* This is the standard connection thread's main function. */
1745 static void *
1746 start_connection_thread (void *arg)
1748 ctrl_t ctrl = arg;
1750 if (check_nonce (ctrl, &socket_nonce))
1751 return NULL;
1753 agent_init_default_ctrl (ctrl);
1754 if (opt.verbose)
1755 log_info (_("handler 0x%lx for fd %d started\n"),
1756 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1758 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1759 if (opt.verbose)
1760 log_info (_("handler 0x%lx for fd %d terminated\n"),
1761 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1763 agent_deinit_default_ctrl (ctrl);
1764 xfree (ctrl);
1765 return NULL;
1769 /* This is the ssh connection thread's main function. */
1770 static void *
1771 start_connection_thread_ssh (void *arg)
1773 ctrl_t ctrl = arg;
1775 if (check_nonce (ctrl, &socket_nonce_ssh))
1776 return NULL;
1778 agent_init_default_ctrl (ctrl);
1779 if (opt.verbose)
1780 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1781 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1783 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1784 if (opt.verbose)
1785 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1786 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1788 agent_deinit_default_ctrl (ctrl);
1789 xfree (ctrl);
1790 return NULL;
1794 /* Connection handler loop. Wait for connection requests and spawn a
1795 thread after accepting a connection. */
1796 static void
1797 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1799 pth_attr_t tattr;
1800 pth_event_t ev, time_ev;
1801 sigset_t sigs;
1802 int signo;
1803 struct sockaddr_un paddr;
1804 socklen_t plen;
1805 fd_set fdset, read_fdset;
1806 int ret;
1807 gnupg_fd_t fd;
1808 int nfd;
1810 tattr = pth_attr_new();
1811 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1812 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1814 #ifndef HAVE_W32_SYSTEM /* fixme */
1815 /* Make sure that the signals we are going to handle are not blocked
1816 and create an event object for them. We also set the default
1817 action to ignore because we use an Pth event to get notified
1818 about signals. This avoids that the default action is taken in
1819 case soemthing goes wrong within Pth. The problem might also be
1820 a Pth bug. */
1821 sigemptyset (&sigs );
1823 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1824 struct sigaction sa;
1825 int i;
1827 for (i=0; i < DIM (mysigs); i++)
1829 sigemptyset (&sa.sa_mask);
1830 sa.sa_handler = SIG_IGN;
1831 sa.sa_flags = 0;
1832 sigaction (mysigs[i], &sa, NULL);
1834 sigaddset (&sigs, mysigs[i]);
1838 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1839 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1840 #else
1841 # ifdef PTH_EVENT_HANDLE
1842 sigs = 0;
1843 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1844 signo = 0;
1845 # else
1846 /* Use a dummy event. */
1847 sigs = 0;
1848 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1849 # endif
1850 #endif
1851 time_ev = NULL;
1853 FD_ZERO (&fdset);
1854 FD_SET (FD2INT (listen_fd), &fdset);
1855 nfd = FD2INT (listen_fd);
1856 if (listen_fd_ssh != GNUPG_INVALID_FD)
1858 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1859 if (FD2INT (listen_fd_ssh) > nfd)
1860 nfd = FD2INT (listen_fd_ssh);
1863 for (;;)
1865 /* Make sure that our signals are not blocked. */
1866 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1868 /* Shutdown test. */
1869 if (shutdown_pending)
1871 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1872 break; /* ready */
1874 /* Do not accept new connections but keep on running the
1875 loop to cope with the timer events. */
1876 FD_ZERO (&fdset);
1879 /* Create a timeout event if needed. To help with power saving
1880 we syncronize the ticks to the next full second. */
1881 if (!time_ev)
1883 pth_time_t nexttick;
1885 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1886 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
1888 nexttick.tv_sec++;
1889 nexttick.tv_usec = 0;
1891 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1894 /* POSIX says that fd_set should be implemented as a structure,
1895 thus a simple assignment is fine to copy the entire set. */
1896 read_fdset = fdset;
1898 if (time_ev)
1899 pth_event_concat (ev, time_ev, NULL);
1900 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1901 if (time_ev)
1902 pth_event_isolate (time_ev);
1904 if (ret == -1)
1906 if (pth_event_occurred (ev)
1907 || (time_ev && pth_event_occurred (time_ev)))
1909 if (pth_event_occurred (ev))
1911 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1912 agent_sigusr2_action ();
1913 #else
1914 handle_signal (signo);
1915 #endif
1917 if (time_ev && pth_event_occurred (time_ev))
1919 pth_event_free (time_ev, PTH_FREE_ALL);
1920 time_ev = NULL;
1921 handle_tick ();
1923 continue;
1925 log_error (_("pth_select failed: %s - waiting 1s\n"),
1926 strerror (errno));
1927 pth_sleep (1);
1928 continue;
1931 if (pth_event_occurred (ev))
1933 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1934 agent_sigusr2_action ();
1935 #else
1936 handle_signal (signo);
1937 #endif
1940 if (time_ev && pth_event_occurred (time_ev))
1942 pth_event_free (time_ev, PTH_FREE_ALL);
1943 time_ev = NULL;
1944 handle_tick ();
1948 /* We now might create new threads and because we don't want any
1949 signals (as we are handling them here) to be delivered to a
1950 new thread. Thus we need to block those signals. */
1951 pth_sigmask (SIG_BLOCK, &sigs, NULL);
1953 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
1955 ctrl_t ctrl;
1957 plen = sizeof paddr;
1958 fd = INT2FD (pth_accept (FD2INT(listen_fd),
1959 (struct sockaddr *)&paddr, &plen));
1960 if (fd == GNUPG_INVALID_FD)
1962 log_error ("accept failed: %s\n", strerror (errno));
1964 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1966 log_error ("error allocating connection control data: %s\n",
1967 strerror (errno) );
1968 assuan_sock_close (fd);
1970 else if ( !(ctrl->session_env = session_env_new ()) )
1972 log_error ("error allocating session environment block: %s\n",
1973 strerror (errno) );
1974 xfree (ctrl);
1975 assuan_sock_close (fd);
1977 else
1979 char threadname[50];
1981 snprintf (threadname, sizeof threadname-1,
1982 "conn fd=%d (gpg)", FD2INT(fd));
1983 threadname[sizeof threadname -1] = 0;
1984 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1985 ctrl->thread_startup.fd = fd;
1986 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1988 log_error ("error spawning connection handler: %s\n",
1989 strerror (errno) );
1990 assuan_sock_close (fd);
1991 xfree (ctrl);
1994 fd = GNUPG_INVALID_FD;
1997 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
1998 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
2000 ctrl_t ctrl;
2002 plen = sizeof paddr;
2003 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
2004 (struct sockaddr *)&paddr, &plen));
2005 if (fd == GNUPG_INVALID_FD)
2007 log_error ("accept failed for ssh: %s\n", strerror (errno));
2009 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
2011 log_error ("error allocating connection control data: %s\n",
2012 strerror (errno) );
2013 assuan_sock_close (fd);
2015 else if ( !(ctrl->session_env = session_env_new ()) )
2017 log_error ("error allocating session environment block: %s\n",
2018 strerror (errno) );
2019 xfree (ctrl);
2020 assuan_sock_close (fd);
2022 else
2024 char threadname[50];
2026 agent_init_default_ctrl (ctrl);
2027 snprintf (threadname, sizeof threadname-1,
2028 "conn fd=%d (ssh)", FD2INT(fd));
2029 threadname[sizeof threadname -1] = 0;
2030 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2031 ctrl->thread_startup.fd = fd;
2032 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2034 log_error ("error spawning ssh connection handler: %s\n",
2035 strerror (errno) );
2036 assuan_sock_close (fd);
2037 xfree (ctrl);
2040 fd = GNUPG_INVALID_FD;
2044 pth_event_free (ev, PTH_FREE_ALL);
2045 if (time_ev)
2046 pth_event_free (time_ev, PTH_FREE_ALL);
2047 cleanup ();
2048 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2053 /* Helper for check_own_socket. */
2054 static gpg_error_t
2055 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2057 membuf_t *mb = opaque;
2058 put_membuf (mb, buffer, length);
2059 return 0;
2063 /* The thread running the actual check. We need to run this in a
2064 separate thread so that check_own_thread can be called from the
2065 timer tick. */
2066 static void *
2067 check_own_socket_thread (void *arg)
2069 int rc;
2070 char *sockname = arg;
2071 assuan_context_t ctx = NULL;
2072 membuf_t mb;
2073 char *buffer;
2075 check_own_socket_running++;
2077 rc = assuan_new (&ctx);
2078 xfree (sockname);
2079 if (rc)
2081 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2082 goto leave;
2085 rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2086 if (rc)
2088 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2089 goto leave;
2092 init_membuf (&mb, 100);
2093 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2094 NULL, NULL, NULL, NULL);
2095 put_membuf (&mb, "", 1);
2096 buffer = get_membuf (&mb, NULL);
2097 if (rc || !buffer)
2099 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2100 "GETINFO pid", gpg_strerror (rc));
2101 rc = 1;
2103 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2105 log_error ("socket is now serviced by another server\n");
2106 rc = 1;
2108 else if (opt.verbose > 1)
2109 log_error ("socket is still served by this server\n");
2111 xfree (buffer);
2113 leave:
2114 if (ctx)
2115 assuan_release (ctx);
2116 if (rc)
2118 /* We may not remove the socket as it is now in use by another
2119 server. Setting the name to empty does this. */
2120 if (socket_name)
2121 *socket_name = 0;
2122 if (socket_name_ssh)
2123 *socket_name_ssh = 0;
2124 shutdown_pending = 2;
2125 log_info ("this process is useless - shutting down\n");
2127 check_own_socket_running--;
2128 return NULL;
2132 /* Check whether we are still listening on our own socket. In case
2133 another gpg-agent process started after us has taken ownership of
2134 our socket, we woul linger around without any real taks. Thus we
2135 better check once in a while whether we are really needed. */
2136 static void
2137 check_own_socket (void)
2139 char *sockname;
2140 pth_attr_t tattr;
2142 if (!use_standard_socket)
2143 return; /* This check makes only sense in standard socket mode. */
2145 if (check_own_socket_running || shutdown_pending)
2146 return; /* Still running or already shutting down. */
2148 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2149 if (!sockname)
2150 return; /* Out of memory. */
2152 tattr = pth_attr_new();
2153 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2154 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2155 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2157 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2158 log_error ("error spawning check_own_socket_thread: %s\n",
2159 strerror (errno) );
2160 pth_attr_destroy (tattr);
2165 /* Figure out whether an agent is available and running. Prints an
2166 error if not. If SILENT is true, no messages are printed. Usually
2167 started with MODE 0. Returns 0 if the agent is running. */
2168 static int
2169 check_for_running_agent (int silent, int mode)
2171 int rc;
2172 char *infostr, *p;
2173 assuan_context_t ctx = NULL;
2174 int prot, pid;
2176 if (!mode)
2178 infostr = getenv ("GPG_AGENT_INFO");
2179 if (!infostr || !*infostr)
2181 if (!check_for_running_agent (silent, 1))
2182 return 0; /* Okay, its running on the standard socket. */
2183 if (!silent)
2184 log_error (_("no gpg-agent running in this session\n"));
2185 return -1;
2188 infostr = xstrdup (infostr);
2189 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2191 xfree (infostr);
2192 if (!check_for_running_agent (silent, 1))
2193 return 0; /* Okay, its running on the standard socket. */
2194 if (!silent)
2195 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2196 return -1;
2199 *p++ = 0;
2200 pid = atoi (p);
2201 while (*p && *p != PATHSEP_C)
2202 p++;
2203 prot = *p? atoi (p+1) : 0;
2204 if (prot != 1)
2206 xfree (infostr);
2207 if (!silent)
2208 log_error (_("gpg-agent protocol version %d is not supported\n"),
2209 prot);
2210 if (!check_for_running_agent (silent, 1))
2211 return 0; /* Okay, its running on the standard socket. */
2212 return -1;
2215 else /* MODE != 0 */
2217 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2218 pid = (pid_t)(-1);
2221 rc = assuan_new (&ctx);
2222 if (! rc)
2223 rc = assuan_socket_connect (ctx, infostr, pid, 0);
2224 xfree (infostr);
2225 if (rc)
2227 if (!mode && !check_for_running_agent (silent, 1))
2228 return 0; /* Okay, its running on the standard socket. */
2230 if (!mode && !silent)
2231 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2233 if (ctx)
2234 assuan_release (ctx);
2235 return -1;
2238 if (!opt.quiet && !silent)
2239 log_info ("gpg-agent running and available\n");
2241 assuan_release (ctx);
2242 return 0;