2006-12-18 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / agent / gpg-agent.c
blob75ffb70da46b7005567595da995dfb89fd80ccc3
1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 * 2005 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 2 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, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #include <sys/stat.h>
35 #ifndef HAVE_W32_SYSTEM
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #endif /*HAVE_W32_SYSTEM*/
39 #include <unistd.h>
40 #include <signal.h>
41 #include <pth.h>
43 #define JNLIB_NEED_LOG_LOGV
44 #include "agent.h"
45 #include <assuan.h> /* Malloc hooks */
47 #include "i18n.h"
48 #include "sysutils.h"
49 #ifdef HAVE_W32_SYSTEM
50 #include "../jnlib/w32-afunix.h"
51 #endif
52 #include "setenv.h"
55 enum cmd_and_opt_values
56 { aNull = 0,
57 oCsh = 'c',
58 oQuiet = 'q',
59 oSh = 's',
60 oVerbose = 'v',
62 oNoVerbose = 500,
63 aGPGConfList,
64 aGPGConfTest,
65 oOptions,
66 oDebug,
67 oDebugAll,
68 oDebugLevel,
69 oDebugWait,
70 oNoGreeting,
71 oNoOptions,
72 oHomedir,
73 oNoDetach,
74 oNoGrab,
75 oLogFile,
76 oServer,
77 oDaemon,
78 oBatch,
80 oPinentryProgram,
81 oDisplay,
82 oTTYname,
83 oTTYtype,
84 oLCctype,
85 oLCmessages,
86 oScdaemonProgram,
87 oDefCacheTTL,
88 oDefCacheTTLSSH,
89 oMaxCacheTTL,
90 oMaxCacheTTLSSH,
91 oUseStandardSocket,
92 oNoUseStandardSocket,
94 oIgnoreCacheForSigning,
95 oAllowMarkTrusted,
96 oAllowPresetPassphrase,
97 oKeepTTY,
98 oKeepDISPLAY,
99 oSSHSupport,
100 oDisableScdaemon,
101 oWriteEnvFile
106 static ARGPARSE_OPTS opts[] = {
108 { aGPGConfList, "gpgconf-list", 256, "@" },
109 { aGPGConfTest, "gpgconf-test", 256, "@" },
111 { 301, NULL, 0, N_("@Options:\n ") },
113 { oServer, "server", 0, N_("run in server mode (foreground)") },
114 { oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
115 { oVerbose, "verbose", 0, N_("verbose") },
116 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
117 { oSh, "sh", 0, N_("sh-style command output") },
118 { oCsh, "csh", 0, N_("csh-style command output") },
119 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
120 { oDebug, "debug" ,4|16, "@"},
121 { oDebugAll, "debug-all" ,0, "@"},
122 { oDebugLevel, "debug-level" ,2, "@"},
123 { oDebugWait,"debug-wait",1, "@"},
124 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
125 { oNoGrab, "no-grab" ,0, N_("do not grab keyboard and mouse")},
126 { oLogFile, "log-file" ,2, N_("use a log file for the server")},
127 { oUseStandardSocket, "use-standard-socket", 0,
128 N_("use a standard location for the socket")},
129 { oNoUseStandardSocket, "no-use-standard-socket", 0, "@"},
131 { oPinentryProgram, "pinentry-program", 2 ,
132 N_("|PGM|use PGM as the PIN-Entry program") },
133 { oScdaemonProgram, "scdaemon-program", 2 ,
134 N_("|PGM|use PGM as the SCdaemon program") },
135 { oDisableScdaemon, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
137 { oDisplay, "display", 2, "@" },
138 { oTTYname, "ttyname", 2, "@" },
139 { oTTYtype, "ttytype", 2, "@" },
140 { oLCctype, "lc-ctype", 2, "@" },
141 { oLCmessages, "lc-messages", 2, "@" },
142 { oKeepTTY, "keep-tty", 0, N_("ignore requests to change the TTY")},
143 { oKeepDISPLAY, "keep-display",
144 0, N_("ignore requests to change the X display")},
146 { oDefCacheTTL, "default-cache-ttl", 4,
147 N_("|N|expire cached PINs after N seconds")},
148 { oDefCacheTTLSSH, "default-cache-ttl-ssh", 4, "@" },
149 { oMaxCacheTTL, "max-cache-ttl", 4, "@" },
150 { oMaxCacheTTLSSH, "max-cache-ttl-ssh", 4, "@" },
151 { oIgnoreCacheForSigning, "ignore-cache-for-signing", 0,
152 N_("do not use the PIN cache when signing")},
153 { oAllowMarkTrusted, "allow-mark-trusted", 0,
154 N_("allow clients to mark keys as \"trusted\"")},
155 { oAllowPresetPassphrase, "allow-preset-passphrase", 0,
156 N_("allow presetting passphrase")},
157 { oSSHSupport, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
158 { oWriteEnvFile, "write-env-file", 2|8,
159 N_("|FILE|write environment settings also to FILE")},
164 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
165 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
166 #define MAX_CACHE_TTL (120*60) /* 2 hours */
169 /* flag to indicate that a shutdown was requested */
170 static int shutdown_pending;
173 /* It is possible that we are currently running under setuid permissions */
174 static int maybe_setuid = 1;
176 /* Name of the communication socket used for native gpg-agent requests. */
177 static char *socket_name;
179 /* Name of the communication socket used for ssh-agent-emulation. */
180 static char *socket_name_ssh;
182 /* Default values for options passed to the pinentry. */
183 static char *default_display;
184 static char *default_ttyname;
185 static char *default_ttytype;
186 static char *default_lc_ctype;
187 static char *default_lc_messages;
189 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
190 static char *config_filename;
192 /* Helper to implement --debug-level */
193 static const char *debug_level;
195 /* Keep track of the current log file so that we can avoid updating
196 the log file after a SIGHUP if it didn't changed. Malloced. */
197 static char *current_logfile;
199 /* The handle_tick() function may test whether a parent is still
200 running. We record the PID of the parent here or -1 if it should be
201 watched. */
202 static pid_t parent_pid = (pid_t)(-1);
206 Local prototypes.
209 static char *create_socket_name (int use_standard_socket,
210 char *standard_name, char *template);
211 static int create_server_socket (int is_standard_name, const char *name);
212 static void create_directories (void);
214 static void agent_init_default_ctrl (ctrl_t ctrl);
215 static void agent_deinit_default_ctrl (ctrl_t ctrl);
217 static void handle_connections (int listen_fd, int listen_fd_ssh);
218 static int check_for_running_agent (int);
220 /* Pth wrapper function definitions. */
221 GCRY_THREAD_OPTION_PTH_IMPL;
227 Functions.
231 static const char *
232 my_strusage (int level)
234 const char *p;
235 switch (level)
237 case 11: p = "gpg-agent (GnuPG)";
238 break;
239 case 13: p = VERSION; break;
240 case 17: p = PRINTABLE_OS_NAME; break;
241 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
242 break;
243 case 1:
244 case 40: p = _("Usage: gpg-agent [options] (-h for help)");
245 break;
246 case 41: p = _("Syntax: gpg-agent [options] [command [args]]\n"
247 "Secret key management for GnuPG\n");
248 break;
250 default: p = NULL;
252 return p;
257 static void
258 i18n_init (void)
260 #ifdef USE_SIMPLE_GETTEXT
261 set_gettext_file( PACKAGE_GT );
262 #else
263 #ifdef ENABLE_NLS
264 setlocale (LC_ALL, "");
265 bindtextdomain (PACKAGE_GT, LOCALEDIR);
266 textdomain (PACKAGE_GT);
267 #endif
268 #endif
273 /* Used by gcry for logging */
274 static void
275 my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
277 /* translate the log levels */
278 switch (level)
280 case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break;
281 case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break;
282 case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break;
283 case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break;
284 case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break;
285 case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break;
286 case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break;
287 default: level = JNLIB_LOG_ERROR; break;
289 log_logv (level, fmt, arg_ptr);
293 /* This function is called by libgcrypt if it ran out of core and
294 there is no way to return that error to the caller. We do our own
295 function here to make use of our logging functions. */
296 static int
297 my_gcry_outofcore_handler ( void *opaque, size_t req_n, unsigned int flags)
299 static int been_here; /* Used to protect against recursive calls. */
301 if (!been_here)
303 been_here = 1;
304 if ( (flags & 1) )
305 log_fatal (_("out of core in secure memory "
306 "while allocating %lu bytes"), (unsigned long)req_n);
307 else
308 log_fatal (_("out of core while allocating %lu bytes"),
309 (unsigned long)req_n);
311 return 0; /* Let libgcrypt call its own fatal error handler. */
315 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
316 only the active debug flags are propagated to the subsystems. With
317 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
318 all flags already set. Note that we don't fail here, because it is
319 important to keep gpg-agent running even after re-reading the
320 options due to a SIGHUP. */
321 static void
322 set_debug (void)
324 if (!debug_level)
326 else if (!strcmp (debug_level, "none"))
327 opt.debug = 0;
328 else if (!strcmp (debug_level, "basic"))
329 opt.debug = DBG_ASSUAN_VALUE;
330 else if (!strcmp (debug_level, "advanced"))
331 opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
332 else if (!strcmp (debug_level, "expert"))
333 opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
334 |DBG_CACHE_VALUE);
335 else if (!strcmp (debug_level, "guru"))
336 opt.debug = ~0;
337 else
339 log_error (_("invalid debug-level `%s' given\n"), debug_level);
340 opt.debug = 0; /* Reset debugging, so that prior debug
341 statements won't have an undesired effect. */
344 if (opt.debug && !opt.verbose)
345 opt.verbose = 1;
346 if (opt.debug && opt.quiet)
347 opt.quiet = 0;
349 if (opt.debug & DBG_MPI_VALUE)
350 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
351 if (opt.debug & DBG_CRYPTO_VALUE )
352 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
353 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
357 /* Helper for cleanup to remove one socket with NAME. */
358 static void
359 remove_socket (char *name)
361 if (name && *name)
363 char *p;
365 remove (name);
366 p = strrchr (name, '/');
367 if (p)
369 *p = 0;
370 rmdir (name);
371 *p = '/';
373 *name = 0;
377 static void
378 cleanup (void)
380 remove_socket (socket_name);
381 remove_socket (socket_name_ssh);
386 /* Handle options which are allowed to be reset after program start.
387 Return true when the current option in PARGS could be handled and
388 false if not. As a special feature, passing a value of NULL for
389 PARGS, resets the options to the default. REREAD should be set
390 true if it is not the initial option parsing. */
391 static int
392 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
394 if (!pargs)
395 { /* reset mode */
396 opt.quiet = 0;
397 opt.verbose = 0;
398 opt.debug = 0;
399 opt.no_grab = 0;
400 opt.pinentry_program = NULL;
401 opt.scdaemon_program = NULL;
402 opt.def_cache_ttl = DEFAULT_CACHE_TTL;
403 opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
404 opt.max_cache_ttl = MAX_CACHE_TTL;
405 opt.max_cache_ttl_ssh = MAX_CACHE_TTL;
406 opt.ignore_cache_for_signing = 0;
407 opt.allow_mark_trusted = 0;
408 opt.disable_scdaemon = 0;
409 return 1;
412 switch (pargs->r_opt)
414 case oQuiet: opt.quiet = 1; break;
415 case oVerbose: opt.verbose++; break;
417 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
418 case oDebugAll: opt.debug = ~0; break;
419 case oDebugLevel: debug_level = pargs->r.ret_str; break;
421 case oLogFile:
422 if (!reread)
423 return 0; /* not handeld */
424 if (!current_logfile || !pargs->r.ret_str
425 || strcmp (current_logfile, pargs->r.ret_str))
427 log_set_file (pargs->r.ret_str);
428 xfree (current_logfile);
429 current_logfile = xtrystrdup (pargs->r.ret_str);
431 break;
433 case oNoGrab: opt.no_grab = 1; break;
435 case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
436 case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
437 case oDisableScdaemon: opt.disable_scdaemon = 1; break;
439 case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
440 case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
441 case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
442 case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
444 case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
446 case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
448 case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
450 default:
451 return 0; /* not handled */
454 return 1; /* handled */
459 main (int argc, char **argv )
461 ARGPARSE_ARGS pargs;
462 int orig_argc;
463 int may_coredump;
464 char **orig_argv;
465 FILE *configfp = NULL;
466 char *configname = NULL;
467 const char *shell;
468 unsigned configlineno;
469 int parse_debug = 0;
470 int default_config =1;
471 int greeting = 0;
472 int nogreeting = 0;
473 int pipe_server = 0;
474 int is_daemon = 0;
475 int nodetach = 0;
476 int csh_style = 0;
477 char *logfile = NULL;
478 int debug_wait = 0;
479 int gpgconf_list = 0;
480 int standard_socket = 0;
481 gpg_error_t err;
482 const char *env_file_name = NULL;
484 set_strusage (my_strusage);
485 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
486 /* Please note that we may running SUID(ROOT), so be very CAREFUL
487 when adding any stuff between here and the call to INIT_SECMEM()
488 somewhere after the option parsing */
489 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX|JNLIB_LOG_WITH_PID);
491 /* Try to auto set the character set. */
492 set_native_charset (NULL);
494 i18n_init ();
496 /* Libgcrypt requires us to register the threading model first.
497 Note that this will also do the pth_init. */
498 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
499 if (err)
501 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
502 gpg_strerror (err));
506 /* Check that the libraries are suitable. Do it here because
507 the option parsing may need services of the library. */
508 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
510 log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
511 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
514 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
515 assuan_set_assuan_log_stream (log_get_stream ());
516 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
517 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
519 gcry_set_log_handler (my_gcry_logger, NULL);
520 gcry_set_outofcore_handler (my_gcry_outofcore_handler, NULL);
521 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
523 may_coredump = disable_core_dumps ();
525 /* Set default options. */
526 parse_rereadable_options (NULL, 0); /* Reset them to default values. */
527 #ifdef HAVE_W32_SYSTEM
528 standard_socket = 1; /* Under Windows we always use a standard
529 socket. */
530 #endif
532 shell = getenv ("SHELL");
533 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
534 csh_style = 1;
536 opt.homedir = default_homedir ();
538 /* Record some of the original environment strings. */
539 opt.startup_display = getenv ("DISPLAY");
540 if (opt.startup_display)
541 opt.startup_display = xstrdup (opt.startup_display);
542 opt.startup_ttyname = ttyname (0);
543 if (opt.startup_ttyname)
544 opt.startup_ttyname = xstrdup (opt.startup_ttyname);
545 opt.startup_ttytype = getenv ("TERM");
546 if (opt.startup_ttytype)
547 opt.startup_ttytype = xstrdup (opt.startup_ttytype);
548 /* Fixme: Better use the locale function here. */
549 opt.startup_lc_ctype = getenv ("LC_CTYPE");
550 if (opt.startup_lc_ctype)
551 opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
552 opt.startup_lc_messages = getenv ("LC_MESSAGES");
553 if (opt.startup_lc_messages)
554 opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
556 /* Check whether we have a config file on the commandline */
557 orig_argc = argc;
558 orig_argv = argv;
559 pargs.argc = &argc;
560 pargs.argv = &argv;
561 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
562 while (arg_parse( &pargs, opts))
564 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
565 parse_debug++;
566 else if (pargs.r_opt == oOptions)
567 { /* yes there is one, so we do not try the default one, but
568 read the option file when it is encountered at the
569 commandline */
570 default_config = 0;
572 else if (pargs.r_opt == oNoOptions)
573 default_config = 0; /* --no-options */
574 else if (pargs.r_opt == oHomedir)
575 opt.homedir = pargs.r.ret_str;
578 /* Initialize the secure memory. */
579 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
580 maybe_setuid = 0;
583 Now we are now working under our real uid
586 if (default_config)
587 configname = make_filename (opt.homedir, "gpg-agent.conf", NULL );
589 argc = orig_argc;
590 argv = orig_argv;
591 pargs.argc = &argc;
592 pargs.argv = &argv;
593 pargs.flags= 1; /* do not remove the args */
594 next_pass:
595 if (configname)
597 configlineno = 0;
598 configfp = fopen (configname, "r");
599 if (!configfp)
601 if (default_config)
603 if( parse_debug )
604 log_info (_("NOTE: no default option file `%s'\n"),
605 configname );
607 else
609 log_error (_("option file `%s': %s\n"),
610 configname, strerror(errno) );
611 exit(2);
613 xfree (configname);
614 configname = NULL;
616 if (parse_debug && configname )
617 log_info (_("reading options from `%s'\n"), configname );
618 default_config = 0;
621 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
623 if (parse_rereadable_options (&pargs, 0))
624 continue; /* Already handled */
625 switch (pargs.r_opt)
627 case aGPGConfList: gpgconf_list = 1; break;
628 case aGPGConfTest: gpgconf_list = 2; break;
629 case oBatch: opt.batch=1; break;
631 case oDebugWait: debug_wait = pargs.r.ret_int; break;
633 case oOptions:
634 /* config files may not be nested (silently ignore them) */
635 if (!configfp)
637 xfree(configname);
638 configname = xstrdup(pargs.r.ret_str);
639 goto next_pass;
641 break;
642 case oNoGreeting: nogreeting = 1; break;
643 case oNoVerbose: opt.verbose = 0; break;
644 case oNoOptions: break; /* no-options */
645 case oHomedir: opt.homedir = pargs.r.ret_str; break;
646 case oNoDetach: nodetach = 1; break;
647 case oLogFile: logfile = pargs.r.ret_str; break;
648 case oCsh: csh_style = 1; break;
649 case oSh: csh_style = 0; break;
650 case oServer: pipe_server = 1; break;
651 case oDaemon: is_daemon = 1; break;
653 case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
654 case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
655 case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
656 case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
657 case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
658 break;
660 case oUseStandardSocket: standard_socket = 1; break;
661 case oNoUseStandardSocket: standard_socket = 0; break;
663 case oKeepTTY: opt.keep_tty = 1; break;
664 case oKeepDISPLAY: opt.keep_display = 1; break;
666 case oSSHSupport: opt.ssh_support = 1; break;
667 case oWriteEnvFile:
668 if (pargs.r_type)
669 env_file_name = pargs.r.ret_str;
670 else
671 env_file_name = make_filename ("~/.gpg-agent-info", NULL);
672 break;
674 default : pargs.err = configfp? 1:2; break;
677 if (configfp)
679 fclose( configfp );
680 configfp = NULL;
681 /* Keep a copy of the name so that it can be read on SIGHUP. */
682 config_filename = configname;
683 configname = NULL;
684 goto next_pass;
686 xfree (configname);
687 configname = NULL;
688 if (log_get_errorcount(0))
689 exit(2);
690 if (nogreeting )
691 greeting = 0;
693 if (greeting)
695 fprintf (stderr, "%s %s; %s\n",
696 strusage(11), strusage(13), strusage(14) );
697 fprintf (stderr, "%s\n", strusage(15) );
699 #ifdef IS_DEVELOPMENT_VERSION
700 /* We don't want to print it here because gpg-agent is useful of its
701 own and quite matured. */
702 /*log_info ("NOTE: this is a development version!\n");*/
703 #endif
705 set_debug ();
707 if (atexit (cleanup))
709 log_error ("atexit failed\n");
710 cleanup ();
711 exit (1);
714 initialize_module_query ();
715 initialize_module_call_scd ();
717 /* Try to create missing directories. */
718 create_directories ();
720 if (debug_wait && pipe_server)
722 log_debug ("waiting for debugger - my pid is %u .....\n",
723 (unsigned int)getpid());
724 sleep (debug_wait);
725 log_debug ("... okay\n");
728 if (gpgconf_list == 2)
729 agent_exit (0);
730 if (gpgconf_list)
732 char *filename;
734 /* List options and default values in the GPG Conf format. */
736 /* The following list is taken from gnupg/tools/gpgconf-comp.c. */
737 /* Option flags. YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING
738 FLAGS, AS THEY ARE PART OF THE EXTERNAL INTERFACE. */
739 #define GC_OPT_FLAG_NONE 0UL
740 /* The RUNTIME flag for an option indicates that the option can be
741 changed at runtime. */
742 #define GC_OPT_FLAG_RUNTIME (1UL << 3)
743 /* The DEFAULT flag for an option indicates that the option has a
744 default value. */
745 #define GC_OPT_FLAG_DEFAULT (1UL << 4)
746 /* The DEF_DESC flag for an option indicates that the option has a
747 default, which is described by the value of the default field. */
748 #define GC_OPT_FLAG_DEF_DESC (1UL << 5)
749 /* The NO_ARG_DESC flag for an option indicates that the argument has
750 a default, which is described by the value of the ARGDEF field. */
751 #define GC_OPT_FLAG_NO_ARG_DESC (1UL << 6)
753 filename = make_filename (opt.homedir, "gpg-agent.conf", NULL );
754 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
755 GC_OPT_FLAG_DEFAULT, filename);
756 xfree (filename);
758 printf ("verbose:%lu:\n"
759 "quiet:%lu:\n"
760 "debug-level:%lu:\"none:\n"
761 "log-file:%lu:\n",
762 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
763 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
764 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
765 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
766 printf ("default-cache-ttl:%lu:%d:\n",
767 GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
768 printf ("no-grab:%lu:\n",
769 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
770 printf ("ignore-cache-for-signing:%lu:\n",
771 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
772 printf ("allow-mark-trusted:%lu:\n",
773 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
774 printf ("disable-scdaemon:%lu:\n",
775 GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
777 agent_exit (0);
780 /* If this has been called without any options, we merely check
781 whether an agent is already running. We do this here so that we
782 don't clobber a logfile but print it directly to stderr. */
783 if (!pipe_server && !is_daemon)
785 log_set_prefix (NULL, JNLIB_LOG_WITH_PREFIX);
786 check_for_running_agent (0);
787 agent_exit (0);
790 #ifdef ENABLE_NLS
791 /* gpg-agent usually does not output any messages because it runs in
792 the background. For log files it is acceptable to have messages
793 always encoded in utf-8. We switch here to utf-8, so that
794 commands like --help still give native messages. It is far
795 easier to switch only once instead of for every message and it
796 actually helps when more then one thread is active (avoids an
797 extra copy step). */
798 bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
799 #endif
801 /* Now start with logging to a file if this is desired. */
802 if (logfile)
804 log_set_file (logfile);
805 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
806 |JNLIB_LOG_WITH_TIME
807 |JNLIB_LOG_WITH_PID));
808 current_logfile = xstrdup (logfile);
811 /* Make sure that we have a default ttyname. */
812 if (!default_ttyname && ttyname (1))
813 default_ttyname = xstrdup (ttyname (1));
814 if (!default_ttytype && getenv ("TERM"))
815 default_ttytype = xstrdup (getenv ("TERM"));
818 if (pipe_server)
820 /* This is the simple pipe based server */
821 ctrl_t ctrl;
823 ctrl = xtrycalloc (1, sizeof *ctrl);
824 if (!ctrl)
826 log_error ("error allocating connection control data: %s\n",
827 strerror (errno) );
828 agent_exit (1);
830 agent_init_default_ctrl (ctrl);
831 start_command_handler (ctrl, -1, -1);
832 agent_deinit_default_ctrl (ctrl);
833 xfree (ctrl);
835 else if (!is_daemon)
836 ; /* NOTREACHED */
837 else
838 { /* Regular server mode */
839 int fd;
840 int fd_ssh;
841 pid_t pid;
843 /* Remove the DISPLAY variable so that a pinentry does not
844 default to a specific display. There is still a default
845 display when gpg-agent was started using --display or a
846 client requested this using an OPTION command. Note, that we
847 don't do this when running in reverse daemon mode (i.e. when
848 exec the program given as arguments). */
849 #ifndef HAVE_W32_SYSTEM
850 if (!opt.keep_display && !argc)
851 unsetenv ("DISPLAY");
852 #endif
855 /* Create the sockets. */
856 socket_name = create_socket_name (standard_socket,
857 "S.gpg-agent",
858 "/tmp/gpg-XXXXXX/S.gpg-agent");
859 if (opt.ssh_support)
860 socket_name_ssh = create_socket_name (standard_socket,
861 "S.gpg-agent.ssh",
862 "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
864 fd = create_server_socket (standard_socket, socket_name);
865 if (opt.ssh_support)
866 fd_ssh = create_server_socket (standard_socket, socket_name_ssh);
867 else
868 fd_ssh = -1;
870 /* If we are going to exec a program in the parent, we record
871 the PID, so that the child may check whether the program is
872 still alive. */
873 if (argc)
874 parent_pid = getpid ();
876 fflush (NULL);
877 #ifdef HAVE_W32_SYSTEM
878 pid = getpid ();
879 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name, (ulong)pid);
880 #else /*!HAVE_W32_SYSTEM*/
881 pid = fork ();
882 if (pid == (pid_t)-1)
884 log_fatal ("fork failed: %s\n", strerror (errno) );
885 exit (1);
887 else if (pid)
888 { /* We are the parent */
889 char *infostr, *infostr_ssh_sock, *infostr_ssh_pid;
891 close (fd);
893 /* Create the info string: <name>:<pid>:<protocol_version> */
894 if (asprintf (&infostr, "GPG_AGENT_INFO=%s:%lu:1",
895 socket_name, (ulong)pid ) < 0)
897 log_error ("out of core\n");
898 kill (pid, SIGTERM);
899 exit (1);
901 if (opt.ssh_support)
903 if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
904 socket_name_ssh) < 0)
906 log_error ("out of core\n");
907 kill (pid, SIGTERM);
908 exit (1);
910 if (asprintf (&infostr_ssh_pid, "SSH_AGENT_PID=%u",
911 pid) < 0)
913 log_error ("out of core\n");
914 kill (pid, SIGTERM);
915 exit (1);
919 *socket_name = 0; /* Don't let cleanup() remove the socket -
920 the child should do this from now on */
921 if (opt.ssh_support)
922 *socket_name_ssh = 0;
924 if (env_file_name)
926 FILE *fp;
928 fp = fopen (env_file_name, "w");
929 if (!fp)
930 log_error (_("error creating `%s': %s\n"),
931 env_file_name, strerror (errno));
932 else
934 fputs (infostr, fp);
935 putc ('\n', fp);
936 if (opt.ssh_support)
938 fputs (infostr_ssh_sock, fp);
939 putc ('\n', fp);
940 fputs (infostr_ssh_pid, fp);
941 putc ('\n', fp);
943 fclose (fp);
948 if (argc)
949 { /* Run the program given on the commandline. */
950 if (putenv (infostr))
952 log_error ("failed to set environment: %s\n",
953 strerror (errno) );
954 kill (pid, SIGTERM );
955 exit (1);
957 if (opt.ssh_support && putenv (infostr_ssh_sock))
959 log_error ("failed to set environment: %s\n",
960 strerror (errno) );
961 kill (pid, SIGTERM );
962 exit (1);
964 if (opt.ssh_support && putenv (infostr_ssh_pid))
966 log_error ("failed to set environment: %s\n",
967 strerror (errno) );
968 kill (pid, SIGTERM );
969 exit (1);
971 execvp (argv[0], argv);
972 log_error ("failed to run the command: %s\n", strerror (errno));
973 kill (pid, SIGTERM);
974 exit (1);
976 else
978 /* Print the environment string, so that the caller can use
979 shell's eval to set it */
980 if (csh_style)
982 *strchr (infostr, '=') = ' ';
983 printf ("setenv %s\n", infostr);
984 if (opt.ssh_support)
986 *strchr (infostr_ssh_sock, '=') = ' ';
987 printf ("setenv %s\n", infostr_ssh_sock);
988 *strchr (infostr_ssh_pid, '=') = ' ';
989 printf ("setenv %s\n", infostr_ssh_pid);
992 else
994 printf ( "%s; export GPG_AGENT_INFO;\n", infostr);
995 if (opt.ssh_support)
997 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock);
998 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid);
1001 free (infostr); /* (Note that a vanilla free is here correct.) */
1002 if (opt.ssh_support)
1004 free (infostr_ssh_sock);
1005 free (infostr_ssh_pid);
1007 exit (0);
1009 /*NOTREACHED*/
1010 } /* End parent */
1013 This is the child
1016 /* Detach from tty and put process into a new session */
1017 if (!nodetach )
1019 int i;
1020 unsigned int oldflags;
1022 /* Close stdin, stdout and stderr unless it is the log stream */
1023 for (i=0; i <= 2; i++)
1025 if (!log_test_fd (i) && i != fd )
1027 if ( ! close (i)
1028 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1030 log_error ("failed to open `%s': %s\n",
1031 "/dev/null", strerror (errno));
1032 cleanup ();
1033 exit (1);
1037 if (setsid() == -1)
1039 log_error ("setsid() failed: %s\n", strerror(errno) );
1040 cleanup ();
1041 exit (1);
1044 log_get_prefix (&oldflags);
1045 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1046 opt.running_detached = 1;
1049 if (chdir("/"))
1051 log_error ("chdir to / failed: %s\n", strerror (errno));
1052 exit (1);
1056 struct sigaction sa;
1058 sa.sa_handler = SIG_IGN;
1059 sigemptyset (&sa.sa_mask);
1060 sa.sa_flags = 0;
1061 sigaction (SIGPIPE, &sa, NULL);
1063 #endif /*!HAVE_W32_SYSTEM*/
1065 handle_connections (fd, opt.ssh_support ? fd_ssh : -1);
1066 close (fd);
1069 return 0;
1072 void
1073 agent_exit (int rc)
1075 /*FIXME: update_random_seed_file();*/
1076 #if 1
1077 /* at this time a bit annoying */
1078 if (opt.debug & DBG_MEMSTAT_VALUE)
1080 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1081 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1083 if (opt.debug)
1084 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1085 #endif
1086 gcry_control (GCRYCTL_TERM_SECMEM );
1087 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1088 exit (rc);
1092 static void
1093 agent_init_default_ctrl (ctrl_t ctrl)
1095 ctrl->connection_fd = -1;
1097 /* Note we ignore malloc errors because we can't do much about it
1098 and the request will fail anyway shortly after this
1099 initialization. */
1100 if (ctrl->display)
1101 free (ctrl->display);
1102 ctrl->display = default_display? strdup (default_display) : NULL;
1104 if (ctrl->ttyname)
1105 free (ctrl->ttyname);
1106 ctrl->ttyname = default_ttyname? strdup (default_ttyname) : NULL;
1108 if (ctrl->ttytype)
1109 free (ctrl->ttytype);
1110 ctrl->ttytype = default_ttytype? strdup (default_ttytype) : NULL;
1112 if (ctrl->lc_ctype)
1113 free (ctrl->lc_ctype);
1114 ctrl->lc_ctype = default_lc_ctype? strdup (default_lc_ctype) : NULL;
1116 if (ctrl->lc_messages)
1117 free (ctrl->lc_messages);
1118 ctrl->lc_messages = default_lc_messages? strdup (default_lc_messages) : NULL;
1122 static void
1123 agent_deinit_default_ctrl (ctrl_t ctrl)
1125 if (ctrl->display)
1126 free (ctrl->display);
1127 if (ctrl->ttyname)
1128 free (ctrl->ttyname);
1129 if (ctrl->ttytype)
1130 free (ctrl->ttytype);
1131 if (ctrl->lc_ctype)
1132 free (ctrl->lc_ctype);
1133 if (ctrl->lc_messages)
1134 free (ctrl->lc_messages);
1137 /* Reread parts of the configuration. Note, that this function is
1138 obviously not thread-safe and should only be called from the PTH
1139 signal handler.
1141 Fixme: Due to the way the argument parsing works, we create a
1142 memory leak here for all string type arguments. There is currently
1143 no clean way to tell whether the memory for the argument has been
1144 allocated or points into the process' original arguments. Unless
1145 we have a mechanism to tell this, we need to live on with this. */
1146 static void
1147 reread_configuration (void)
1149 ARGPARSE_ARGS pargs;
1150 FILE *fp;
1151 unsigned int configlineno = 0;
1152 int dummy;
1154 if (!config_filename)
1155 return; /* No config file. */
1157 fp = fopen (config_filename, "r");
1158 if (!fp)
1160 log_error (_("option file `%s': %s\n"),
1161 config_filename, strerror(errno) );
1162 return;
1165 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1167 memset (&pargs, 0, sizeof pargs);
1168 dummy = 0;
1169 pargs.argc = &dummy;
1170 pargs.flags = 1; /* do not remove the args */
1171 while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1173 if (pargs.r_opt < -1)
1174 pargs.err = 1; /* Print a warning. */
1175 else /* Try to parse this option - ignore unchangeable ones. */
1176 parse_rereadable_options (&pargs, 1);
1178 fclose (fp);
1179 set_debug ();
1185 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1186 true using STANDARD_NAME in the home directory or if given has
1187 false from the mkdir type name TEMPLATE. In the latter case a
1188 unique name in a unique new directory will be created. In both
1189 cases check for valid characters as well as against a maximum
1190 allowed length for a unix domain socket is done. The function
1191 terminates the process in case of an error. Returns: Pointer to an
1192 allcoated string with the absolute name of the socket used. */
1193 static char *
1194 create_socket_name (int use_standard_socket,
1195 char *standard_name, char *template)
1197 char *name, *p;
1199 if (use_standard_socket)
1200 name = make_filename (opt.homedir, standard_name, NULL);
1201 else
1203 name = xstrdup (template);
1204 p = strrchr (name, '/');
1205 if (!p)
1206 BUG ();
1207 *p = 0;
1208 if (!mkdtemp (name))
1210 log_error (_("can't create directory `%s': %s\n"),
1211 name, strerror (errno));
1212 agent_exit (2);
1214 *p = '/';
1217 if (strchr (name, PATHSEP_C))
1219 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S);
1220 agent_exit (2);
1222 if (strlen (name) + 1 >= DIMof (struct sockaddr_un, sun_path) )
1224 log_error (_("name of socket too long\n"));
1225 agent_exit (2);
1227 return name;
1232 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1233 whether a non-random socket is used. Returns the filedescriptor or
1234 terminates the process in case of an error. */
1235 static int
1236 create_server_socket (int is_standard_name, const char *name)
1238 struct sockaddr_un *serv_addr;
1239 socklen_t len;
1240 int fd;
1241 int rc;
1243 #ifdef HAVE_W32_SYSTEM
1244 fd = _w32_sock_new (AF_UNIX, SOCK_STREAM, 0);
1245 #else
1246 fd = socket (AF_UNIX, SOCK_STREAM, 0);
1247 #endif
1248 if (fd == -1)
1250 log_error (_("can't create socket: %s\n"), strerror (errno));
1251 agent_exit (2);
1254 serv_addr = xmalloc (sizeof (*serv_addr));
1255 memset (serv_addr, 0, sizeof *serv_addr);
1256 serv_addr->sun_family = AF_UNIX;
1257 assert (strlen (name) + 1 < sizeof (serv_addr->sun_path));
1258 strcpy (serv_addr->sun_path, name);
1259 len = (offsetof (struct sockaddr_un, sun_path)
1260 + strlen (serv_addr->sun_path) + 1);
1262 #ifdef HAVE_W32_SYSTEM
1263 rc = _w32_sock_bind (fd, (struct sockaddr*) serv_addr, len);
1264 if (is_standard_name && rc == -1 )
1266 remove (name);
1267 rc = bind (fd, (struct sockaddr*) serv_addr, len);
1269 #else
1270 rc = bind (fd, (struct sockaddr*) serv_addr, len);
1271 if (is_standard_name && rc == -1 && errno == EADDRINUSE)
1273 remove (name);
1274 rc = bind (fd, (struct sockaddr*) serv_addr, len);
1276 #endif
1277 if (rc == -1)
1279 log_error (_("error binding socket to `%s': %s\n"),
1280 serv_addr->sun_path, strerror (errno));
1281 close (fd);
1282 agent_exit (2);
1285 if (listen (fd, 5 ) == -1)
1287 log_error (_("listen() failed: %s\n"), strerror (errno));
1288 close (fd);
1289 agent_exit (2);
1292 if (opt.verbose)
1293 log_info (_("listening on socket `%s'\n"), serv_addr->sun_path);
1295 return fd;
1299 /* Check that the directory for storing the private keys exists and
1300 create it if not. This function won't fail as it is only a
1301 convenience function and not strictly necessary. */
1302 static void
1303 create_private_keys_directory (const char *home)
1305 char *fname;
1306 struct stat statbuf;
1308 fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
1309 if (stat (fname, &statbuf) && errno == ENOENT)
1311 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1312 if (!CreateDirectory (fname, NULL))
1313 log_error (_("can't create directory `%s': %s\n"),
1314 fname, w32_strerror (-1) );
1315 #else
1316 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR ))
1317 log_error (_("can't create directory `%s': %s\n"),
1318 fname, strerror (errno) );
1319 #endif
1320 else if (!opt.quiet)
1321 log_info (_("directory `%s' created\n"), fname);
1323 xfree (fname);
1326 /* Create the directory only if the supplied directory name is the
1327 same as the default one. This way we avoid to create arbitrary
1328 directories when a non-default home directory is used. To cope
1329 with HOME, we compare only the suffix if we see that the default
1330 homedir does start with a tilde. We don't stop here in case of
1331 problems because other functions will throw an error anyway.*/
1332 static void
1333 create_directories (void)
1335 struct stat statbuf;
1336 const char *defhome = GNUPG_DEFAULT_HOMEDIR;
1337 char *home;
1339 home = make_filename (opt.homedir, NULL);
1340 if ( stat (home, &statbuf) )
1342 if (errno == ENOENT)
1344 if ( (*defhome == '~'
1345 && (strlen (home) >= strlen (defhome+1)
1346 && !strcmp (home + strlen(home)
1347 - strlen (defhome+1), defhome+1)))
1348 || (*defhome != '~' && !strcmp (home, defhome) )
1351 #ifdef HAVE_W32_SYSTEM
1352 if (!CreateDirectory (home, NULL))
1353 log_error (_("can't create directory `%s': %s\n"),
1354 home, w32_strerror (-1) );
1355 #else
1356 if (mkdir (home, S_IRUSR|S_IWUSR|S_IXUSR ))
1357 log_error (_("can't create directory `%s': %s\n"),
1358 home, strerror (errno) );
1359 #endif
1360 else
1362 if (!opt.quiet)
1363 log_info (_("directory `%s' created\n"), home);
1364 create_private_keys_directory (home);
1368 else
1369 log_error (_("stat() failed for `%s': %s\n"), home, strerror (errno));
1371 else if ( !S_ISDIR(statbuf.st_mode))
1373 log_error (_("can't use `%s' as home directory\n"), home);
1375 else /* exists and is a directory. */
1377 create_private_keys_directory (home);
1379 xfree (home);
1384 /* This is the worker for the ticker. It is called every few seconds
1385 and may only do fast operations. */
1386 static void
1387 handle_tick (void)
1389 /* Check whether the scdaemon has died and cleanup in this case. */
1390 agent_scd_check_aliveness ();
1392 /* If we are running as a child of another process, check whether
1393 the parent is still alive and shutdown if not. */
1394 #ifndef HAVE_W32_SYSTEM
1395 if (parent_pid != (pid_t)(-1))
1397 if (kill (parent_pid, 0))
1399 shutdown_pending = 2;
1400 log_info ("parent process died - shutting down\n");
1401 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1402 cleanup ();
1403 agent_exit (0);
1406 #endif /*HAVE_W32_SYSTEM*/
1410 static void
1411 handle_signal (int signo)
1413 switch (signo)
1415 #ifndef HAVE_W32_SYSTEM
1416 case SIGHUP:
1417 log_info ("SIGHUP received - "
1418 "re-reading configuration and flushing cache\n");
1419 agent_flush_cache ();
1420 reread_configuration ();
1421 agent_reload_trustlist ();
1422 break;
1424 case SIGUSR1:
1425 log_info ("SIGUSR1 received - printing internal information:\n");
1426 pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ());
1427 agent_query_dump_state ();
1428 agent_scd_dump_state ();
1429 break;
1431 case SIGUSR2:
1432 if (opt.verbose)
1433 log_info ("SIGUSR2 received - checking smartcard status\n");
1434 /* Nothing to check right now. We only increment a counter. */
1435 bump_card_eventcounter ();
1436 break;
1438 case SIGTERM:
1439 if (!shutdown_pending)
1440 log_info ("SIGTERM received - shutting down ...\n");
1441 else
1442 log_info ("SIGTERM received - still %ld running threads\n",
1443 pth_ctrl( PTH_CTRL_GETTHREADS ));
1444 shutdown_pending++;
1445 if (shutdown_pending > 2)
1447 log_info ("shutdown forced\n");
1448 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1449 cleanup ();
1450 agent_exit (0);
1452 break;
1454 case SIGINT:
1455 log_info ("SIGINT received - immediate shutdown\n");
1456 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1457 cleanup ();
1458 agent_exit (0);
1459 break;
1460 #endif
1461 default:
1462 log_info ("signal %d received - no action defined\n", signo);
1467 /* This is the standard connection thread's main function. */
1468 static void *
1469 start_connection_thread (void *arg)
1471 ctrl_t ctrl = arg;
1473 agent_init_default_ctrl (ctrl);
1474 if (opt.verbose)
1475 log_info (_("handler 0x%lx for fd %d started\n"),
1476 (long)pth_self (), ctrl->thread_startup.fd);
1478 start_command_handler (ctrl, -1, ctrl->thread_startup.fd);
1479 if (opt.verbose)
1480 log_info (_("handler 0x%lx for fd %d terminated\n"),
1481 (long)pth_self (), ctrl->thread_startup.fd);
1483 agent_deinit_default_ctrl (ctrl);
1484 xfree (ctrl);
1485 return NULL;
1489 /* This is the ssh connection thread's main function. */
1490 static void *
1491 start_connection_thread_ssh (void *arg)
1493 ctrl_t ctrl = arg;
1495 agent_init_default_ctrl (ctrl);
1496 if (opt.verbose)
1497 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1498 (long)pth_self (), ctrl->thread_startup.fd);
1500 start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
1501 if (opt.verbose)
1502 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1503 (long)pth_self (), ctrl->thread_startup.fd);
1505 agent_deinit_default_ctrl (ctrl);
1506 xfree (ctrl);
1507 return NULL;
1511 /* Connection handler loop. Wait for coecntion requests and spawn a
1512 thread after accepting a connection. */
1513 static void
1514 handle_connections (int listen_fd, int listen_fd_ssh)
1516 pth_attr_t tattr;
1517 pth_event_t ev, time_ev;
1518 sigset_t sigs;
1519 int signo;
1520 struct sockaddr_un paddr;
1521 socklen_t plen;
1522 fd_set fdset, read_fdset;
1523 int ret;
1524 int fd;
1526 tattr = pth_attr_new();
1527 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1528 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
1530 #ifndef HAVE_W32_SYSTEM /* fixme */
1531 /* Make sure that the signals we are going to handle are not blocked
1532 and create an event object for them. */
1533 sigemptyset (&sigs );
1534 sigaddset (&sigs, SIGHUP);
1535 sigaddset (&sigs, SIGUSR1);
1536 sigaddset (&sigs, SIGUSR2);
1537 sigaddset (&sigs, SIGINT);
1538 sigaddset (&sigs, SIGTERM);
1539 pth_sigmask (SIG_UNBLOCK, &sigs, NULL);
1540 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1541 #else
1542 ev = NULL;
1543 #endif
1544 time_ev = NULL;
1546 FD_ZERO (&fdset);
1547 FD_SET (listen_fd, &fdset);
1548 if (listen_fd_ssh != -1)
1549 FD_SET (listen_fd_ssh, &fdset);
1551 for (;;)
1553 sigset_t oldsigs;
1555 if (shutdown_pending)
1557 if (pth_ctrl (PTH_CTRL_GETTHREADS) == 1)
1558 break; /* ready */
1560 /* Do not accept anymore connections and wait for existing
1561 connections to terminate */
1562 signo = 0;
1563 pth_wait (ev);
1564 if (pth_event_occurred (ev) && signo)
1565 handle_signal (signo);
1566 continue;
1569 /* Create a timeout event if needed. */
1570 if (!time_ev)
1571 time_ev = pth_event (PTH_EVENT_TIME, pth_timeout (2, 0));
1573 /* POSIX says that fd_set should be implemented as a structure,
1574 thus a simple assignment is fine to copy the entire set. */
1575 read_fdset = fdset;
1577 if (time_ev)
1578 pth_event_concat (ev, time_ev, NULL);
1579 ret = pth_select_ev (FD_SETSIZE, &read_fdset, NULL, NULL, NULL, ev);
1580 if (time_ev)
1581 pth_event_isolate (time_ev);
1583 if (ret == -1)
1585 if (pth_event_occurred (ev)
1586 || (time_ev && pth_event_occurred (time_ev)))
1588 if (pth_event_occurred (ev))
1589 handle_signal (signo);
1590 if (time_ev && pth_event_occurred (time_ev))
1592 pth_event_free (time_ev, PTH_FREE_ALL);
1593 time_ev = NULL;
1594 handle_tick ();
1596 continue;
1598 log_error (_("pth_select failed: %s - waiting 1s\n"),
1599 strerror (errno));
1600 pth_sleep (1);
1601 continue;
1604 if (pth_event_occurred (ev))
1606 handle_signal (signo);
1609 if (time_ev && pth_event_occurred (time_ev))
1611 pth_event_free (time_ev, PTH_FREE_ALL);
1612 time_ev = NULL;
1613 handle_tick ();
1617 /* We now might create new threads and because we don't want any
1618 signals - we are handling here - to be delivered to a new
1619 thread. Thus we need to block those signals. */
1620 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1622 if (FD_ISSET (listen_fd, &read_fdset))
1624 ctrl_t ctrl;
1626 plen = sizeof paddr;
1627 fd = pth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1628 if (fd == -1)
1630 log_error ("accept failed: %s\n", strerror (errno));
1632 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1634 log_error ("error allocating connection control data: %s\n",
1635 strerror (errno) );
1636 close (fd);
1638 else
1640 char threadname[50];
1642 snprintf (threadname, sizeof threadname-1,
1643 "conn fd=%d (gpg)", fd);
1644 threadname[sizeof threadname -1] = 0;
1645 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1646 ctrl->thread_startup.fd = fd;
1647 if (!pth_spawn (tattr, start_connection_thread, ctrl))
1649 log_error ("error spawning connection handler: %s\n",
1650 strerror (errno) );
1651 close (fd);
1652 xfree (ctrl);
1655 fd = -1;
1658 if (listen_fd_ssh != -1 && FD_ISSET (listen_fd_ssh, &read_fdset))
1660 ctrl_t ctrl;
1662 plen = sizeof paddr;
1663 fd = pth_accept (listen_fd_ssh, (struct sockaddr *)&paddr, &plen);
1664 if (fd == -1)
1666 log_error ("accept failed for ssh: %s\n", strerror (errno));
1668 else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1670 log_error ("error allocating connection control data: %s\n",
1671 strerror (errno) );
1672 close (fd);
1674 else
1676 char threadname[50];
1678 agent_init_default_ctrl (ctrl);
1679 snprintf (threadname, sizeof threadname-1,
1680 "conn fd=%d (ssh)", fd);
1681 threadname[sizeof threadname -1] = 0;
1682 pth_attr_set (tattr, PTH_ATTR_NAME, threadname);
1683 ctrl->thread_startup.fd = fd;
1684 if (!pth_spawn (tattr, start_connection_thread_ssh, ctrl) )
1686 log_error ("error spawning ssh connection handler: %s\n",
1687 strerror (errno) );
1688 close (fd);
1689 xfree (ctrl);
1692 fd = -1;
1695 /* Restore the signal mask. */
1696 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1700 pth_event_free (ev, PTH_FREE_ALL);
1701 if (time_ev)
1702 pth_event_free (time_ev, PTH_FREE_ALL);
1703 cleanup ();
1704 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1708 /* Figure out whether an agent is available and running. Prints an
1709 error if not. Usually started with MODE 0. */
1710 static int
1711 check_for_running_agent (int mode)
1713 int rc;
1714 char *infostr, *p;
1715 assuan_context_t ctx;
1716 int prot, pid;
1718 if (!mode)
1720 infostr = getenv ("GPG_AGENT_INFO");
1721 if (!infostr || !*infostr)
1723 if (!check_for_running_agent (1))
1724 return 0; /* Okay, its running on the standard socket. */
1725 log_error (_("no gpg-agent running in this session\n"));
1726 return -1;
1729 infostr = xstrdup (infostr);
1730 if ( !(p = strchr (infostr, PATHSEP_C)) || p == infostr)
1732 xfree (infostr);
1733 if (!check_for_running_agent (1))
1734 return 0; /* Okay, its running on the standard socket. */
1735 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
1736 return -1;
1739 *p++ = 0;
1740 pid = atoi (p);
1741 while (*p && *p != PATHSEP_C)
1742 p++;
1743 prot = *p? atoi (p+1) : 0;
1744 if (prot != 1)
1746 xfree (infostr);
1747 log_error (_("gpg-agent protocol version %d is not supported\n"),
1748 prot);
1749 if (!check_for_running_agent (1))
1750 return 0; /* Okay, its running on the standard socket. */
1751 return -1;
1754 else /* MODE != 0 */
1756 infostr = make_filename (opt.homedir, "S.gpg-agent", NULL);
1757 pid = (pid_t)(-1);
1761 rc = assuan_socket_connect (&ctx, infostr, pid);
1762 xfree (infostr);
1763 if (rc)
1765 if (!mode && !check_for_running_agent (1))
1766 return 0; /* Okay, its running on the standard socket. */
1768 if (!mode)
1769 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc));
1770 return -1;
1773 if (!opt.quiet)
1774 log_info ("gpg-agent running and available\n");
1776 assuan_disconnect (ctx);
1777 return 0;