Add comment about Cherry.
[gnupg.git] / agent / gpg-agent.c
blobeccf44539b077771783e66140e3f59f690a7d3db
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"
54 enum cmd_and_opt_values
55 { aNull = 0,
56 oCsh = 'c',
57 oQuiet = 'q',
58 oSh = 's',
59 oVerbose = 'v',
61 oNoVerbose = 500,
62 aGPGConfList,
63 aGPGConfTest,
64 oOptions,
65 oDebug,
66 oDebugAll,
67 oDebugLevel,
68 oDebugWait,
69 oNoGreeting,
70 oNoOptions,
71 oHomedir,
72 oNoDetach,
73 oNoGrab,
74 oLogFile,
75 oServer,
76 oDaemon,
77 oBatch,
79 oPinentryProgram,
80 oPinentryTouchFile,
81 oDisplay,
82 oTTYname,
83 oTTYtype,
84 oLCctype,
85 oLCmessages,
86 oXauthority,
87 oScdaemonProgram,
88 oDefCacheTTL,
89 oDefCacheTTLSSH,
90 oMaxCacheTTL,
91 oMaxCacheTTLSSH,
92 oEnforcePassphraseConstraints,
93 oMinPassphraseLen,
94 oMinPassphraseNonalpha,
95 oCheckPassphrasePattern,
96 oMaxPassphraseDays,
97 oEnablePassphraseHistory,
98 oUseStandardSocket,
99 oNoUseStandardSocket,
100 oFakedSystemTime,
102 oIgnoreCacheForSigning,
103 oAllowMarkTrusted,
104 oAllowPresetPassphrase,
105 oKeepTTY,
106 oKeepDISPLAY,
107 oSSHSupport,
108 oDisableScdaemon,
109 oWriteEnvFile
114 static ARGPARSE_OPTS opts[] = {
116 { aGPGConfList, "gpgconf-list", 256, "@" },
117 { aGPGConfTest, "gpgconf-test", 256, "@" },
119 { 301, NULL, 0, N_("@Options:\n ") },
121 { oServer, "server", 0, N_("run in server mode (foreground)") },
122 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
123 { oVerbose, "verbose", 0, N_("verbose") },
124 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
125 { oSh, "sh", 0, N_("sh-style command output") },
126 { oCsh, "csh", 0, N_("csh-style command output") },
127 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
128 { oDebug, "debug" ,4|16, "@"},
129 { oDebugAll, "debug-all" ,0, "@"},
130 { oDebugLevel, "debug-level" ,2, "@"},
131 { oDebugWait,"debug-wait",1, "@"},
132 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
133 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
134 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
135 { oUseStandardSocket, "use-standard-socket", 0,
136 N_("use a standard location for the socket")},
137 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
138 { oPinentryProgram, "pinentry-program", 2 ,
139 N_("|PGM|use PGM as the PIN-Entry program") },
140 { oPinentryTouchFile, "pinentry-touch-file", 2 , "@" },
141 { oScdaemonProgram, "scdaemon-program", 2 ,
142 N_("|PGM|use PGM as the SCdaemon program") },
143 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
144 { oFakedSystemTime, "faked-system-time", 2, "@" }, /* (epoch time) */
146 { oBatch, "batch", 0, "@" },
147 { oHomedir, "homedir", 2, "@"},
149 { oDisplay, "display", 2, "@" },
150 { oTTYname, "ttyname", 2, "@" },
151 { oTTYtype, "ttytype", 2, "@" },
152 { oLCctype, "lc-ctype", 2, "@" },
153 { oLCmessages, "lc-messages", 2, "@" },
154 { oXauthority, "xauthority", 2, "@" },
155 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
156 { oKeepDISPLAY, "keep-display",
157 0, N_("ignore requests to change the X display")},
159 { oDefCacheTTL, "default-cache-ttl", 4,
160 N_("|N|expire cached PINs after N seconds")},
161 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
162 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
163 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
165 { oEnforcePassphraseConstraints, "enforce-passphrase-constraints", 0, "@"},
166 { oMinPassphraseLen, "min-passphrase-len", 4, "@" },
167 { oMinPassphraseNonalpha, "min-passphrase-nonalpha", 4, "@" },
168 { oCheckPassphrasePattern, "check-passphrase-pattern", 2, "@" },
169 { oMaxPassphraseDays, "max-passphrase-days", 4, "@" },
170 { oEnablePassphraseHistory, "enable-passphrase-history", 0, "@" },
172 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
173 N_("do not use the PIN cache when signing")},
174 { oAllowMarkTrusted, "allow-mark-trusted", 0,
175 N_("allow clients to mark keys as \"trusted\"")},
176 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
177 N_("allow presetting passphrase")},
178 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
179 { oWriteEnvFile, "write-env-file", 2|8,
180 N_("|FILE|write environment settings also to FILE")},
185 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
186 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
187 #define MAX_CACHE_TTL (120*60) /* 2 hours */
188 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
189 #define MIN_PASSPHRASE_LEN (8)
190 #define MIN_PASSPHRASE_NONALPHA (1)
191 #define MAX_PASSPHRASE_DAYS (0)
193 /* The timer tick used for housekeeping stuff. For Windows we use a
194 longer period as the SetWaitableTimer seems to signal earlier than
195 the 2 seconds. */
196 #ifdef HAVE_W32_SYSTEM
197 #define TIMERTICK_INTERVAL (4)
198 #else
199 #define TIMERTICK_INTERVAL (2) /* Seconds. */
200 #endif
203 /* The list of open file descriptors at startup. Note that this list
204 has been allocated using the standard malloc. */
205 static int *startup_fd_list;
207 /* The signal mask at startup and a flag telling whether it is valid. */
208 #ifdef HAVE_SIGPROCMASK
209 static sigset_t startup_signal_mask;
210 static int startup_signal_mask_valid;
211 #endif
213 /* Flag to indicate that a shutdown was requested. */
214 static int shutdown_pending;
216 /* Counter for the currently running own socket checks. */
217 static int check_own_socket_running;
219 /* True if we are listening on the standard socket. */
220 static int use_standard_socket;
222 /* It is possible that we are currently running under setuid permissions */
223 static int maybe_setuid = 1;
225 /* Name of the communication socket used for native gpg-agent requests. */
226 static char *socket_name;
228 /* Name of the communication socket used for ssh-agent-emulation. */
229 static char *socket_name_ssh;
231 /* We need to keep track of the server's nonces (these are dummies for
232 POSIX systems). */
233 static assuan_sock_nonce_t socket_nonce;
234 static assuan_sock_nonce_t socket_nonce_ssh;
237 /* Default values for options passed to the pinentry. */
238 static char *default_display;
239 static char *default_ttyname;
240 static char *default_ttytype;
241 static char *default_lc_ctype;
242 static char *default_lc_messages;
243 static char *default_xauthority;
245 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
246 static char *config_filename;
248 /* Helper to implement --debug-level */
249 static const char *debug_level;
251 /* Keep track of the current log file so that we can avoid updating
252 the log file after a SIGHUP if it didn't changed. Malloced. */
253 static char *current_logfile;
255 /* The handle_tick() function may test whether a parent is still
256 running. We record the PID of the parent here or -1 if it should be
257 watched. */
258 static pid_t parent_pid = (pid_t)(-1);
262 Local prototypes.
265 static char *create_socket_name (char *standard_name, char *template);
266 static gnupg_fd_t create_server_socket (char *name, int is_ssh,
267 assuan_sock_nonce_t *nonce);
268 static void create_directories (void);
270 static void agent_init_default_ctrl (ctrl_t ctrl);
271 static void agent_deinit_default_ctrl (ctrl_t ctrl);
273 static void handle_connections (gnupg_fd_t listen_fd,
274 gnupg_fd_t listen_fd_ssh);
275 static void check_own_socket (void);
276 static int check_for_running_agent (int silent, int mode);
278 /* Pth wrapper function definitions. */
279 GCRY_THREAD_OPTION_PTH_IMPL;
280 static int fixed_gcry_pth_init (void)
282 return pth_self ()? 0 : (pth_init () == FALSE) ? errno : 0;
286 #ifndef PTH_HAVE_PTH_THREAD_ID
287 static unsigned long pth_thread_id (void)
289 return (unsigned long)pth_self ();
291 #endif
296 Functions.
299 static char *
300 make_libversion (const char *libname, const char *(*getfnc)(const char*))
302 const char *s;
303 char *result;
305 if (maybe_setuid)
307 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
308 maybe_setuid = 0;
310 s = getfnc (NULL);
311 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
312 strcpy (stpcpy (stpcpy (result, libname), " "), s);
313 return result;
317 static const char *
318 my_strusage (int level)
320 static char *ver_gcry;
321 const char *p;
323 switch (level)
325 case 11: p = "gpg-agent (GnuPG)";
326 break;
327 case 13: p = VERSION; break;
328 case 17: p = PRINTABLE_OS_NAME; break;
329 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
330 break;
331 case 20:
332 if (!ver_gcry)
333 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
334 p = ver_gcry;
335 break;
337 case 1:
338 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
339 break;
340 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
341 "Secret key management for GnuPG\n");
342 break;
344 default: p = NULL;
346 return p;
351 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
352 only the active debug flags are propagated to the subsystems. With
353 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
354 all flags already set. Note that we don't fail here, because it is
355 important to keep gpg-agent running even after re-reading the
356 options due to a SIGHUP. */
357 static void
358 set_debug (void)
360 if (!debug_level)
362 else if (!strcmp (debug_level, "none"))
363 opt.debug = 0;
364 else if (!strcmp (debug_level, "basic"))
365 opt.debug = DBG_ASSUAN_VALUE;
366 else if (!strcmp (debug_level, "advanced"))
367 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
368 else if (!strcmp (debug_level, "expert"))
369 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
370 |DBG_CACHE_VALUE);
371 else if (!strcmp (debug_level, "guru"))
372 opt.debug = ~0;
373 else
375 log_error (_("invalid debug-level `%s' given\n"), debug_level);
376 opt.debug = 0; /* Reset debugging, so that prior debug
377 statements won't have an undesired effect. */
380 if (opt.debug && !opt.verbose)
381 opt.verbose = 1;
382 if (opt.debug && opt.quiet)
383 opt.quiet = 0;
385 if (opt.debug & DBG_MPI_VALUE)
386 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
387 if (opt.debug & DBG_CRYPTO_VALUE )
388 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
389 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
393 /* Helper for cleanup to remove one socket with NAME. */
394 static void
395 remove_socket (char *name)
397 if (name && *name)
399 char *p;
401 remove (name);
402 p = strrchr (name, '/');
403 if (p)
405 *p = 0;
406 rmdir (name);
407 *p = '/';
409 *name = 0;
413 static void
414 cleanup (void)
416 remove_socket (socket_name);
417 remove_socket (socket_name_ssh);
422 /* Handle options which are allowed to be reset after program start.
423 Return true when the current option in PARGS could be handled and
424 false if not. As a special feature, passing a value of NULL for
425 PARGS, resets the options to the default. REREAD should be set
426 true if it is not the initial option parsing. */
427 static int
428 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
430 if (!pargs)
431 { /* reset mode */
432 opt.quiet = 0;
433 opt.verbose = 0;
434 opt.debug = 0;
435 opt.no_grab = 0;
436 opt.pinentry_program = NULL;
437 opt.pinentry_touch_file = NULL;
438 opt.scdaemon_program = NULL;
439 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
440 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
441 opt.max_cache_ttl = MAX_CACHE_TTL;
442 opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
443 opt.enforce_passphrase_constraints = 0;
444 opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
445 opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
446 opt.check_passphrase_pattern = NULL;
447 opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
448 opt.enable_passhrase_history = 0;
449 opt.ignore_cache_for_signing = 0;
450 opt.allow_mark_trusted = 0;
451 opt.disable_scdaemon = 0;
452 return 1;
455 switch (pargs->r_opt)
457 case oQuiet: opt.quiet = 1; break;
458 case oVerbose: opt.verbose++; break;
460 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
461 case oDebugAll: opt.debug = ~0; break;
462 case oDebugLevel: debug_level = pargs->r.ret_str; break;
464 case oLogFile:
465 if (!reread)
466 return 0; /* not handeld */
467 if (!current_logfile || !pargs->r.ret_str
468 || strcmp (current_logfile, pargs->r.ret_str))
470 log_set_file (pargs->r.ret_str);
471 assuan_set_assuan_log_stream (log_get_stream ());
472 xfree (current_logfile);
473 current_logfile = xtrystrdup (pargs->r.ret_str);
475 break;
477 case oNoGrab: opt.no_grab = 1; break;
479 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
480 case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
481 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
482 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
484 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
485 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
486 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
487 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
489 case oEnforcePassphraseConstraints:
490 opt.enforce_passphrase_constraints=1;
491 break;
492 case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
493 case oMinPassphraseNonalpha:
494 opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
495 break;
496 case oCheckPassphrasePattern:
497 opt.check_passphrase_pattern = pargs->r.ret_str;
498 break;
499 case oMaxPassphraseDays:
500 opt.max_passphrase_days = pargs->r.ret_ulong;
501 break;
502 case oEnablePassphraseHistory:
503 opt.enable_passhrase_history = 1;
504 break;
506 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
508 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
510 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
512 default:
513 return 0; /* not handled */
516 return 1; /* handled */
520 /* The main entry point. */
522 main (int argc, char **argv )
524 ARGPARSE_ARGS pargs;
525 int orig_argc;
526 int may_coredump;
527 char **orig_argv;
528 FILE *configfp = NULL;
529 char *configname = NULL;
530 const char *shell;
531 unsigned configlineno;
532 int parse_debug = 0;
533 int default_config =1;
534 int greeting = 0;
535 int nogreeting = 0;
536 int pipe_server = 0;
537 int is_daemon = 0;
538 int nodetach = 0;
539 int csh_style = 0;
540 char *logfile = NULL;
541 int debug_wait = 0;
542 int gpgconf_list = 0;
543 gpg_error_t err;
544 const char *env_file_name = NULL;
547 /* Before we do anything else we save the list of currently open
548 file descriptors and the signal mask. This info is required to
549 do the exec call properly. */
550 startup_fd_list = get_all_open_fds ();
551 #ifdef HAVE_SIGPROCMASK
552 if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
553 startup_signal_mask_valid = 1;
554 #endif /*HAVE_SIGPROCMASK*/
556 /* Set program name etc. */
557 set_strusage (my_strusage);
558 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
559 /* Please note that we may running SUID(ROOT), so be very CAREFUL
560 when adding any stuff between here and the call to INIT_SECMEM()
561 somewhere after the option parsing */
562 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
564 /* Make sure that our subsystems are ready. */
565 i18n_init ();
566 init_common_subsystems ();
569 /* Libgcrypt requires us to register the threading model first.
570 Note that this will also do the pth_init. */
571 gcry_threads_pth.init = fixed_gcry_pth_init;
572 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
573 if (err)
575 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
576 gpg_strerror (err));
580 /* Check that the libraries are suitable. Do it here because
581 the option parsing may need services of the library. */
582 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
584 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
585 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
588 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
589 assuan_set_assuan_log_stream (log_get_stream ());
590 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
591 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
593 setup_libgcrypt_logging ();
594 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
596 may_coredump = disable_core_dumps ();
598 /* Set default options. */
599 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
600 #ifdef HAVE_W32_SYSTEM
601 use_standard_socket = 1; /* Under Windows we always use a standard
602 socket. */
603 #endif
605 shell = getenv ("SHELL");
606 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
607 csh_style = 1;
609 opt.homedir = default_homedir ();
611 /* Record some of the original environment strings. */
612 opt.startup_display = getenv ("DISPLAY");
613 if (opt.startup_display)
614 opt.startup_display = xstrdup (opt.startup_display);
615 opt.startup_ttyname = ttyname (0);
616 if (opt.startup_ttyname)
617 opt.startup_ttyname = xstrdup (opt.startup_ttyname);
618 opt.startup_ttytype = getenv ("TERM");
619 if (opt.startup_ttytype)
620 opt.startup_ttytype = xstrdup (opt.startup_ttytype);
621 /* Fixme: Better use the locale function here. */
622 opt.startup_lc_ctype = getenv ("LC_CTYPE");
623 if (opt.startup_lc_ctype)
624 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
625 opt.startup_lc_messages = getenv ("LC_MESSAGES");
626 if (opt.startup_lc_messages)
627 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
628 opt.startup_xauthority = getenv ("XAUTHORITY");
629 if (opt.startup_xauthority)
630 opt.startup_xauthority = xstrdup (opt.startup_xauthority);
631 opt.startup_pinentry_user_data = getenv ("PINENTRY_USER_DATA");
632 if (opt.startup_pinentry_user_data)
633 opt.startup_pinentry_user_data = xstrdup (opt.startup_pinentry_user_data);
635 /* Check whether we have a config file on the commandline */
636 orig_argc = argc;
637 orig_argv = argv;
638 pargs.argc = &argc;
639 pargs.argv = &argv;
640 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
641 while (arg_parse( &pargs, opts))
643 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
644 parse_debug++;
645 else if (pargs.r_opt == oOptions)
646 { /* yes there is one, so we do not try the default one, but
647 read the option file when it is encountered at the
648 commandline */
649 default_config = 0;
651 else if (pargs.r_opt == oNoOptions)
652 default_config = 0; /* --no-options */
653 else if (pargs.r_opt == oHomedir)
654 opt.homedir = pargs.r.ret_str;
657 /* Initialize the secure memory. */
658 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
659 maybe_setuid = 0;
662 Now we are now working under our real uid
665 if (default_config)
666 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
668 argc = orig_argc;
669 argv = orig_argv;
670 pargs.argc = &argc;
671 pargs.argv = &argv;
672 pargs.flags= 1; /* do not remove the args */
673 next_pass:
674 if (configname)
676 configlineno = 0;
677 configfp = fopen (configname, "r");
678 if (!configfp)
680 if (default_config)
682 if( parse_debug )
683 log_info (_("NOTE: no default option file `%s'\n"),
684 configname );
686 else
688 log_error (_("option file `%s': %s\n"),
689 configname, strerror(errno) );
690 exit(2);
692 xfree (configname);
693 configname = NULL;
695 if (parse_debug && configname )
696 log_info (_("reading options from `%s'\n"), configname );
697 default_config = 0;
700 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
702 if (parse_rereadable_options (&pargs, 0))
703 continue; /* Already handled */
704 switch (pargs.r_opt)
706 case aGPGConfList: gpgconf_list = 1; break;
707 case aGPGConfTest: gpgconf_list = 2; break;
708 case oBatch: opt.batch=1; break;
710 case oDebugWait: debug_wait = pargs.r.ret_int; break;
712 case oOptions:
713 /* config files may not be nested (silently ignore them) */
714 if (!configfp)
716 xfree(configname);
717 configname = xstrdup(pargs.r.ret_str);
718 goto next_pass;
720 break;
721 case oNoGreeting: nogreeting = 1; break;
722 case oNoVerbose: opt.verbose = 0; break;
723 case oNoOptions: break; /* no-options */
724 case oHomedir: opt.homedir = pargs.r.ret_str; break;
725 case oNoDetach: nodetach = 1; break;
726 case oLogFile: logfile = pargs.r.ret_str; break;
727 case oCsh: csh_style = 1; break;
728 case oSh: csh_style = 0; break;
729 case oServer: pipe_server = 1; break;
730 case oDaemon: is_daemon = 1; break;
732 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
733 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
734 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
735 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
736 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
737 case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
738 break;
740 case oUseStandardSocket: use_standard_socket = 1; break;
741 case oNoUseStandardSocket: use_standard_socket = 0; break;
743 case oFakedSystemTime:
745 time_t faked_time = isotime2epoch (pargs.r.ret_str);
746 if (faked_time == (time_t)(-1))
747 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
748 gnupg_set_time (faked_time, 0);
750 break;
752 case oKeepTTY: opt.keep_tty = 1; break;
753 case oKeepDISPLAY: opt.keep_display = 1; break;
755 case oSSHSupport: opt.ssh_support = 1; break;
756 case oWriteEnvFile:
757 if (pargs.r_type)
758 env_file_name = pargs.r.ret_str;
759 else
760 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
761 break;
763 default : pargs.err = configfp? 1:2; break;
766 if (configfp)
768 fclose( configfp );
769 configfp = NULL;
770 /* Keep a copy of the name so that it can be read on SIGHUP. */
771 config_filename = configname;
772 configname = NULL;
773 goto next_pass;
775 xfree (configname);
776 configname = NULL;
777 if (log_get_errorcount(0))
778 exit(2);
779 if (nogreeting )
780 greeting = 0;
782 if (greeting)
784 fprintf (stderr, "%s %s; %s\n",
785 strusage(11), strusage(13), strusage(14) );
786 fprintf (stderr, "%s\n", strusage(15) );
788 #ifdef IS_DEVELOPMENT_VERSION
789 /* We don't want to print it here because gpg-agent is useful of its
790 own and quite matured. */
791 /*log_info ("NOTE: this is a development version!\n");*/
792 #endif
794 set_debug ();
796 if (atexit (cleanup))
798 log_error ("atexit failed\n");
799 cleanup ();
800 exit (1);
803 initialize_module_call_pinentry ();
804 initialize_module_call_scd ();
805 initialize_module_trustlist ();
807 /* Try to create missing directories. */
808 create_directories ();
810 if (debug_wait && pipe_server)
812 log_debug ("waiting for debugger - my pid is %u .....\n",
813 (unsigned int)getpid());
814 gnupg_sleep (debug_wait);
815 log_debug ("... okay\n");
818 if (gpgconf_list == 2)
819 agent_exit (0);
820 if (gpgconf_list)
822 char *filename;
823 char *filename_esc;
825 /* List options and default values in the GPG Conf format. */
826 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
827 filename_esc = percent_escape (filename, NULL);
829 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
830 GC_OPT_FLAG_DEFAULT, filename_esc);
831 xfree (filename);
832 xfree (filename_esc);
834 printf ("verbose:%lu:\n"
835 "quiet:%lu:\n"
836 "debug-level:%lu:\"none:\n"
837 "log-file:%lu:\n",
838 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
839 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
840 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
841 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
842 printf ("default-cache-ttl:%lu:%d:\n",
843 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
844 printf ("default-cache-ttl-ssh:%lu:%d:\n",
845 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
846 printf ("max-cache-ttl:%lu:%d:\n",
847 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
848 printf ("max-cache-ttl-ssh:%lu:%d:\n",
849 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
850 printf ("enforce-passphrase-constraints:%lu:\n",
851 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
852 printf ("min-passphrase-len:%lu:%d:\n",
853 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
854 printf ("min-passphrase-nonalpha:%lu:%d:\n",
855 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
856 MIN_PASSPHRASE_NONALPHA);
857 printf ("check-passphrase-pattern:%lu:\n",
858 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
859 printf ("max-passphrase-days:%lu:%d:\n",
860 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
861 MAX_PASSPHRASE_DAYS);
862 printf ("enable-passphrase-history:%lu:\n",
863 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
864 printf ("no-grab:%lu:\n",
865 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
866 printf ("ignore-cache-for-signing:%lu:\n",
867 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
868 printf ("allow-mark-trusted:%lu:\n",
869 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
870 printf ("disable-scdaemon:%lu:\n",
871 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
873 agent_exit (0);
876 /* If this has been called without any options, we merely check
877 whether an agent is already running. We do this here so that we
878 don't clobber a logfile but print it directly to stderr. */
879 if (!pipe_server && !is_daemon)
881 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
882 check_for_running_agent (0, 0);
883 agent_exit (0);
886 #ifdef ENABLE_NLS
887 /* gpg-agent usually does not output any messages because it runs in
888 the background. For log files it is acceptable to have messages
889 always encoded in utf-8. We switch here to utf-8, so that
890 commands like --help still give native messages. It is far
891 easier to switch only once instead of for every message and it
892 actually helps when more then one thread is active (avoids an
893 extra copy step). */
894 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
895 #endif
897 /* Now start with logging to a file if this is desired. */
898 if (logfile)
900 log_set_file (logfile);
901 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
902 |JNLIB_LOG_WITH_TIME
903 |JNLIB_LOG_WITH_PID));
904 current_logfile = xstrdup (logfile);
905 assuan_set_assuan_log_stream (log_get_stream ());
908 /* Make sure that we have a default ttyname. */
909 if (!default_ttyname && ttyname (1))
910 default_ttyname = xstrdup (ttyname (1));
911 if (!default_ttytype && getenv ("TERM"))
912 default_ttytype = xstrdup (getenv ("TERM"));
915 if (pipe_server)
917 /* This is the simple pipe based server */
918 ctrl_t ctrl;
920 ctrl = xtrycalloc (1, sizeof *ctrl);
921 if (!ctrl)
923 log_error ("error allocating connection control data: %s\n",
924 strerror (errno) );
925 agent_exit (1);
927 agent_init_default_ctrl (ctrl);
928 start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
929 agent_deinit_default_ctrl (ctrl);
930 xfree (ctrl);
932 else if (!is_daemon)
933 ; /* NOTREACHED */
934 else
935 { /* Regular server mode */
936 gnupg_fd_t fd;
937 gnupg_fd_t fd_ssh;
938 pid_t pid;
940 /* Remove the DISPLAY variable so that a pinentry does not
941 default to a specific display. There is still a default
942 display when gpg-agent was started using --display or a
943 client requested this using an OPTION command. Note, that we
944 don't do this when running in reverse daemon mode (i.e. when
945 exec the program given as arguments). */
946 #ifndef HAVE_W32_SYSTEM
947 if (!opt.keep_display && !argc)
948 unsetenv ("DISPLAY");
949 #endif
952 /* Create the sockets. */
953 socket_name = create_socket_name
954 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
955 if (opt.ssh_support)
956 socket_name_ssh = create_socket_name
957 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
959 fd = create_server_socket (socket_name, 0, &socket_nonce);
960 if (opt.ssh_support)
961 fd_ssh = create_server_socket (socket_name_ssh, 1, &socket_nonce_ssh);
962 else
963 fd_ssh = GNUPG_INVALID_FD;
965 /* If we are going to exec a program in the parent, we record
966 the PID, so that the child may check whether the program is
967 still alive. */
968 if (argc)
969 parent_pid = getpid ();
971 fflush (NULL);
972 #ifdef HAVE_W32_SYSTEM
973 pid = getpid ();
974 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
975 #else /*!HAVE_W32_SYSTEM*/
976 pid = fork ();
977 if (pid == (pid_t)-1)
979 log_fatal ("fork failed: %s\n", strerror (errno) );
980 exit (1);
982 else if (pid)
983 { /* We are the parent */
984 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
986 /* Close the socket FD. */
987 close (fd);
989 /* Note that we used a standard fork so that Pth runs in
990 both the parent and the child. The pth_fork would
991 terminate Pth in the child but that is not the way we
992 want it. Thus we use a plain fork and terminate Pth here
993 in the parent. The pth_kill may or may not work reliable
994 but it should not harm to call it. Because Pth fiddles
995 with the signal mask the signal mask might not be correct
996 right now and thus we restore it. That is not strictly
997 necessary but some programs falsely assume a cleared
998 signal mask. */
999 if ( !pth_kill () )
1000 log_error ("pth_kill failed in forked process\n");
1002 #ifdef HAVE_SIGPROCMASK
1003 if (startup_signal_mask_valid)
1005 if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1006 log_error ("error restoring signal mask: %s\n",
1007 strerror (errno));
1009 else
1010 log_info ("no saved signal mask\n");
1011 #endif /*HAVE_SIGPROCMASK*/
1013 /* Create the info string: <name>:<pid>:<protocol_version> */
1014 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
1015 socket_name, (ulong)pid ) < 0)
1017 log_error ("out of core\n");
1018 kill (pid, SIGTERM);
1019 exit (1);
1021 if (opt.ssh_support)
1023 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1024 socket_name_ssh) < 0)
1026 log_error ("out of core\n");
1027 kill (pid, SIGTERM);
1028 exit (1);
1030 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
1031 pid) < 0)
1033 log_error ("out of core\n");
1034 kill (pid, SIGTERM);
1035 exit (1);
1039 *socket_name = 0; /* Don't let cleanup() remove the socket -
1040 the child should do this from now on */
1041 if (opt.ssh_support)
1042 *socket_name_ssh = 0;
1044 if (env_file_name)
1046 FILE *fp;
1048 fp = fopen (env_file_name, "w");
1049 if (!fp)
1050 log_error (_("error creating `%s': %s\n"),
1051 env_file_name, strerror (errno));
1052 else
1054 fputs (infostr, fp);
1055 putc ('\n', fp);
1056 if (opt.ssh_support)
1058 fputs (infostr_ssh_sock, fp);
1059 putc ('\n', fp);
1060 fputs (infostr_ssh_pid, fp);
1061 putc ('\n', fp);
1063 fclose (fp);
1068 if (argc)
1069 { /* Run the program given on the commandline. */
1070 if (putenv (infostr))
1072 log_error ("failed to set environment: %s\n",
1073 strerror (errno) );
1074 kill (pid, SIGTERM );
1075 exit (1);
1077 if (opt.ssh_support && putenv (infostr_ssh_sock))
1079 log_error ("failed to set environment: %s\n",
1080 strerror (errno) );
1081 kill (pid, SIGTERM );
1082 exit (1);
1084 if (opt.ssh_support && putenv (infostr_ssh_pid))
1086 log_error ("failed to set environment: %s\n",
1087 strerror (errno) );
1088 kill (pid, SIGTERM );
1089 exit (1);
1092 /* Close all the file descriptors except the standard
1093 ones and those open at startup. We explicitly don't
1094 close 0,1,2 in case something went wrong collecting
1095 them at startup. */
1096 close_all_fds (3, startup_fd_list);
1098 /* Run the command. */
1099 execvp (argv[0], argv);
1100 log_error ("failed to run the command: %s\n", strerror (errno));
1101 kill (pid, SIGTERM);
1102 exit (1);
1104 else
1106 /* Print the environment string, so that the caller can use
1107 shell's eval to set it */
1108 if (csh_style)
1110 *strchr (infostr, '=') = ' ';
1111 printf ("setenv %s\n", infostr);
1112 if (opt.ssh_support)
1114 *strchr (infostr_ssh_sock, '=') = ' ';
1115 printf ("setenv %s\n", infostr_ssh_sock);
1116 *strchr (infostr_ssh_pid, '=') = ' ';
1117 printf ("setenv %s\n", infostr_ssh_pid);
1120 else
1122 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
1123 if (opt.ssh_support)
1125 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
1126 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1129 xfree (infostr);
1130 if (opt.ssh_support)
1132 xfree (infostr_ssh_sock);
1133 xfree (infostr_ssh_pid);
1135 exit (0);
1137 /*NOTREACHED*/
1138 } /* End parent */
1141 This is the child
1144 /* Detach from tty and put process into a new session */
1145 if (!nodetach )
1147 int i;
1148 unsigned int oldflags;
1150 /* Close stdin, stdout and stderr unless it is the log stream */
1151 for (i=0; i <= 2; i++)
1153 if (!log_test_fd (i) && i != fd )
1155 if ( ! close (i)
1156 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1158 log_error ("failed to open `%s': %s\n",
1159 "/dev/null", strerror (errno));
1160 cleanup ();
1161 exit (1);
1165 if (setsid() == -1)
1167 log_error ("setsid() failed: %s\n", strerror(errno) );
1168 cleanup ();
1169 exit (1);
1172 log_get_prefix (&oldflags);
1173 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1174 opt.running_detached = 1;
1177 if (chdir("/"))
1179 log_error ("chdir to / failed: %s\n", strerror (errno));
1180 exit (1);
1184 struct sigaction sa;
1186 sa.sa_handler = SIG_IGN;
1187 sigemptyset (&sa.sa_mask);
1188 sa.sa_flags = 0;
1189 sigaction (SIGPIPE, &sa, NULL);
1191 #endif /*!HAVE_W32_SYSTEM*/
1193 log_info ("%s %s started\n", strusage(11), strusage(13) );
1194 handle_connections (fd, opt.ssh_support ? fd_ssh : GNUPG_INVALID_FD);
1195 assuan_sock_close (fd);
1198 return 0;
1202 void
1203 agent_exit (int rc)
1205 /*FIXME: update_random_seed_file();*/
1206 #if 1
1207 /* at this time a bit annoying */
1208 if (opt.debug & DBG_MEMSTAT_VALUE)
1210 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1211 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1213 if (opt.debug)
1214 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1215 #endif
1216 gcry_control (GCRYCTL_TERM_SECMEM );
1217 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1218 exit (rc);
1221 static void
1222 agent_init_default_ctrl (ctrl_t ctrl)
1224 /* Note we ignore malloc errors because we can't do much about it
1225 and the request will fail anyway shortly after this
1226 initialization. */
1227 if (ctrl->display)
1228 xfree (ctrl->display);
1229 ctrl->display = default_display? xtrystrdup (default_display) : NULL;
1231 if (ctrl->ttyname)
1232 xfree (ctrl->ttyname);
1233 ctrl->ttyname = default_ttyname? xtrystrdup (default_ttyname) : NULL;
1235 if (ctrl->ttytype)
1236 xfree (ctrl->ttytype);
1237 ctrl->ttytype = default_ttytype? xtrystrdup (default_ttytype) : NULL;
1239 if (ctrl->lc_ctype)
1240 xfree (ctrl->lc_ctype);
1241 ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1243 if (ctrl->lc_messages)
1244 xfree (ctrl->lc_messages);
1245 ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1246 /**/ : NULL;
1248 if (ctrl->xauthority)
1249 xfree (ctrl->xauthority);
1250 ctrl->xauthority = default_xauthority? xtrystrdup (default_xauthority)
1251 /**/: NULL;
1253 if (ctrl->pinentry_user_data)
1254 xfree (ctrl->pinentry_user_data);
1255 ctrl->pinentry_user_data = NULL;
1259 static void
1260 agent_deinit_default_ctrl (ctrl_t ctrl)
1262 if (ctrl->display)
1263 xfree (ctrl->display);
1264 if (ctrl->ttyname)
1265 xfree (ctrl->ttyname);
1266 if (ctrl->ttytype)
1267 xfree (ctrl->ttytype);
1268 if (ctrl->lc_ctype)
1269 xfree (ctrl->lc_ctype);
1270 if (ctrl->lc_messages)
1271 xfree (ctrl->lc_messages);
1272 if (ctrl->xauthority)
1273 xfree (ctrl->xauthority);
1274 if (ctrl->pinentry_user_data)
1275 xfree (ctrl->pinentry_user_data);
1278 /* Reread parts of the configuration. Note, that this function is
1279 obviously not thread-safe and should only be called from the PTH
1280 signal handler.
1282 Fixme: Due to the way the argument parsing works, we create a
1283 memory leak here for all string type arguments. There is currently
1284 no clean way to tell whether the memory for the argument has been
1285 allocated or points into the process' original arguments. Unless
1286 we have a mechanism to tell this, we need to live on with this. */
1287 static void
1288 reread_configuration (void)
1290 ARGPARSE_ARGS pargs;
1291 FILE *fp;
1292 unsigned int configlineno = 0;
1293 int dummy;
1295 if (!config_filename)
1296 return; /* No config file. */
1298 fp = fopen (config_filename, "r");
1299 if (!fp)
1301 log_error (_("option file `%s': %s\n"),
1302 config_filename, strerror(errno) );
1303 return;
1306 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1308 memset (&pargs, 0, sizeof pargs);
1309 dummy = 0;
1310 pargs.argc = &dummy;
1311 pargs.flags = 1; /* do not remove the args */
1312 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1314 if (pargs.r_opt < -1)
1315 pargs.err = 1; /* Print a warning. */
1316 else /* Try to parse this option - ignore unchangeable ones. */
1317 parse_rereadable_options (&pargs, 1);
1319 fclose (fp);
1320 set_debug ();
1324 /* Return the file name of the socket we are using for native
1325 requests. */
1326 const char *
1327 get_agent_socket_name (void)
1329 const char *s = socket_name;
1331 return (s && *s)? s : NULL;
1334 /* Return the file name of the socket we are using for SSH
1335 requests. */
1336 const char *
1337 get_agent_ssh_socket_name (void)
1339 const char *s = socket_name_ssh;
1341 return (s && *s)? s : NULL;
1345 /* Under W32, this function returns the handle of the scdaemon
1346 notification event. Calling it the first time creates that
1347 event. */
1348 #ifdef HAVE_W32_SYSTEM
1349 void *
1350 get_agent_scd_notify_event (void)
1352 static HANDLE the_event;
1354 if (!the_event)
1356 HANDLE h, h2;
1357 SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1359 /* We need to use manual reset evet object due to the way our
1360 w32-pth wait function works: If we would use an automatic
1361 reset event we are not able to figure out which handle has
1362 been signaled because at the time we single out the signaled
1363 handles using WFSO the event has already been reset due to
1364 the WFMO. */
1365 h = CreateEvent (&sa, TRUE, FALSE, NULL);
1366 if (!h)
1367 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1368 else if (!DuplicateHandle (GetCurrentProcess(), h,
1369 GetCurrentProcess(), &h2,
1370 EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1372 log_error ("setting syncronize for scd notify event failed: %s\n",
1373 w32_strerror (-1) );
1374 CloseHandle (h);
1376 else
1378 CloseHandle (h);
1379 the_event = h2;
1383 log_debug ("returning notify handle %p\n", the_event);
1384 return the_event;
1386 #endif /*HAVE_W32_SYSTEM*/
1390 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1391 true using STANDARD_NAME in the home directory or if given as
1392 false from the mkdir type name TEMPLATE. In the latter case a
1393 unique name in a unique new directory will be created. In both
1394 cases check for valid characters as well as against a maximum
1395 allowed length for a unix domain socket is done. The function
1396 terminates the process in case of an error. Returns: Pointer to an
1397 allocated string with the absolute name of the socket used. */
1398 static char *
1399 create_socket_name (char *standard_name, char *template)
1401 char *name, *p;
1403 if (use_standard_socket)
1404 name = make_filename (opt.homedir, standard_name, NULL);
1405 else
1407 name = xstrdup (template);
1408 p = strrchr (name, '/');
1409 if (!p)
1410 BUG ();
1411 *p = 0;
1412 if (!mkdtemp (name))
1414 log_error (_("can't create directory `%s': %s\n"),
1415 name, strerror (errno));
1416 agent_exit (2);
1418 *p = '/';
1421 if (strchr (name, PATHSEP_C))
1423 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1424 agent_exit (2);
1426 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1428 log_error (_("name of socket too long\n"));
1429 agent_exit (2);
1431 return name;
1436 /* Create a Unix domain socket with NAME. Returns the file descriptor
1437 or terminates the process in case of an error. Not that this
1438 function needs to be used for the regular socket first and only
1439 then for the ssh socket. */
1440 static gnupg_fd_t
1441 create_server_socket (char *name, int is_ssh, assuan_sock_nonce_t *nonce)
1443 struct sockaddr_un *serv_addr;
1444 socklen_t len;
1445 gnupg_fd_t fd;
1446 int rc;
1448 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1449 if (fd == ASSUAN_INVALID_FD)
1451 log_error (_("can't create socket: %s\n"), strerror (errno));
1452 agent_exit (2);
1455 serv_addr = xmalloc (sizeof (*serv_addr));
1456 memset (serv_addr, 0, sizeof *serv_addr);
1457 serv_addr->sun_family = AF_UNIX;
1458 if (strlen (name) + 1 >= sizeof (serv_addr->sun_path))
1460 log_error (_("socket name `%s' is too long\n"), name);
1461 agent_exit (2);
1463 strcpy (serv_addr->sun_path, name);
1464 len = SUN_LEN (serv_addr);
1465 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1466 if (use_standard_socket && rc == -1 && errno == EADDRINUSE)
1468 /* Check whether a gpg-agent is already running on the standard
1469 socket. We do this test only if this is not the ssh socket.
1470 For ssh we assume that a test for gpg-agent has already been
1471 done and reuse the requested ssh socket. Testing the
1472 ssh-socket is not possible because at this point, though we
1473 know the new Assuan socket, the Assuan server and thus the
1474 ssh-agent server is not yet operational. This would lead to
1475 a hang. */
1476 if (!is_ssh && !check_for_running_agent (1, 1))
1478 log_error (_("a gpg-agent is already running - "
1479 "not starting a new one\n"));
1480 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1481 assuan_sock_close (fd);
1482 agent_exit (2);
1484 remove (name);
1485 rc = assuan_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1487 if (rc != -1
1488 && (rc=assuan_sock_get_nonce ((struct sockaddr*)serv_addr, len, nonce)))
1489 log_error (_("error getting nonce for the socket\n"));
1490 if (rc == -1)
1492 /* We use gpg_strerror here because it allows us to get strings
1493 for some W32 socket error codes. */
1494 log_error (_("error binding socket to `%s': %s\n"),
1495 serv_addr->sun_path,
1496 gpg_strerror (gpg_error_from_errno (errno)));
1498 assuan_sock_close (fd);
1499 if (use_standard_socket)
1500 *name = 0; /* Inhibit removal of the socket by cleanup(). */
1501 agent_exit (2);
1504 if (listen (FD2INT(fd), 5 ) == -1)
1506 log_error (_("listen() failed: %s\n"), strerror (errno));
1507 assuan_sock_close (fd);
1508 agent_exit (2);
1511 if (opt.verbose)
1512 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1514 return fd;
1518 /* Check that the directory for storing the private keys exists and
1519 create it if not. This function won't fail as it is only a
1520 convenience function and not strictly necessary. */
1521 static void
1522 create_private_keys_directory (const char *home)
1524 char *fname;
1525 struct stat statbuf;
1527 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1528 if (stat (fname, &statbuf) && errno == ENOENT)
1530 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1531 if (!CreateDirectory (fname, NULL))
1532 log_error (_("can't create directory `%s': %s\n"),
1533 fname, w32_strerror (-1) );
1534 #else
1535 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1536 log_error (_("can't create directory `%s': %s\n"),
1537 fname, strerror (errno) );
1538 #endif
1539 else if (!opt.quiet)
1540 log_info (_("directory `%s' created\n"), fname);
1542 xfree (fname);
1545 /* Create the directory only if the supplied directory name is the
1546 same as the default one. This way we avoid to create arbitrary
1547 directories when a non-default home directory is used. To cope
1548 with HOME, we compare only the suffix if we see that the default
1549 homedir does start with a tilde. We don't stop here in case of
1550 problems because other functions will throw an error anyway.*/
1551 static void
1552 create_directories (void)
1554 struct stat statbuf;
1555 const char *defhome = standard_homedir ();
1556 char *home;
1558 home = make_filename (opt.homedir, NULL);
1559 if ( stat (home, &statbuf) )
1561 if (errno == ENOENT)
1563 if (
1564 #ifdef HAVE_W32_SYSTEM
1565 ( !compare_filenames (home, defhome) )
1566 #else
1567 (*defhome == '~'
1568 && (strlen (home) >= strlen (defhome+1)
1569 && !strcmp (home + strlen(home)
1570 - strlen (defhome+1), defhome+1)))
1571 || (*defhome != '~' && !strcmp (home, defhome) )
1572 #endif
1575 #ifdef HAVE_W32_SYSTEM
1576 if (!CreateDirectory (home, NULL))
1577 log_error (_("can't create directory `%s': %s\n"),
1578 home, w32_strerror (-1) );
1579 #else
1580 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1581 log_error (_("can't create directory `%s': %s\n"),
1582 home, strerror (errno) );
1583 #endif
1584 else
1586 if (!opt.quiet)
1587 log_info (_("directory `%s' created\n"), home);
1588 create_private_keys_directory (home);
1592 else
1593 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1595 else if ( !S_ISDIR(statbuf.st_mode))
1597 log_error (_("can't use `%s' as home directory\n"), home);
1599 else /* exists and is a directory. */
1601 create_private_keys_directory (home);
1603 xfree (home);
1608 /* This is the worker for the ticker. It is called every few seconds
1609 and may only do fast operations. */
1610 static void
1611 handle_tick (void)
1613 static time_t last_minute;
1615 if (!last_minute)
1616 last_minute = time (NULL);
1618 /* Check whether the scdaemon has died and cleanup in this case. */
1619 agent_scd_check_aliveness ();
1621 /* If we are running as a child of another process, check whether
1622 the parent is still alive and shutdown if not. */
1623 #ifndef HAVE_W32_SYSTEM
1624 if (parent_pid != (pid_t)(-1))
1626 if (kill (parent_pid, 0))
1628 shutdown_pending = 2;
1629 log_info ("parent process died - shutting down\n");
1630 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1631 cleanup ();
1632 agent_exit (0);
1635 #endif /*HAVE_W32_SYSTEM*/
1637 /* Code to be run every minute. */
1638 if (last_minute + 60 <= time (NULL))
1640 check_own_socket ();
1641 last_minute = time (NULL);
1647 /* A global function which allows us to call the reload stuff from
1648 other places too. This is only used when build for W32. */
1649 void
1650 agent_sighup_action (void)
1652 log_info ("SIGHUP received - "
1653 "re-reading configuration and flushing cache\n");
1654 agent_flush_cache ();
1655 reread_configuration ();
1656 agent_reload_trustlist ();
1660 static void
1661 agent_sigusr2_action (void)
1663 if (opt.verbose)
1664 log_info ("SIGUSR2 received - updating card event counter\n");
1665 /* Nothing to check right now. We only increment a counter. */
1666 bump_card_eventcounter ();
1670 static void
1671 handle_signal (int signo)
1673 switch (signo)
1675 #ifndef HAVE_W32_SYSTEM
1676 case SIGHUP:
1677 agent_sighup_action ();
1678 break;
1680 case SIGUSR1:
1681 log_info ("SIGUSR1 received - printing internal information:\n");
1682 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1683 agent_query_dump_state ();
1684 agent_scd_dump_state ();
1685 break;
1687 case SIGUSR2:
1688 agent_sigusr2_action ();
1689 break;
1691 case SIGTERM:
1692 if (!shutdown_pending)
1693 log_info ("SIGTERM received - shutting down ...\n");
1694 else
1695 log_info ("SIGTERM received - still %ld running threads\n",
1696 pth_ctrl( PTH_CTRL_GETTHREADS ));
1697 shutdown_pending++;
1698 if (shutdown_pending > 2)
1700 log_info ("shutdown forced\n");
1701 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1702 cleanup ();
1703 agent_exit (0);
1705 break;
1707 case SIGINT:
1708 log_info ("SIGINT received - immediate shutdown\n");
1709 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1710 cleanup ();
1711 agent_exit (0);
1712 break;
1713 #endif
1714 default:
1715 log_info ("signal %d received - no action defined\n", signo);
1720 /* Check the nonce on a new connection. This is a NOP unless we we
1721 are using our Unix domain socket emulation under Windows. */
1722 static int
1723 check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
1725 if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
1727 log_info (_("error reading nonce on fd %d: %s\n"),
1728 FD2INT(ctrl->thread_startup.fd), strerror (errno));
1729 assuan_sock_close (ctrl->thread_startup.fd);
1730 xfree (ctrl);
1731 return -1;
1733 else
1734 return 0;
1738 /* This is the standard connection thread's main function. */
1739 static void *
1740 start_connection_thread (void *arg)
1742 ctrl_t ctrl = arg;
1744 if (check_nonce (ctrl, &socket_nonce))
1745 return NULL;
1747 agent_init_default_ctrl (ctrl);
1748 if (opt.verbose)
1749 log_info (_("handler 0x%lx for fd %d started\n"),
1750 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1752 start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
1753 if (opt.verbose)
1754 log_info (_("handler 0x%lx for fd %d terminated\n"),
1755 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1757 agent_deinit_default_ctrl (ctrl);
1758 xfree (ctrl);
1759 return NULL;
1763 /* This is the ssh connection thread's main function. */
1764 static void *
1765 start_connection_thread_ssh (void *arg)
1767 ctrl_t ctrl = arg;
1769 if (check_nonce (ctrl, &socket_nonce_ssh))
1770 return NULL;
1772 agent_init_default_ctrl (ctrl);
1773 if (opt.verbose)
1774 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1775 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1777 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1778 if (opt.verbose)
1779 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1780 pth_thread_id (), FD2INT(ctrl->thread_startup.fd));
1782 agent_deinit_default_ctrl (ctrl);
1783 xfree (ctrl);
1784 return NULL;
1788 /* Connection handler loop. Wait for connection requests and spawn a
1789 thread after accepting a connection. */
1790 static void
1791 handle_connections (gnupg_fd_t listen_fd, gnupg_fd_t listen_fd_ssh)
1793 pth_attr_t tattr;
1794 pth_event_t ev, time_ev;
1795 sigset_t sigs;
1796 int signo;
1797 struct sockaddr_un paddr;
1798 socklen_t plen;
1799 fd_set fdset, read_fdset;
1800 int ret;
1801 gnupg_fd_t fd;
1802 int nfd;
1804 tattr = pth_attr_new();
1805 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1806 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1808 #ifndef HAVE_W32_SYSTEM /* fixme */
1809 /* Make sure that the signals we are going to handle are not blocked
1810 and create an event object for them. We also set the default
1811 action to ignore because we use an Pth event to get notified
1812 about signals. This avoids that the default action is taken in
1813 case soemthing goes wrong within Pth. The problem might also be
1814 a Pth bug. */
1815 sigemptyset (&sigs );
1817 static const int mysigs[] = { SIGHUP, SIGUSR1, SIGUSR2, SIGINT, SIGTERM };
1818 struct sigaction sa;
1819 int i;
1821 for (i=0; i < DIM (mysigs); i++)
1823 sigemptyset (&sa.sa_mask);
1824 sa.sa_handler = SIG_IGN;
1825 sa.sa_flags = 0;
1826 sigaction (mysigs[i], &sa, NULL);
1828 sigaddset (&sigs, mysigs[i]);
1832 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1833 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1834 #else
1835 # ifdef PTH_EVENT_HANDLE
1836 sigs = 0;
1837 ev = pth_event (PTH_EVENT_HANDLE, get_agent_scd_notify_event ());
1838 signo = 0;
1839 # else
1840 /* Use a dummy event. */
1841 sigs = 0;
1842 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1843 # endif
1844 #endif
1845 time_ev = NULL;
1847 FD_ZERO (&fdset);
1848 FD_SET (FD2INT (listen_fd), &fdset);
1849 nfd = FD2INT (listen_fd);
1850 if (listen_fd_ssh != GNUPG_INVALID_FD)
1852 FD_SET ( FD2INT(listen_fd_ssh), &fdset);
1853 if (FD2INT (listen_fd_ssh) > nfd)
1854 nfd = FD2INT (listen_fd_ssh);
1857 for (;;)
1859 /* Make sure that our signals are not blocked. */
1860 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1862 /* Shutdown test. */
1863 if (shutdown_pending)
1865 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1866 break; /* ready */
1868 /* Do not accept new connections but keep on running the
1869 loop to cope with the timer events. */
1870 FD_ZERO (&fdset);
1873 /* Create a timeout event if needed. To help with power saving
1874 we syncronize the ticks to the next full second. */
1875 if (!time_ev)
1877 pth_time_t nexttick;
1879 nexttick = pth_timeout (TIMERTICK_INTERVAL, 0);
1880 if (nexttick.tv_usec > 10) /* Use a 10 usec threshhold. */
1882 nexttick.tv_sec++;
1883 nexttick.tv_usec = 0;
1885 time_ev = pth_event (PTH_EVENT_TIME, nexttick);
1888 /* POSIX says that fd_set should be implemented as a structure,
1889 thus a simple assignment is fine to copy the entire set. */
1890 read_fdset = fdset;
1892 if (time_ev)
1893 pth_event_concat (ev, time_ev, NULL);
1894 ret = pth_select_ev (nfd+1, &read_fdset, NULL, NULL, NULL, ev);
1895 if (time_ev)
1896 pth_event_isolate (time_ev);
1898 if (ret == -1)
1900 if (pth_event_occurred (ev)
1901 || (time_ev && pth_event_occurred (time_ev)))
1903 if (pth_event_occurred (ev))
1905 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1906 agent_sigusr2_action ();
1907 #else
1908 handle_signal (signo);
1909 #endif
1911 if (time_ev && pth_event_occurred (time_ev))
1913 pth_event_free (time_ev, PTH_FREE_ALL);
1914 time_ev = NULL;
1915 handle_tick ();
1917 continue;
1919 log_error (_("pth_select failed: %s - waiting 1s\n"),
1920 strerror (errno));
1921 pth_sleep (1);
1922 continue;
1925 if (pth_event_occurred (ev))
1927 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1928 agent_sigusr2_action ();
1929 #else
1930 handle_signal (signo);
1931 #endif
1934 if (time_ev && pth_event_occurred (time_ev))
1936 pth_event_free (time_ev, PTH_FREE_ALL);
1937 time_ev = NULL;
1938 handle_tick ();
1942 /* We now might create new threads and because we don't want any
1943 signals (as we are handling them here) to be delivered to a
1944 new thread. Thus we need to block those signals. */
1945 pth_sigmask (SIG_BLOCK, &sigs, NULL);
1947 if (!shutdown_pending && FD_ISSET (FD2INT (listen_fd), &read_fdset))
1949 ctrl_t ctrl;
1951 plen = sizeof paddr;
1952 fd = INT2FD (pth_accept (FD2INT(listen_fd),
1953 (struct sockaddr *)&paddr, &plen));
1954 if (fd == GNUPG_INVALID_FD)
1956 log_error ("accept failed: %s\n", strerror (errno));
1958 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1960 log_error ("error allocating connection control data: %s\n",
1961 strerror (errno) );
1962 assuan_sock_close (fd);
1964 else
1966 char threadname[50];
1968 snprintf (threadname, sizeof threadname-1,
1969 "conn fd=%d (gpg)", FD2INT(fd));
1970 threadname[sizeof threadname -1] = 0;
1971 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1972 ctrl->thread_startup.fd = fd;
1973 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1975 log_error ("error spawning connection handler: %s\n",
1976 strerror (errno) );
1977 assuan_sock_close (fd);
1978 xfree (ctrl);
1981 fd = GNUPG_INVALID_FD;
1984 if (!shutdown_pending && listen_fd_ssh != GNUPG_INVALID_FD
1985 && FD_ISSET ( FD2INT (listen_fd_ssh), &read_fdset))
1987 ctrl_t ctrl;
1989 plen = sizeof paddr;
1990 fd = INT2FD(pth_accept (FD2INT(listen_fd_ssh),
1991 (struct sockaddr *)&paddr, &plen));
1992 if (fd == GNUPG_INVALID_FD)
1994 log_error ("accept failed for ssh: %s\n", strerror (errno));
1996 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1998 log_error ("error allocating connection control data: %s\n",
1999 strerror (errno) );
2000 assuan_sock_close (fd);
2002 else
2004 char threadname[50];
2006 agent_init_default_ctrl (ctrl);
2007 snprintf (threadname, sizeof threadname-1,
2008 "conn fd=%d (ssh)", FD2INT(fd));
2009 threadname[sizeof threadname -1] = 0;
2010 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
2011 ctrl->thread_startup.fd = fd;
2012 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
2014 log_error ("error spawning ssh connection handler: %s\n",
2015 strerror (errno) );
2016 assuan_sock_close (fd);
2017 xfree (ctrl);
2020 fd = GNUPG_INVALID_FD;
2024 pth_event_free (ev, PTH_FREE_ALL);
2025 if (time_ev)
2026 pth_event_free (time_ev, PTH_FREE_ALL);
2027 cleanup ();
2028 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2033 /* Helper for check_own_socket. */
2034 static int
2035 check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2037 membuf_t *mb = opaque;
2038 put_membuf (mb, buffer, length);
2039 return 0;
2043 /* The thread running the actual check. We need to run this in a
2044 separate thread so that check_own_thread can be called from the
2045 timer tick. */
2046 static void *
2047 check_own_socket_thread (void *arg)
2049 int rc;
2050 char *sockname = arg;
2051 assuan_context_t ctx;
2052 membuf_t mb;
2053 char *buffer;
2055 check_own_socket_running++;
2057 rc = assuan_socket_connect (&ctx, sockname, (pid_t)(-1));
2058 xfree (sockname);
2059 if (rc)
2061 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2062 goto leave;
2065 init_membuf (&mb, 100);
2066 rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
2067 NULL, NULL, NULL, NULL);
2068 put_membuf (&mb, "", 1);
2069 buffer = get_membuf (&mb, NULL);
2070 if (rc || !buffer)
2072 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2073 "GETINFO pid", gpg_strerror (rc));
2074 rc = 1;
2076 else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
2078 log_error ("socket is now serviced by another server\n");
2079 rc = 1;
2081 else if (opt.verbose > 1)
2082 log_error ("socket is still served by this server\n");
2084 xfree (buffer);
2085 assuan_disconnect (ctx);
2087 leave:
2088 if (rc)
2090 /* We may not remove the socket as it is now in use by another
2091 server. Setting the name to empty does this. */
2092 if (socket_name)
2093 *socket_name = 0;
2094 if (socket_name_ssh)
2095 *socket_name_ssh = 0;
2096 shutdown_pending = 2;
2097 log_info ("this process is useless - shutting down\n");
2099 check_own_socket_running--;
2100 return NULL;
2104 /* Check whether we are still listening on our own socket. In case
2105 another gpg-agent process started after us has taken ownership of
2106 our socket, we woul linger around without any real taks. Thus we
2107 better check once in a while whether we are really needed. */
2108 static void
2109 check_own_socket (void)
2111 char *sockname;
2112 pth_attr_t tattr;
2114 if (!use_standard_socket)
2115 return; /* This check makes only sense in standard socket mode. */
2117 if (check_own_socket_running || shutdown_pending)
2118 return; /* Still running or already shutting down. */
2120 sockname = make_filename (opt.homedir, "S.gpg-agent", NULL);
2121 if (!sockname)
2122 return; /* Out of memory. */
2124 tattr = pth_attr_new();
2125 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
2126 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
2127 pth_attr_set (tattr, PTH_ATTR_NAME, "check-own-socket");
2129 if (!pth_spawn (tattr, check_own_socket_thread, sockname))
2130 log_error ("error spawning check_own_socket_thread: %s\n",
2131 strerror (errno) );
2132 pth_attr_destroy (tattr);
2137 /* Figure out whether an agent is available and running. Prints an
2138 error if not. If SILENT is true, no messages are printed. Usually
2139 started with MODE 0. Returns 0 if the agent is running. */
2140 static int
2141 check_for_running_agent (int silent, int mode)
2143 int rc;
2144 char *infostr, *p;
2145 assuan_context_t ctx;
2146 int prot, pid;
2148 if (!mode)
2150 infostr = getenv ("GPG_AGENT_INFO");
2151 if (!infostr || !*infostr)
2153 if (!check_for_running_agent (silent, 1))
2154 return 0; /* Okay, its running on the standard socket. */
2155 if (!silent)
2156 log_error (_("no gpg-agent running in this session\n"));
2157 return -1;
2160 infostr = xstrdup (infostr);
2161 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
2163 xfree (infostr);
2164 if (!check_for_running_agent (silent, 1))
2165 return 0; /* Okay, its running on the standard socket. */
2166 if (!silent)
2167 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2168 return -1;
2171 *p++ = 0;
2172 pid = atoi (p);
2173 while (*p && *p != PATHSEP_C)
2174 p++;
2175 prot = *p? atoi (p+1) : 0;
2176 if (prot != 1)
2178 xfree (infostr);
2179 if (!silent)
2180 log_error (_("gpg-agent protocol version %d is not supported\n"),
2181 prot);
2182 if (!check_for_running_agent (silent, 1))
2183 return 0; /* Okay, its running on the standard socket. */
2184 return -1;
2187 else /* MODE != 0 */
2189 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
2190 pid = (pid_t)(-1);
2194 rc = assuan_socket_connect (&ctx, infostr, pid);
2195 xfree (infostr);
2196 if (rc)
2198 if (!mode && !check_for_running_agent (silent, 1))
2199 return 0; /* Okay, its running on the standard socket. */
2201 if (!mode && !silent)
2202 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
2203 return -1;
2206 if (!opt.quiet && !silent)
2207 log_info ("gpg-agent running and available\n");
2209 assuan_disconnect (ctx);
2210 return 0;