Import/export of pkcs#12 now uses the gpg-agent directly.
[gnupg.git] / agent / gpg-agent.c
blobb5f9a47e20fc0bb791b7f50db756d3f0f93e5a2d
1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2009 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <time.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #ifndef HAVE_W32_SYSTEM
34 # include <sys/socket.h>
35 # include <sys/un.h>
36 #endif /*!HAVE_W32_SYSTEM*/
37 #include <unistd.h>
38 #include <signal.h>
39 #include <pth.h>
41 #define JNLIB_NEED_LOG_LOGV
42 #include "agent.h"
43 #include <assuan.h> /* Malloc hooks and socket wrappers. */
45 #include "i18n.h"
46 #include "mkdtemp.h" /* Gnulib replacement. */
47 #include "sysutils.h"
48 #include "setenv.h"
49 #include "gc-opt-flags.h"
50 #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 GCRY_THREAD_OPTION_PTH_IMPL;
279 static int fixed_gcry_pth_init (void)
281 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
285 #ifndef PTH_HAVE_PTH_THREAD_ID
286 static unsigned long pth_thread_id (void)
288 return (unsigned long)pth_self ();
290 #endif
295 Functions.
298 static char *
299 make_libversion (const char *libname, const char *(*getfnc)(const char*))
301 const char *s;
302 char *result;
304 if (maybe_setuid)
306 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
307 maybe_setuid = 0;
309 s = getfnc (NULL);
310 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
311 strcpy (stpcpy (stpcpy (result, libname), " "), s);
312 return result;
316 static const char *
317 my_strusage (int level)
319 static char *ver_gcry;
320 const char *p;
322 switch (level)
324 case 11: p = "gpg-agent (GnuPG)";
325 break;
326 case 13: p = VERSION; break;
327 case 17: p = PRINTABLE_OS_NAME; break;
328 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
329 break;
330 case 20:
331 if (!ver_gcry)
332 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
333 p = ver_gcry;
334 break;
336 case 1:
337 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
338 break;
339 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
340 "Secret key management for GnuPG\n");
341 break;
343 default: p = NULL;
345 return p;
350 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
351 only the active debug flags are propagated to the subsystems. With
352 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
353 all flags already set. Note that we don't fail here, because it is
354 important to keep gpg-agent running even after re-reading the
355 options due to a SIGHUP. */
356 static void
357 set_debug (void)
359 if (!debug_level)
361 else if (!strcmp (debug_level, "none"))
362 opt.debug = 0;
363 else if (!strcmp (debug_level, "basic"))
364 opt.debug = DBG_ASSUAN_VALUE;
365 else if (!strcmp (debug_level, "advanced"))
366 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
367 else if (!strcmp (debug_level, "expert"))
368 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
369 |DBG_CACHE_VALUE);
370 else if (!strcmp (debug_level, "guru"))
371 opt.debug = ~0;
372 else
374 log_error (_("invalid debug-level `%s' given\n"), debug_level);
375 opt.debug = 0; /* Reset debugging, so that prior debug
376 statements won't have an undesired effect. */
379 if (opt.debug && !opt.verbose)
380 opt.verbose = 1;
381 if (opt.debug && opt.quiet)
382 opt.quiet = 0;
384 if (opt.debug & DBG_MPI_VALUE)
385 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
386 if (opt.debug & DBG_CRYPTO_VALUE )
387 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
388 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
392 /* Helper for cleanup to remove one socket with NAME. */
393 static void
394 remove_socket (char *name)
396 if (name && *name)
398 char *p;
400 remove (name);
401 p = strrchr (name, '/');
402 if (p)
404 *p = 0;
405 rmdir (name);
406 *p = '/';
408 *name = 0;
412 static void
413 cleanup (void)
415 remove_socket (socket_name);
416 remove_socket (socket_name_ssh);
421 /* Handle options which are allowed to be reset after program start.
422 Return true when the current option in PARGS could be handled and
423 false if not. As a special feature, passing a value of NULL for
424 PARGS, resets the options to the default. REREAD should be set
425 true if it is not the initial option parsing. */
426 static int
427 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
429 if (!pargs)
430 { /* reset mode */
431 opt.quiet = 0;
432 opt.verbose = 0;
433 opt.debug = 0;
434 opt.no_grab = 0;
435 opt.pinentry_program = NULL;
436 opt.pinentry_touch_file = NULL;
437 opt.scdaemon_program = NULL;
438 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
439 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
440 opt.max_cache_ttl = MAX_CACHE_TTL;
441 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
442 opt.enforce_passphrase_constraints = 0;
443 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
444 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
445 opt.check_passphrase_pattern = NULL;
446 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
447 opt.enable_passhrase_history = 0;
448 opt.ignore_cache_for_signing = 0;
449 opt.allow_mark_trusted = 0;
450 opt.disable_scdaemon = 0;
451 return 1;
454 switch (pargs->r_opt)
456 case oQuiet: opt.quiet = 1; break;
457 case oVerbose: opt.verbose++; break;
459 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
460 case oDebugAll: opt.debug = ~0; break;
461 case oDebugLevel: debug_level = pargs->r.ret_str; break;
463 case oLogFile:
464 if (!reread)
465 return 0; /* not handeld */
466 if (!current_logfile || !pargs->r.ret_str
467 || strcmp (current_logfile, pargs->r.ret_str))
469 log_set_file (pargs->r.ret_str);
470 assuan_set_assuan_log_stream (log_get_stream ());
471 xfree (current_logfile);
472 current_logfile = xtrystrdup (pargs->r.ret_str);
474 break;
476 case oNoGrab: opt.no_grab = 1; break;
478 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
479 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
480 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
481 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
483 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
484 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
485 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
486 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
488 case oEnforcePassphraseConstraints:
489 opt.enforce_passphrase_constraints=1;
490 break;
491 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
492 case oMinPassphraseNonalpha:
493 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
494 break;
495 case oCheckPassphrasePattern:
496 opt.check_passphrase_pattern = pargs->r.ret_str;
497 break;
498 case oMaxPassphraseDays:
499 opt.max_passphrase_days = pargs->r.ret_ulong;
500 break;
501 case oEnablePassphraseHistory:
502 opt.enable_passhrase_history = 1;
503 break;
505 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
507 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
509 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
511 default:
512 return 0; /* not handled */
515 return 1; /* handled */
519 /* The main entry point. */
521 main (int argc, char **argv )
523 ARGPARSE_ARGS pargs;
524 int orig_argc;
525 int may_coredump;
526 char **orig_argv;
527 FILE *configfp = NULL;
528 char *configname = NULL;
529 const char *shell;
530 unsigned configlineno;
531 int parse_debug = 0;
532 int default_config =1;
533 int greeting = 0;
534 int nogreeting = 0;
535 int pipe_server = 0;
536 int is_daemon = 0;
537 int nodetach = 0;
538 int csh_style = 0;
539 char *logfile = NULL;
540 int debug_wait = 0;
541 int gpgconf_list = 0;
542 gpg_error_t err;
543 const char *env_file_name = NULL;
546 /* Before we do anything else we save the list of currently open
547 file descriptors and the signal mask. This info is required to
548 do the exec call properly. */
549 startup_fd_list = get_all_open_fds ();
550 #ifdef HAVE_SIGPROCMASK
551 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
552 startup_signal_mask_valid = 1;
553 #endif /*HAVE_SIGPROCMASK*/
555 /* Set program name etc. */
556 set_strusage (my_strusage);
557 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
558 /* Please note that we may running SUID(ROOT), so be very CAREFUL
559 when adding any stuff between here and the call to INIT_SECMEM()
560 somewhere after the option parsing */
561 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
563 /* Make sure that our subsystems are ready. */
564 i18n_init ();
565 init_common_subsystems ();
568 /* Libgcrypt requires us to register the threading model first.
569 Note that this will also do the pth_init. */
570 gcry_threads_pth.init = fixed_gcry_pth_init;
571 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
572 if (err)
574 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
575 gpg_strerror (err));
579 /* Check that the libraries are suitable. Do it here because
580 the option parsing may need services of the library. */
581 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
583 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
584 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
587 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
588 assuan_set_assuan_log_stream (log_get_stream ());
589 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
590 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
592 setup_libgcrypt_logging ();
593 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
595 may_coredump = disable_core_dumps ();
597 /* Set default options. */
598 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
599 #ifdef HAVE_W32_SYSTEM
600 use_standard_socket = 1; /* Under Windows we always use a standard
601 socket. */
602 #endif
604 shell = getenv ("SHELL");
605 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
606 csh_style = 1;
608 opt.homedir = default_homedir ();
610 /* Record some of the original environment strings. */
611 opt.startup_display = getenv ("DISPLAY");
612 if (opt.startup_display)
613 opt.startup_display = xstrdup (opt.startup_display);
614 opt.startup_ttyname = ttyname (0);
615 if (opt.startup_ttyname)
616 opt.startup_ttyname = xstrdup (opt.startup_ttyname);
617 opt.startup_ttytype = getenv ("TERM");
618 if (opt.startup_ttytype)
619 opt.startup_ttytype = xstrdup (opt.startup_ttytype);
620 /* Fixme: Better use the locale function here. */
621 opt.startup_lc_ctype = getenv ("LC_CTYPE");
622 if (opt.startup_lc_ctype)
623 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
624 opt.startup_lc_messages = getenv ("LC_MESSAGES");
625 if (opt.startup_lc_messages)
626 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
627 opt.startup_xauthority = getenv ("XAUTHORITY");
628 if (opt.startup_xauthority)
629 opt.startup_xauthority = xstrdup (opt.startup_xauthority);
630 opt.startup_pinentry_user_data = getenv ("PINENTRY_USER_DATA");
631 if (opt.startup_pinentry_user_data)
632 opt.startup_pinentry_user_data = xstrdup (opt.startup_pinentry_user_data);
634 /* Check whether we have a config file on the commandline */
635 orig_argc = argc;
636 orig_argv = argv;
637 pargs.argc = &argc;
638 pargs.argv = &argv;
639 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
640 while (arg_parse( &pargs, opts))
642 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
643 parse_debug++;
644 else if (pargs.r_opt == oOptions)
645 { /* yes there is one, so we do not try the default one, but
646 read the option file when it is encountered at the
647 commandline */
648 default_config = 0;
650 else if (pargs.r_opt == oNoOptions)
651 default_config = 0; /* --no-options */
652 else if (pargs.r_opt == oHomedir)
653 opt.homedir = pargs.r.ret_str;
656 /* Initialize the secure memory. */
657 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
658 maybe_setuid = 0;
661 Now we are now working under our real uid
664 if (default_config)
665 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
667 argc = orig_argc;
668 argv = orig_argv;
669 pargs.argc = &argc;
670 pargs.argv = &argv;
671 pargs.flags= 1; /* do not remove the args */
672 next_pass:
673 if (configname)
675 configlineno = 0;
676 configfp = fopen (configname, "r");
677 if (!configfp)
679 if (default_config)
681 if( parse_debug )
682 log_info (_("NOTE: no default option file `%s'\n"),
683 configname );
685 else
687 log_error (_("option file `%s': %s\n"),
688 configname, strerror(errno) );
689 exit(2);
691 xfree (configname);
692 configname = NULL;
694 if (parse_debug && configname )
695 log_info (_("reading options from `%s'\n"), configname );
696 default_config = 0;
699 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
701 if (parse_rereadable_options (&pargs, 0))
702 continue; /* Already handled */
703 switch (pargs.r_opt)
705 case aGPGConfList: gpgconf_list = 1; break;
706 case aGPGConfTest: gpgconf_list = 2; break;
707 case oBatch: opt.batch=1; break;
709 case oDebugWait: debug_wait = pargs.r.ret_int; break;
711 case oOptions:
712 /* config files may not be nested (silently ignore them) */
713 if (!configfp)
715 xfree(configname);
716 configname = xstrdup(pargs.r.ret_str);
717 goto next_pass;
719 break;
720 case oNoGreeting: nogreeting = 1; break;
721 case oNoVerbose: opt.verbose = 0; break;
722 case oNoOptions: break; /* no-options */
723 case oHomedir: opt.homedir = pargs.r.ret_str; break;
724 case oNoDetach: nodetach = 1; break;
725 case oLogFile: logfile = pargs.r.ret_str; break;
726 case oCsh: csh_style = 1; break;
727 case oSh: csh_style = 0; break;
728 case oServer: pipe_server = 1; break;
729 case oDaemon: is_daemon = 1; break;
731 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
732 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
733 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
734 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
735 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
736 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
737 break;
739 case oUseStandardSocket: use_standard_socket = 1; break;
740 case oNoUseStandardSocket: use_standard_socket = 0; break;
742 case oFakedSystemTime:
744 time_t faked_time = isotime2epoch (pargs.r.ret_str);
745 if (faked_time == (time_t)(-1))
746 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
747 gnupg_set_time (faked_time, 0);
749 break;
751 case oKeepTTY: opt.keep_tty = 1; break;
752 case oKeepDISPLAY: opt.keep_display = 1; break;
754 case oSSHSupport: opt.ssh_support = 1; break;
755 case oWriteEnvFile:
756 if (pargs.r_type)
757 env_file_name = pargs.r.ret_str;
758 else
759 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
760 break;
762 default : pargs.err = configfp? 1:2; break;
765 if (configfp)
767 fclose( configfp );
768 configfp = NULL;
769 /* Keep a copy of the name so that it can be read on SIGHUP. */
770 config_filename = configname;
771 configname = NULL;
772 goto next_pass;
774 xfree (configname);
775 configname = NULL;
776 if (log_get_errorcount(0))
777 exit(2);
778 if (nogreeting )
779 greeting = 0;
781 if (greeting)
783 fprintf (stderr, "%s %s; %s\n",
784 strusage(11), strusage(13), strusage(14) );
785 fprintf (stderr, "%s\n", strusage(15) );
787 #ifdef IS_DEVELOPMENT_VERSION
788 /* We don't want to print it here because gpg-agent is useful of its
789 own and quite matured. */
790 /*log_info ("NOTE: this is a development version!\n");*/
791 #endif
793 set_debug ();
795 if (atexit (cleanup))
797 log_error ("atexit failed\n");
798 cleanup ();
799 exit (1);
802 initialize_module_call_pinentry ();
803 initialize_module_call_scd ();
804 initialize_module_trustlist ();
806 /* Try to create missing directories. */
807 create_directories ();
809 if (debug_wait && pipe_server)
811 log_debug ("waiting for debugger - my pid is %u .....\n",
812 (unsigned int)getpid());
813 gnupg_sleep (debug_wait);
814 log_debug ("... okay\n");
817 if (gpgconf_list == 2)
818 agent_exit (0);
819 if (gpgconf_list)
821 char *filename;
822 char *filename_esc;
824 /* List options and default values in the GPG Conf format. */
825 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
826 filename_esc = percent_escape (filename, NULL);
828 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
829 GC_OPT_FLAG_DEFAULT, filename_esc);
830 xfree (filename);
831 xfree (filename_esc);
833 printf ("verbose:%lu:\n"
834 "quiet:%lu:\n"
835 "debug-level:%lu:\"none:\n"
836 "log-file:%lu:\n",
837 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
838 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
839 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
840 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
841 printf ("default-cache-ttl:%lu:%d:\n",
842 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
843 printf ("default-cache-ttl-ssh:%lu:%d:\n",
844 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
845 printf ("max-cache-ttl:%lu:%d:\n",
846 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
847 printf ("max-cache-ttl-ssh:%lu:%d:\n",
848 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
849 printf ("enforce-passphrase-constraints:%lu:\n",
850 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
851 printf ("min-passphrase-len:%lu:%d:\n",
852 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
853 printf ("min-passphrase-nonalpha:%lu:%d:\n",
854 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
855 MIN_PASSPHRASE_NONALPHA);
856 printf ("check-passphrase-pattern:%lu:\n",
857 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
858 printf ("max-passphrase-days:%lu:%d:\n",
859 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
860 MAX_PASSPHRASE_DAYS);
861 printf ("enable-passphrase-history:%lu:\n",
862 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
863 printf ("no-grab:%lu:\n",
864 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
865 printf ("ignore-cache-for-signing:%lu:\n",
866 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
867 printf ("allow-mark-trusted:%lu:\n",
868 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
869 printf ("disable-scdaemon:%lu:\n",
870 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
872 agent_exit (0);
875 /* If this has been called without any options, we merely check
876 whether an agent is already running. We do this here so that we
877 don't clobber a logfile but print it directly to stderr. */
878 if (!pipe_server && !is_daemon)
880 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
881 check_for_running_agent (0, 0);
882 agent_exit (0);
885 #ifdef ENABLE_NLS
886 /* gpg-agent usually does not output any messages because it runs in
887 the background. For log files it is acceptable to have messages
888 always encoded in utf-8. We switch here to utf-8, so that
889 commands like --help still give native messages. It is far
890 easier to switch only once instead of for every message and it
891 actually helps when more then one thread is active (avoids an
892 extra copy step). */
893 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
894 #endif
896 /* Now start with logging to a file if this is desired. */
897 if (logfile)
899 log_set_file (logfile);
900 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
901 |JNLIB_LOG_WITH_TIME
902 |JNLIB_LOG_WITH_PID));
903 current_logfile = xstrdup (logfile);
904 assuan_set_assuan_log_stream (log_get_stream ());
907 /* Make sure that we have a default ttyname. */
908 if (!default_ttyname && ttyname (1))
909 default_ttyname = xstrdup (ttyname (1));
910 if (!default_ttytype && getenv ("TERM"))
911 default_ttytype = xstrdup (getenv ("TERM"));
914 if (pipe_server)
916 /* This is the simple pipe based server */
917 ctrl_t ctrl;
919 ctrl = xtrycalloc (1, sizeof *ctrl);
920 if (!ctrl)
922 log_error ("error allocating connection control data: %s\n",
923 strerror (errno) );
924 agent_exit (1);
926 agent_init_default_ctrl (ctrl);
927 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
928 agent_deinit_default_ctrl (ctrl);
929 xfree (ctrl);
931 else if (!is_daemon)
932 ; /* NOTREACHED */
933 else
934 { /* Regular server mode */
935 gnupg_fd_t fd;
936 gnupg_fd_t fd_ssh;
937 pid_t pid;
939 /* Remove the DISPLAY variable so that a pinentry does not
940 default to a specific display. There is still a default
941 display when gpg-agent was started using --display or a
942 client requested this using an OPTION command. Note, that we
943 don't do this when running in reverse daemon mode (i.e. when
944 exec the program given as arguments). */
945 #ifndef HAVE_W32_SYSTEM
946 if (!opt.keep_display && !argc)
947 unsetenv ("DISPLAY");
948 #endif
951 /* Create the sockets. */
952 socket_name = create_socket_name
953 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
954 if (opt.ssh_support)
955 socket_name_ssh = create_socket_name
956 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
958 fd = create_server_socket (socket_name, 0, &socket_nonce);
959 if (opt.ssh_support)
960 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
961 else
962 fd_ssh = GNUPG_INVALID_FD;
964 /* If we are going to exec a program in the parent, we record
965 the PID, so that the child may check whether the program is
966 still alive. */
967 if (argc)
968 parent_pid = getpid ();
970 fflush (NULL);
971 #ifdef HAVE_W32_SYSTEM
972 pid = getpid ();
973 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
974 #else /*!HAVE_W32_SYSTEM*/
975 pid = fork ();
976 if (pid == (pid_t)-1)
978 log_fatal ("fork failed: %s\n", strerror (errno) );
979 exit (1);
981 else if (pid)
982 { /* We are the parent */
983 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
985 /* Close the socket FD. */
986 close (fd);
988 /* Note that we used a standard fork so that Pth runs in
989 both the parent and the child. The pth_fork would
990 terminate Pth in the child but that is not the way we
991 want it. Thus we use a plain fork and terminate Pth here
992 in the parent. The pth_kill may or may not work reliable
993 but it should not harm to call it. Because Pth fiddles
994 with the signal mask the signal mask might not be correct
995 right now and thus we restore it. That is not strictly
996 necessary but some programs falsely assume a cleared
997 signal mask. */
998 #ifdef HAVE_SIGPROCMASK
999 if (startup_signal_mask_valid)
1001 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1002 log_error ("error restoring signal mask: %s\n",
1003 strerror (errno));
1005 else
1006 log_info ("no saved signal mask\n");
1007 #endif /*HAVE_SIGPROCMASK*/
1009 /* Create the info string: <name>:<pid>:<protocol_version> */
1010 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1011 socket_name, (ulong)pid ) < 0)
1013 log_error ("out of core\n");
1014 kill (pid, SIGTERM);
1015 exit (1);
1017 if (opt.ssh_support)
1019 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1020 socket_name_ssh) < 0)
1022 log_error ("out of core\n");
1023 kill (pid, SIGTERM);
1024 exit (1);
1026 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1027 pid) < 0)
1029 log_error ("out of core\n");
1030 kill (pid, SIGTERM);
1031 exit (1);
1035 *socket_name = 0; /* Don't let cleanup() remove the socket -
1036 the child should do this from now on */
1037 if (opt.ssh_support)
1038 *socket_name_ssh = 0;
1040 if (env_file_name)
1042 FILE *fp;
1044 fp = fopen (env_file_name, "w");
1045 if (!fp)
1046 log_error (_("error creating `%s': %s\n"),
1047 env_file_name, strerror (errno));
1048 else
1050 fputs (infostr, fp);
1051 putc ('\n', fp);
1052 if (opt.ssh_support)
1054 fputs (infostr_ssh_sock, fp);
1055 putc ('\n', fp);
1056 fputs (infostr_ssh_pid, fp);
1057 putc ('\n', fp);
1059 fclose (fp);
1064 if (argc)
1065 { /* Run the program given on the commandline. */
1066 if (putenv (infostr))
1068 log_error ("failed to set environment: %s\n",
1069 strerror (errno) );
1070 kill (pid, SIGTERM );
1071 exit (1);
1073 if (opt.ssh_support && putenv (infostr_ssh_sock))
1075 log_error ("failed to set environment: %s\n",
1076 strerror (errno) );
1077 kill (pid, SIGTERM );
1078 exit (1);
1080 if (opt.ssh_support && putenv (infostr_ssh_pid))
1082 log_error ("failed to set environment: %s\n",
1083 strerror (errno) );
1084 kill (pid, SIGTERM );
1085 exit (1);
1088 /* Close all the file descriptors except the standard
1089 ones and those open at startup. We explicitly don't
1090 close 0,1,2 in case something went wrong collecting
1091 them at startup. */
1092 close_all_fds (3, startup_fd_list);
1094 /* Run the command. */
1095 execvp (argv[0], argv);
1096 log_error ("failed to run the command: %s\n", strerror (errno));
1097 kill (pid, SIGTERM);
1098 exit (1);
1100 else
1102 /* Print the environment string, so that the caller can use
1103 shell's eval to set it */
1104 if (csh_style)
1106 *strchr (infostr, '=') = ' ';
1107 printf ("setenv %s\n", infostr);
1108 if (opt.ssh_support)
1110 *strchr (infostr_ssh_sock, '=') = ' ';
1111 printf ("setenv %s\n", infostr_ssh_sock);
1112 *strchr (infostr_ssh_pid, '=') = ' ';
1113 printf ("setenv %s\n", infostr_ssh_pid);
1116 else
1118 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1119 if (opt.ssh_support)
1121 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1122 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1125 xfree (infostr);
1126 if (opt.ssh_support)
1128 xfree (infostr_ssh_sock);
1129 xfree (infostr_ssh_pid);
1131 exit (0);
1133 /*NOTREACHED*/
1134 } /* End parent */
1137 This is the child
1140 /* Detach from tty and put process into a new session */
1141 if (!nodetach )
1143 int i;
1144 unsigned int oldflags;
1146 /* Close stdin, stdout and stderr unless it is the log stream */
1147 for (i=0; i <= 2; i++)
1149 if (!log_test_fd (i) && i != fd )
1151 if ( ! close (i)
1152 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1154 log_error ("failed to open `%s': %s\n",
1155 "/dev/null", strerror (errno));
1156 cleanup ();
1157 exit (1);
1161 if (setsid() == -1)
1163 log_error ("setsid() failed: %s\n", strerror(errno) );
1164 cleanup ();
1165 exit (1);
1168 log_get_prefix (&oldflags);
1169 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1170 opt.running_detached = 1;
1173 if (chdir("/"))
1175 log_error ("chdir to / failed: %s\n", strerror (errno));
1176 exit (1);
1180 struct sigaction sa;
1182 sa.sa_handler = SIG_IGN;
1183 sigemptyset (&sa.sa_mask);
1184 sa.sa_flags = 0;
1185 sigaction (SIGPIPE, &sa, NULL);
1187 #endif /*!HAVE_W32_SYSTEM*/
1189 log_info ("%s %s started\n", strusage(11), strusage(13) );
1190 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1191 assuan_sock_close (fd);
1194 return 0;
1198 void
1199 agent_exit (int rc)
1201 /*FIXME: update_random_seed_file();*/
1202 #if 1
1203 /* at this time a bit annoying */
1204 if (opt.debug & DBG_MEMSTAT_VALUE)
1206 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1207 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1209 if (opt.debug)
1210 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1211 #endif
1212 gcry_control (GCRYCTL_TERM_SECMEM );
1213 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1214 exit (rc);
1217 static void
1218 agent_init_default_ctrl (ctrl_t ctrl)
1220 /* Note we ignore malloc errors because we can't do much about it
1221 and the request will fail anyway shortly after this
1222 initialization. */
1223 if (ctrl->display)
1224 xfree (ctrl->display);
1225 ctrl->display = default_display? xtrystrdup (default_display) : NULL;
1227 if (ctrl->ttyname)
1228 xfree (ctrl->ttyname);
1229 ctrl->ttyname = default_ttyname? xtrystrdup (default_ttyname) : NULL;
1231 if (ctrl->ttytype)
1232 xfree (ctrl->ttytype);
1233 ctrl->ttytype = default_ttytype? xtrystrdup (default_ttytype) : NULL;
1235 if (ctrl->lc_ctype)
1236 xfree (ctrl->lc_ctype);
1237 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1239 if (ctrl->lc_messages)
1240 xfree (ctrl->lc_messages);
1241 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1242 /**/ : NULL;
1244 if (ctrl->xauthority)
1245 xfree (ctrl->xauthority);
1246 ctrl->xauthority = default_xauthority? xtrystrdup (default_xauthority)
1247 /**/: NULL;
1249 if (ctrl->pinentry_user_data)
1250 xfree (ctrl->pinentry_user_data);
1251 ctrl->pinentry_user_data = NULL;
1255 static void
1256 agent_deinit_default_ctrl (ctrl_t ctrl)
1258 if (ctrl->display)
1259 xfree (ctrl->display);
1260 if (ctrl->ttyname)
1261 xfree (ctrl->ttyname);
1262 if (ctrl->ttytype)
1263 xfree (ctrl->ttytype);
1264 if (ctrl->lc_ctype)
1265 xfree (ctrl->lc_ctype);
1266 if (ctrl->lc_messages)
1267 xfree (ctrl->lc_messages);
1268 if (ctrl->xauthority)
1269 xfree (ctrl->xauthority);
1270 if (ctrl->pinentry_user_data)
1271 xfree (ctrl->pinentry_user_data);
1274 /* Reread parts of the configuration. Note, that this function is
1275 obviously not thread-safe and should only be called from the PTH
1276 signal handler.
1278 Fixme: Due to the way the argument parsing works, we create a
1279 memory leak here for all string type arguments. There is currently
1280 no clean way to tell whether the memory for the argument has been
1281 allocated or points into the process' original arguments. Unless
1282 we have a mechanism to tell this, we need to live on with this. */
1283 static void
1284 reread_configuration (void)
1286 ARGPARSE_ARGS pargs;
1287 FILE *fp;
1288 unsigned int configlineno = 0;
1289 int dummy;
1291 if (!config_filename)
1292 return; /* No config file. */
1294 fp = fopen (config_filename, "r");
1295 if (!fp)
1297 log_error (_("option file `%s': %s\n"),
1298 config_filename, strerror(errno) );
1299 return;
1302 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1304 memset (&pargs, 0, sizeof pargs);
1305 dummy = 0;
1306 pargs.argc = &dummy;
1307 pargs.flags = 1; /* do not remove the args */
1308 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1310 if (pargs.r_opt < -1)
1311 pargs.err = 1; /* Print a warning. */
1312 else /* Try to parse this option - ignore unchangeable ones. */
1313 parse_rereadable_options (&pargs, 1);
1315 fclose (fp);
1316 set_debug ();
1320 /* Return the file name of the socket we are using for native
1321 requests. */
1322 const char *
1323 get_agent_socket_name (void)
1325 const char *s = socket_name;
1327 return (s && *s)? s : NULL;
1330 /* Return the file name of the socket we are using for SSH
1331 requests. */
1332 const char *
1333 get_agent_ssh_socket_name (void)
1335 const char *s = socket_name_ssh;
1337 return (s && *s)? s : NULL;
1341 /* Under W32, this function returns the handle of the scdaemon
1342 notification event. Calling it the first time creates that
1343 event. */
1344 #ifdef HAVE_W32_SYSTEM
1345 void *
1346 get_agent_scd_notify_event (void)
1348 static HANDLE the_event;
1350 if (!the_event)
1352 HANDLE h, h2;
1353 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1355 /* We need to use manual reset evet object due to the way our
1356 w32-pth wait function works: If we would use an automatic
1357 reset event we are not able to figure out which handle has
1358 been signaled because at the time we single out the signaled
1359 handles using WFSO the event has already been reset due to
1360 the WFMO. */
1361 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1362 if (!h)
1363 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1364 else if (!DuplicateHandle (GetCurrentProcess(), h,
1365 GetCurrentProcess(), &h2,
1366 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1368 log_error ("setting syncronize for scd notify event failed: %s\n",
1369 w32_strerror (-1) );
1370 CloseHandle (h);
1372 else
1374 CloseHandle (h);
1375 the_event = h2;
1379 log_debug ("returning notify handle %p\n", the_event);
1380 return the_event;
1382 #endif /*HAVE_W32_SYSTEM*/
1386 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1387 true using STANDARD_NAME in the home directory or if given as
1388 false from the mkdir type name TEMPLATE. In the latter case a
1389 unique name in a unique new directory will be created. In both
1390 cases check for valid characters as well as against a maximum
1391 allowed length for a unix domain socket is done. The function
1392 terminates the process in case of an error. Returns: Pointer to an
1393 allocated string with the absolute name of the socket used. */
1394 static char *
1395 create_socket_name (char *standard_name, char *template)
1397 char *name, *p;
1399 if (use_standard_socket)
1400 name = make_filename (opt.homedir, standard_name, NULL);
1401 else
1403 name = xstrdup (template);
1404 p = strrchr (name, '/');
1405 if (!p)
1406 BUG ();
1407 *p = 0;
1408 if (!mkdtemp (name))
1410 log_error (_("can't create directory `%s': %s\n"),
1411 name, strerror (errno));
1412 agent_exit (2);
1414 *p = '/';
1417 if (strchr (name, PATHSEP_C))
1419 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1420 agent_exit (2);
1422 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1424 log_error (_("name of socket too long\n"));
1425 agent_exit (2);
1427 return name;
1432 /* Create a Unix domain socket with NAME. Returns the file descriptor
1433 or terminates the process in case of an error. Not that this
1434 function needs to be used for the regular socket first and only
1435 then for the ssh socket. */
1436 static gnupg_fd_t
1437 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1439 struct sockaddr_un *serv_addr;
1440 socklen_t len;
1441 gnupg_fd_t fd;
1442 int rc;
1444 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1445 if (fd == ASSUAN_INVALID_FD)
1447 log_error (_("can't create socket: %s\n"), strerror (errno));
1448 agent_exit (2);
1451 serv_addr = xmalloc (sizeof (*serv_addr));
1452 memset (serv_addr, 0, sizeof *serv_addr);
1453 serv_addr->sun_family = AF_UNIX;
1454 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1456 log_error (_("socket name `%s' is too long\n"), name);
1457 agent_exit (2);
1459 strcpy (serv_addr->sun_path, name);
1460 len = (offsetof (struct sockaddr_un, sun_path)
1461 + strlen (serv_addr->sun_path) + 1);
1463 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1464 if (use_standard_socket && rc == -1 && errno == EADDRINUSE)
1466 /* Check whether a gpg-agent is already running on the standard
1467 socket. We do this test only if this is not the ssh socket.
1468 For ssh we assume that a test for gpg-agent has already been
1469 done and reuse the requested ssh socket. Testing the
1470 ssh-socket is not possible because at this point, though we
1471 know the new Assuan socket, the Assuan server and thus the
1472 ssh-agent server is not yet operational. This would lead to
1473 a hang. */
1474 if (!is_ssh && !check_for_running_agent (1, 1))
1476 log_error (_("a gpg-agent is already running - "
1477 "not starting a new one\n"));
1478 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1479 assuan_sock_close (fd);
1480 agent_exit (2);
1482 remove (name);
1483 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1485 if (rc != -1
1486 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1487 log_error (_("error getting nonce for the socket\n"));
1488 if (rc == -1)
1490 /* We use gpg_strerror here because it allows us to get strings
1491 for some W32 socket error codes. */
1492 log_error (_("error binding socket to `%s': %s\n"),
1493 serv_addr->sun_path,
1494 gpg_strerror (gpg_error_from_errno (errno)));
1496 assuan_sock_close (fd);
1497 if (use_standard_socket)
1498 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1499 agent_exit (2);
1502 if (listen (FD2INT(fd), 5 ) == -1)
1504 log_error (_("listen() failed: %s\n"), strerror (errno));
1505 assuan_sock_close (fd);
1506 agent_exit (2);
1509 if (opt.verbose)
1510 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1512 return fd;
1516 /* Check that the directory for storing the private keys exists and
1517 create it if not. This function won't fail as it is only a
1518 convenience function and not strictly necessary. */
1519 static void
1520 create_private_keys_directory (const char *home)
1522 char *fname;
1523 struct stat statbuf;
1525 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1526 if (stat (fname, &statbuf) && errno == ENOENT)
1528 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1529 if (!CreateDirectory (fname, NULL))
1530 log_error (_("can't create directory `%s': %s\n"),
1531 fname, w32_strerror (-1) );
1532 #else
1533 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1534 log_error (_("can't create directory `%s': %s\n"),
1535 fname, strerror (errno) );
1536 #endif
1537 else if (!opt.quiet)
1538 log_info (_("directory `%s' created\n"), fname);
1540 xfree (fname);
1543 /* Create the directory only if the supplied directory name is the
1544 same as the default one. This way we avoid to create arbitrary
1545 directories when a non-default home directory is used. To cope
1546 with HOME, we compare only the suffix if we see that the default
1547 homedir does start with a tilde. We don't stop here in case of
1548 problems because other functions will throw an error anyway.*/
1549 static void
1550 create_directories (void)
1552 struct stat statbuf;
1553 const char *defhome = standard_homedir ();
1554 char *home;
1556 home = make_filename (opt.homedir, NULL);
1557 if ( stat (home, &statbuf) )
1559 if (errno == ENOENT)
1561 if (
1562 #ifdef HAVE_W32_SYSTEM
1563 ( !compare_filenames (home, defhome) )
1564 #else
1565 (*defhome == '~'
1566 && (strlen (home) >= strlen (defhome+1)
1567 && !strcmp (home + strlen(home)
1568 - strlen (defhome+1), defhome+1)))
1569 || (*defhome != '~' && !strcmp (home, defhome) )
1570 #endif
1573 #ifdef HAVE_W32_SYSTEM
1574 if (!CreateDirectory (home, NULL))
1575 log_error (_("can't create directory `%s': %s\n"),
1576 home, w32_strerror (-1) );
1577 #else
1578 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1579 log_error (_("can't create directory `%s': %s\n"),
1580 home, strerror (errno) );
1581 #endif
1582 else
1584 if (!opt.quiet)
1585 log_info (_("directory `%s' created\n"), home);
1586 create_private_keys_directory (home);
1590 else
1591 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1593 else if ( !S_ISDIR(statbuf.st_mode))
1595 log_error (_("can't use `%s' as home directory\n"), home);
1597 else /* exists and is a directory. */
1599 create_private_keys_directory (home);
1601 xfree (home);
1606 /* This is the worker for the ticker. It is called every few seconds
1607 and may only do fast operations. */
1608 static void
1609 handle_tick (void)
1611 static time_t last_minute;
1613 if (!last_minute)
1614 last_minute = time (NULL);
1616 /* Check whether the scdaemon has died and cleanup in this case. */
1617 agent_scd_check_aliveness ();
1619 /* If we are running as a child of another process, check whether
1620 the parent is still alive and shutdown if not. */
1621 #ifndef HAVE_W32_SYSTEM
1622 if (parent_pid != (pid_t)(-1))
1624 if (kill (parent_pid, 0))
1626 shutdown_pending = 2;
1627 log_info ("parent process died - shutting down\n");
1628 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1629 cleanup ();
1630 agent_exit (0);
1633 #endif /*HAVE_W32_SYSTEM*/
1635 /* Code to be run every minute. */
1636 if (last_minute + 60 <= time (NULL))
1638 check_own_socket ();
1639 last_minute = time (NULL);
1645 /* A global function which allows us to call the reload stuff from
1646 other places too. This is only used when build for W32. */
1647 void
1648 agent_sighup_action (void)
1650 log_info ("SIGHUP received - "
1651 "re-reading configuration and flushing cache\n");
1652 agent_flush_cache ();
1653 reread_configuration ();
1654 agent_reload_trustlist ();
1658 static void
1659 agent_sigusr2_action (void)
1661 if (opt.verbose)
1662 log_info ("SIGUSR2 received - updating card event counter\n");
1663 /* Nothing to check right now. We only increment a counter. */
1664 bump_card_eventcounter ();
1668 static void
1669 handle_signal (int signo)
1671 switch (signo)
1673 #ifndef HAVE_W32_SYSTEM
1674 case SIGHUP:
1675 agent_sighup_action ();
1676 break;
1678 case SIGUSR1:
1679 log_info ("SIGUSR1 received - printing internal information:\n");
1680 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1681 agent_query_dump_state ();
1682 agent_scd_dump_state ();
1683 break;
1685 case SIGUSR2:
1686 agent_sigusr2_action ();
1687 break;
1689 case SIGTERM:
1690 if (!shutdown_pending)
1691 log_info ("SIGTERM received - shutting down ...\n");
1692 else
1693 log_info ("SIGTERM received - still %ld running threads\n",
1694 pth_ctrl( PTH_CTRL_GETTHREADS ));
1695 shutdown_pending++;
1696 if (shutdown_pending > 2)
1698 log_info ("shutdown forced\n");
1699 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1700 cleanup ();
1701 agent_exit (0);
1703 break;
1705 case SIGINT:
1706 log_info ("SIGINT received - immediate shutdown\n");
1707 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1708 cleanup ();
1709 agent_exit (0);
1710 break;
1711 #endif
1712 default:
1713 log_info ("signal %d received - no action defined\n", signo);
1718 /* Check the nonce on a new connection. This is a NOP unless we we
1719 are using our Unix domain socket emulation under Windows. */
1720 static int
1721 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1723 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1725 log_info (_("error reading nonce on fd %d: %s\n"),
1726 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1727 assuan_sock_close (ctrl->thread_startup.fd);
1728 xfree (ctrl);
1729 return -1;
1731 else
1732 return 0;
1736 /* This is the standard connection thread's main function. */
1737 static void *
1738 start_connection_thread (void *arg)
1740 ctrl_t ctrl = arg;
1742 if (check_nonce (ctrl, &socket_nonce))
1743 return NULL;
1745 agent_init_default_ctrl (ctrl);
1746 if (opt.verbose)
1747 log_info (_("handler 0x%lx for fd %d started\n"),
1748 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1750 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1751 if (opt.verbose)
1752 log_info (_("handler 0x%lx for fd %d terminated\n"),
1753 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1755 agent_deinit_default_ctrl (ctrl);
1756 xfree (ctrl);
1757 return NULL;
1761 /* This is the ssh connection thread's main function. */
1762 static void *
1763 start_connection_thread_ssh (void *arg)
1765 ctrl_t ctrl = arg;
1767 if (check_nonce (ctrl, &socket_nonce_ssh))
1768 return NULL;
1770 agent_init_default_ctrl (ctrl);
1771 if (opt.verbose)
1772 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1773 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1775 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1776 if (opt.verbose)
1777 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1778 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1780 agent_deinit_default_ctrl (ctrl);
1781 xfree (ctrl);
1782 return NULL;
1786 /* Connection handler loop. Wait for connection requests and spawn a
1787 thread after accepting a connection. */
1788 static void
1789 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1791 pth_attr_t tattr;
1792 pth_event_t ev, time_ev;
1793 sigset_t sigs;
1794 int signo;
1795 struct sockaddr_un paddr;
1796 socklen_t plen;
1797 fd_set fdset, read_fdset;
1798 int ret;
1799 gnupg_fd_t fd;
1800 int nfd;
1802 tattr = pth_attr_new();
1803 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1804 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1806 #ifndef HAVE_W32_SYSTEM /* fixme */
1807 /* Make sure that the signals we are going to handle are not blocked
1808 and create an event object for them. We also set the default
1809 action to ignore because we use an Pth event to get notified
1810 about signals. This avoids that the default action is taken in
1811 case soemthing goes wrong within Pth. The problem might also be
1812 a Pth bug. */
1813 sigemptyset (&sigs );
1815 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1816 struct sigaction sa;
1817 int i;
1819 for (i=0; i < DIM (mysigs); i++)
1821 sigemptyset (&sa.sa_mask);
1822 sa.sa_handler = SIG_IGN;
1823 sa.sa_flags = 0;
1824 sigaction (mysigs[i], &sa, NULL);
1826 sigaddset (&sigs, mysigs[i]);
1830 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1831 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1832 #else
1833 # ifdef PTH_EVENT_HANDLE
1834 sigs = 0;
1835 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1836 signo = 0;
1837 # else
1838 /* Use a dummy event. */
1839 sigs = 0;
1840 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1841 # endif
1842 #endif
1843 time_ev = NULL;
1845 FD_ZERO (&fdset);
1846 FD_SET (FD2INT (listen_fd), &fdset);
1847 nfd = FD2INT (listen_fd);
1848 if (listen_fd_ssh != GNUPG_INVALID_FD)
1850 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1851 if (FD2INT (listen_fd_ssh) > nfd)
1852 nfd = FD2INT (listen_fd_ssh);
1855 for (;;)
1857 /* Make sure that our signals are not blocked. */
1858 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1860 /* Shutdown test. */
1861 if (shutdown_pending)
1863 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1864 break; /* ready */
1866 /* Do not accept new connections but keep on running the
1867 loop to cope with the timer events. */
1868 FD_ZERO (&fdset);
1871 /* Create a timeout event if needed. To help with power saving
1872 we syncronize the ticks to the next full second. */
1873 if (!time_ev)
1875 pth_time_t nexttick;
1877 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1878 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
1880 nexttick.tv_sec++;
1881 nexttick.tv_usec = 0;
1883 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1886 /* POSIX says that fd_set should be implemented as a structure,
1887 thus a simple assignment is fine to copy the entire set. */
1888 read_fdset = fdset;
1890 if (time_ev)
1891 pth_event_concat (ev, time_ev, NULL);
1892 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1893 if (time_ev)
1894 pth_event_isolate (time_ev);
1896 if (ret == -1)
1898 if (pth_event_occurred (ev)
1899 || (time_ev && pth_event_occurred (time_ev)))
1901 if (pth_event_occurred (ev))
1903 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1904 agent_sigusr2_action ();
1905 #else
1906 handle_signal (signo);
1907 #endif
1909 if (time_ev && pth_event_occurred (time_ev))
1911 pth_event_free (time_ev, PTH_FREE_ALL);
1912 time_ev = NULL;
1913 handle_tick ();
1915 continue;
1917 log_error (_("pth_select failed: %s - waiting 1s\n"),
1918 strerror (errno));
1919 pth_sleep (1);
1920 continue;
1923 if (pth_event_occurred (ev))
1925 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1926 agent_sigusr2_action ();
1927 #else
1928 handle_signal (signo);
1929 #endif
1932 if (time_ev && pth_event_occurred (time_ev))
1934 pth_event_free (time_ev, PTH_FREE_ALL);
1935 time_ev = NULL;
1936 handle_tick ();
1940 /* We now might create new threads and because we don't want any
1941 signals (as we are handling them here) to be delivered to a
1942 new thread. Thus we need to block those signals. */
1943 pth_sigmask (SIG_BLOCK, &sigs, NULL);
1945 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
1947 ctrl_t ctrl;
1949 plen = sizeof paddr;
1950 fd = INT2FD (pth_accept (FD2INT(listen_fd),
1951 (struct sockaddr *)&paddr, &plen));
1952 if (fd == GNUPG_INVALID_FD)
1954 log_error ("accept failed: %s\n", strerror (errno));
1956 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1958 log_error ("error allocating connection control data: %s\n",
1959 strerror (errno) );
1960 assuan_sock_close (fd);
1962 else
1964 char threadname[50];
1966 snprintf (threadname, sizeof threadname-1,
1967 "conn fd=%d (gpg)", FD2INT(fd));
1968 threadname[sizeof threadname -1] = 0;
1969 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1970 ctrl->thread_startup.fd = fd;
1971 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1973 log_error ("error spawning connection handler: %s\n",
1974 strerror (errno) );
1975 assuan_sock_close (fd);
1976 xfree (ctrl);
1979 fd = GNUPG_INVALID_FD;
1982 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
1983 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
1985 ctrl_t ctrl;
1987 plen = sizeof paddr;
1988 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
1989 (struct sockaddr *)&paddr, &plen));
1990 if (fd == GNUPG_INVALID_FD)
1992 log_error ("accept failed for ssh: %s\n", strerror (errno));
1994 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1996 log_error ("error allocating connection control data: %s\n",
1997 strerror (errno) );
1998 assuan_sock_close (fd);
2000 else
2002 char threadname[50];
2004 agent_init_default_ctrl (ctrl);
2005 snprintf (threadname, sizeof threadname-1,
2006 "conn fd=%d (ssh)", FD2INT(fd));
2007 threadname[sizeof threadname -1] = 0;
2008 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2009 ctrl->thread_startup.fd = fd;
2010 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2012 log_error ("error spawning ssh connection handler: %s\n",
2013 strerror (errno) );
2014 assuan_sock_close (fd);
2015 xfree (ctrl);
2018 fd = GNUPG_INVALID_FD;
2022 pth_event_free (ev, PTH_FREE_ALL);
2023 if (time_ev)
2024 pth_event_free (time_ev, PTH_FREE_ALL);
2025 cleanup ();
2026 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2031 /* Helper for check_own_socket. */
2032 static int
2033 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2035 membuf_t *mb = opaque;
2036 put_membuf (mb, buffer, length);
2037 return 0;
2041 /* The thread running the actual check. We need to run this in a
2042 separate thread so that check_own_thread can be called from the
2043 timer tick. */
2044 static void *
2045 check_own_socket_thread (void *arg)
2047 int rc;
2048 char *sockname = arg;
2049 assuan_context_t ctx;
2050 membuf_t mb;
2051 char *buffer;
2053 check_own_socket_running++;
2055 rc = assuan_socket_connect (&ctx, sockname, (pid_t)(-1));
2056 xfree (sockname);
2057 if (rc)
2059 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2060 goto leave;
2063 init_membuf (&mb, 100);
2064 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2065 NULL, NULL, NULL, NULL);
2066 put_membuf (&mb, "", 1);
2067 buffer = get_membuf (&mb, NULL);
2068 if (rc || !buffer)
2070 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2071 "GETINFO pid", gpg_strerror (rc));
2072 rc = 1;
2074 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2076 log_error ("socket is now serviced by another server\n");
2077 rc = 1;
2079 else if (opt.verbose > 1)
2080 log_error ("socket is still served by this server\n");
2082 xfree (buffer);
2083 assuan_disconnect (ctx);
2085 leave:
2086 if (rc)
2088 /* We may not remove the socket as it is now in use by another
2089 server. Setting the name to empty does this. */
2090 if (socket_name)
2091 *socket_name = 0;
2092 if (socket_name_ssh)
2093 *socket_name_ssh = 0;
2094 shutdown_pending = 2;
2095 log_info ("this process is useless - shutting down\n");
2097 check_own_socket_running--;
2098 return NULL;
2102 /* Check whether we are still listening on our own socket. In case
2103 another gpg-agent process started after us has taken ownership of
2104 our socket, we woul linger around without any real taks. Thus we
2105 better check once in a while whether we are really needed. */
2106 static void
2107 check_own_socket (void)
2109 char *sockname;
2110 pth_attr_t tattr;
2112 if (!use_standard_socket)
2113 return; /* This check makes only sense in standard socket mode. */
2115 if (check_own_socket_running || shutdown_pending)
2116 return; /* Still running or already shutting down. */
2118 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2119 if (!sockname)
2120 return; /* Out of memory. */
2122 tattr = pth_attr_new();
2123 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2124 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2125 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2127 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2128 log_error ("error spawning check_own_socket_thread: %s\n",
2129 strerror (errno) );
2130 pth_attr_destroy (tattr);
2135 /* Figure out whether an agent is available and running. Prints an
2136 error if not. If SILENT is true, no messages are printed. Usually
2137 started with MODE 0. Returns 0 if the agent is running. */
2138 static int
2139 check_for_running_agent (int silent, int mode)
2141 int rc;
2142 char *infostr, *p;
2143 assuan_context_t ctx;
2144 int prot, pid;
2146 if (!mode)
2148 infostr = getenv ("GPG_AGENT_INFO");
2149 if (!infostr || !*infostr)
2151 if (!check_for_running_agent (silent, 1))
2152 return 0; /* Okay, its running on the standard socket. */
2153 if (!silent)
2154 log_error (_("no gpg-agent running in this session\n"));
2155 return -1;
2158 infostr = xstrdup (infostr);
2159 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2161 xfree (infostr);
2162 if (!check_for_running_agent (silent, 1))
2163 return 0; /* Okay, its running on the standard socket. */
2164 if (!silent)
2165 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2166 return -1;
2169 *p++ = 0;
2170 pid = atoi (p);
2171 while (*p && *p != PATHSEP_C)
2172 p++;
2173 prot = *p? atoi (p+1) : 0;
2174 if (prot != 1)
2176 xfree (infostr);
2177 if (!silent)
2178 log_error (_("gpg-agent protocol version %d is not supported\n"),
2179 prot);
2180 if (!check_for_running_agent (silent, 1))
2181 return 0; /* Okay, its running on the standard socket. */
2182 return -1;
2185 else /* MODE != 0 */
2187 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2188 pid = (pid_t)(-1);
2192 rc = assuan_socket_connect (&ctx, infostr, pid);
2193 xfree (infostr);
2194 if (rc)
2196 if (!mode && !check_for_running_agent (silent, 1))
2197 return 0; /* Okay, its running on the standard socket. */
2199 if (!mode && !silent)
2200 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2201 return -1;
2204 if (!opt.quiet && !silent)
2205 log_info ("gpg-agent running and available\n");
2207 assuan_disconnect (ctx);
2208 return 0;