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/>.
33 #ifndef HAVE_W32_SYSTEM
34 # include <sys/socket.h>
36 #endif /*!HAVE_W32_SYSTEM*/
41 #define JNLIB_NEED_LOG_LOGV
43 #include <assuan.h> /* Malloc hooks and socket wrappers. */
46 #include "mkdtemp.h" /* Gnulib replacement. */
49 #include "gc-opt-flags.h"
52 enum cmd_and_opt_values
90 oEnforcePassphraseConstraints
,
92 oMinPassphraseNonalpha
,
93 oCheckPassphrasePattern
,
95 oEnablePassphraseHistory
,
100 oIgnoreCacheForSigning
,
102 oAllowPresetPassphrase
,
112 static ARGPARSE_OPTS opts
[] = {
114 { aGPGConfList
, "gpgconf-list", 256, "@" },
115 { aGPGConfTest
, "gpgconf-test", 256, "@" },
117 { 301, NULL
, 0, N_("@Options:\n ") },
119 { oServer
, "server", 0, N_("run in server mode (foreground)") },
120 { oDaemon
, "daemon", 0, N_("run in daemon mode (background)") },
121 { oVerbose
, "verbose", 0, N_("verbose") },
122 { oQuiet
, "quiet", 0, N_("be somewhat more quiet") },
123 { oSh
, "sh", 0, N_("sh-style command output") },
124 { oCsh
, "csh", 0, N_("csh-style command output") },
125 { oOptions
, "options" , 2, N_("|FILE|read options from FILE")},
126 { oDebug
, "debug" ,4|16, "@"},
127 { oDebugAll
, "debug-all" ,0, "@"},
128 { oDebugLevel
, "debug-level" ,2, "@"},
129 { oDebugWait
,"debug-wait",1, "@"},
130 { oNoDetach
, "no-detach" ,0, N_("do not detach from the console")},
131 { oNoGrab
, "no-grab" ,0, N_("do not grab keyboard and mouse")},
132 { oLogFile
, "log-file" ,2, N_("use a log file for the server")},
133 { oUseStandardSocket
, "use-standard-socket", 0,
134 N_("use a standard location for the socket")},
135 { oNoUseStandardSocket
, "no-use-standard-socket", 0, "@"},
136 { oPinentryProgram
, "pinentry-program", 2 ,
137 N_("|PGM|use PGM as the PIN-Entry program") },
138 { oPinentryTouchFile
, "pinentry-touch-file", 2 , "@" },
139 { oScdaemonProgram
, "scdaemon-program", 2 ,
140 N_("|PGM|use PGM as the SCdaemon program") },
141 { oDisableScdaemon
, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
142 { oFakedSystemTime
, "faked-system-time", 2, "@" }, /* (epoch time) */
144 { oBatch
, "batch", 0, "@" },
145 { oHomedir
, "homedir", 2, "@"},
147 { oDisplay
, "display", 2, "@" },
148 { oTTYname
, "ttyname", 2, "@" },
149 { oTTYtype
, "ttytype", 2, "@" },
150 { oLCctype
, "lc-ctype", 2, "@" },
151 { oLCmessages
, "lc-messages", 2, "@" },
152 { oXauthority
, "xauthority", 2, "@" },
153 { oKeepTTY
, "keep-tty", 0, N_("ignore requests to change the TTY")},
154 { oKeepDISPLAY
, "keep-display",
155 0, N_("ignore requests to change the X display")},
157 { oDefCacheTTL
, "default-cache-ttl", 4,
158 N_("|N|expire cached PINs after N seconds")},
159 { oDefCacheTTLSSH
, "default-cache-ttl-ssh", 4, "@" },
160 { oMaxCacheTTL
, "max-cache-ttl", 4, "@" },
161 { oMaxCacheTTLSSH
, "max-cache-ttl-ssh", 4, "@" },
163 { oEnforcePassphraseConstraints
, "enforce-passphrase-constraints", 0, "@"},
164 { oMinPassphraseLen
, "min-passphrase-len", 4, "@" },
165 { oMinPassphraseNonalpha
, "min-passphrase-nonalpha", 4, "@" },
166 { oCheckPassphrasePattern
, "check-passphrase-pattern", 2, "@" },
167 { oMaxPassphraseDays
, "max-passphrase-days", 4, "@" },
168 { oEnablePassphraseHistory
, "enable-passphrase-history", 0, "@" },
170 { oIgnoreCacheForSigning
, "ignore-cache-for-signing", 0,
171 N_("do not use the PIN cache when signing")},
172 { oAllowMarkTrusted
, "allow-mark-trusted", 0,
173 N_("allow clients to mark keys as \"trusted\"")},
174 { oAllowPresetPassphrase
, "allow-preset-passphrase", 0,
175 N_("allow presetting passphrase")},
176 { oSSHSupport
, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
177 { oWriteEnvFile
, "write-env-file", 2|8,
178 N_("|FILE|write environment settings also to FILE")},
183 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
184 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
185 #define MAX_CACHE_TTL (120*60) /* 2 hours */
186 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
187 #define MIN_PASSPHRASE_LEN (8)
188 #define MIN_PASSPHRASE_NONALPHA (1)
189 #define MAX_PASSPHRASE_DAYS (0)
191 /* The timer tick used for housekeeping stuff. For Windows we use a
192 longer period as the SetWaitableTimer seems to signal earlier than
194 #ifdef HAVE_W32_SYSTEM
195 #define TIMERTICK_INTERVAL (4)
197 #define TIMERTICK_INTERVAL (2) /* Seconds. */
200 /* Flag to indicate that a shutdown was requested. */
201 static int shutdown_pending
;
203 /* Counter for the currently running own socket checks. */
204 static int check_own_socket_running
;
206 /* True if we are listening on the standard socket. */
207 static int use_standard_socket
;
209 /* It is possible that we are currently running under setuid permissions */
210 static int maybe_setuid
= 1;
212 /* Name of the communication socket used for native gpg-agent requests. */
213 static char *socket_name
;
215 /* Name of the communication socket used for ssh-agent-emulation. */
216 static char *socket_name_ssh
;
218 /* We need to keep track of the server's nonces (these are dummies for
220 static assuan_sock_nonce_t socket_nonce
;
221 static assuan_sock_nonce_t socket_nonce_ssh
;
224 /* Default values for options passed to the pinentry. */
225 static char *default_display
;
226 static char *default_ttyname
;
227 static char *default_ttytype
;
228 static char *default_lc_ctype
;
229 static char *default_lc_messages
;
230 static char *default_xauthority
;
232 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
233 static char *config_filename
;
235 /* Helper to implement --debug-level */
236 static const char *debug_level
;
238 /* Keep track of the current log file so that we can avoid updating
239 the log file after a SIGHUP if it didn't changed. Malloced. */
240 static char *current_logfile
;
242 /* The handle_tick() function may test whether a parent is still
243 running. We record the PID of the parent here or -1 if it should be
245 static pid_t parent_pid
= (pid_t
)(-1);
252 static char *create_socket_name (char *standard_name
, char *template);
253 static gnupg_fd_t
create_server_socket (char *name
, int is_ssh
,
254 assuan_sock_nonce_t
*nonce
);
255 static void create_directories (void);
257 static void agent_init_default_ctrl (ctrl_t ctrl
);
258 static void agent_deinit_default_ctrl (ctrl_t ctrl
);
260 static void handle_connections (gnupg_fd_t listen_fd
,
261 gnupg_fd_t listen_fd_ssh
);
262 static void check_own_socket (void);
263 static int check_for_running_agent (int silent
, int mode
);
265 /* Pth wrapper function definitions. */
266 GCRY_THREAD_OPTION_PTH_IMPL
;
267 static int fixed_gcry_pth_init (void)
269 return pth_self ()? 0 : (pth_init () == FALSE
) ? errno
: 0;
273 #ifndef PTH_HAVE_PTH_THREAD_ID
274 static unsigned long pth_thread_id (void)
276 return (unsigned long)pth_self ();
287 make_libversion (const char *libname
, const char *(*getfnc
)(const char*))
294 gcry_control (GCRYCTL_INIT_SECMEM
, 0, 0); /* Drop setuid. */
298 result
= xmalloc (strlen (libname
) + 1 + strlen (s
) + 1);
299 strcpy (stpcpy (stpcpy (result
, libname
), " "), s
);
305 my_strusage (int level
)
307 static char *ver_gcry
;
312 case 11: p
= "gpg-agent (GnuPG)";
314 case 13: p
= VERSION
; break;
315 case 17: p
= PRINTABLE_OS_NAME
; break;
316 case 19: p
= _("Please report bugs to <" PACKAGE_BUGREPORT
">.\n");
320 ver_gcry
= make_libversion ("libgcrypt", gcry_check_version
);
325 case 40: p
= _("Usage: gpg-agent [options] (-h for help)");
327 case 41: p
= _("Syntax: gpg-agent [options] [command [args]]\n"
328 "Secret key management for GnuPG\n");
338 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
339 only the active debug flags are propagated to the subsystems. With
340 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
341 all flags already set. Note that we don't fail here, because it is
342 important to keep gpg-agent running even after re-reading the
343 options due to a SIGHUP. */
349 else if (!strcmp (debug_level
, "none"))
351 else if (!strcmp (debug_level
, "basic"))
352 opt
.debug
= DBG_ASSUAN_VALUE
;
353 else if (!strcmp (debug_level
, "advanced"))
354 opt
.debug
= DBG_ASSUAN_VALUE
|DBG_COMMAND_VALUE
;
355 else if (!strcmp (debug_level
, "expert"))
356 opt
.debug
= (DBG_ASSUAN_VALUE
|DBG_COMMAND_VALUE
358 else if (!strcmp (debug_level
, "guru"))
362 log_error (_("invalid debug-level `%s' given\n"), debug_level
);
363 opt
.debug
= 0; /* Reset debugging, so that prior debug
364 statements won't have an undesired effect. */
367 if (opt
.debug
&& !opt
.verbose
)
369 if (opt
.debug
&& opt
.quiet
)
372 if (opt
.debug
& DBG_MPI_VALUE
)
373 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 2);
374 if (opt
.debug
& DBG_CRYPTO_VALUE
)
375 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 1);
376 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
380 /* Helper for cleanup to remove one socket with NAME. */
382 remove_socket (char *name
)
389 p
= strrchr (name
, '/');
403 remove_socket (socket_name
);
404 remove_socket (socket_name_ssh
);
409 /* Handle options which are allowed to be reset after program start.
410 Return true when the current option in PARGS could be handled and
411 false if not. As a special feature, passing a value of NULL for
412 PARGS, resets the options to the default. REREAD should be set
413 true if it is not the initial option parsing. */
415 parse_rereadable_options (ARGPARSE_ARGS
*pargs
, int reread
)
423 opt
.pinentry_program
= NULL
;
424 opt
.pinentry_touch_file
= NULL
;
425 opt
.scdaemon_program
= NULL
;
426 opt
.def_cache_ttl
= DEFAULT_CACHE_TTL
;
427 opt
.def_cache_ttl_ssh
= DEFAULT_CACHE_TTL_SSH
;
428 opt
.max_cache_ttl
= MAX_CACHE_TTL
;
429 opt
.max_cache_ttl_ssh
= MAX_CACHE_TTL_SSH
;
430 opt
.enforce_passphrase_constraints
= 0;
431 opt
.min_passphrase_len
= MIN_PASSPHRASE_LEN
;
432 opt
.min_passphrase_nonalpha
= MIN_PASSPHRASE_NONALPHA
;
433 opt
.check_passphrase_pattern
= NULL
;
434 opt
.max_passphrase_days
= MAX_PASSPHRASE_DAYS
;
435 opt
.enable_passhrase_history
= 0;
436 opt
.ignore_cache_for_signing
= 0;
437 opt
.allow_mark_trusted
= 0;
438 opt
.disable_scdaemon
= 0;
442 switch (pargs
->r_opt
)
444 case oQuiet
: opt
.quiet
= 1; break;
445 case oVerbose
: opt
.verbose
++; break;
447 case oDebug
: opt
.debug
|= pargs
->r
.ret_ulong
; break;
448 case oDebugAll
: opt
.debug
= ~0; break;
449 case oDebugLevel
: debug_level
= pargs
->r
.ret_str
; break;
453 return 0; /* not handeld */
454 if (!current_logfile
|| !pargs
->r
.ret_str
455 || strcmp (current_logfile
, pargs
->r
.ret_str
))
457 log_set_file (pargs
->r
.ret_str
);
458 xfree (current_logfile
);
459 current_logfile
= xtrystrdup (pargs
->r
.ret_str
);
463 case oNoGrab
: opt
.no_grab
= 1; break;
465 case oPinentryProgram
: opt
.pinentry_program
= pargs
->r
.ret_str
; break;
466 case oPinentryTouchFile
: opt
.pinentry_touch_file
= pargs
->r
.ret_str
; break;
467 case oScdaemonProgram
: opt
.scdaemon_program
= pargs
->r
.ret_str
; break;
468 case oDisableScdaemon
: opt
.disable_scdaemon
= 1; break;
470 case oDefCacheTTL
: opt
.def_cache_ttl
= pargs
->r
.ret_ulong
; break;
471 case oDefCacheTTLSSH
: opt
.def_cache_ttl_ssh
= pargs
->r
.ret_ulong
; break;
472 case oMaxCacheTTL
: opt
.max_cache_ttl
= pargs
->r
.ret_ulong
; break;
473 case oMaxCacheTTLSSH
: opt
.max_cache_ttl_ssh
= pargs
->r
.ret_ulong
; break;
475 case oEnforcePassphraseConstraints
:
476 opt
.enforce_passphrase_constraints
=1;
478 case oMinPassphraseLen
: opt
.min_passphrase_len
= pargs
->r
.ret_ulong
; break;
479 case oMinPassphraseNonalpha
:
480 opt
.min_passphrase_nonalpha
= pargs
->r
.ret_ulong
;
482 case oCheckPassphrasePattern
:
483 opt
.check_passphrase_pattern
= pargs
->r
.ret_str
;
485 case oMaxPassphraseDays
:
486 opt
.max_passphrase_days
= pargs
->r
.ret_ulong
;
488 case oEnablePassphraseHistory
:
489 opt
.enable_passhrase_history
= 1;
492 case oIgnoreCacheForSigning
: opt
.ignore_cache_for_signing
= 1; break;
494 case oAllowMarkTrusted
: opt
.allow_mark_trusted
= 1; break;
496 case oAllowPresetPassphrase
: opt
.allow_preset_passphrase
= 1; break;
499 return 0; /* not handled */
502 return 1; /* handled */
506 /* The main entry point. */
508 main (int argc
, char **argv
)
514 FILE *configfp
= NULL
;
515 char *configname
= NULL
;
517 unsigned configlineno
;
519 int default_config
=1;
526 char *logfile
= NULL
;
528 int gpgconf_list
= 0;
530 const char *env_file_name
= NULL
;
533 set_strusage (my_strusage
);
534 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN
);
535 /* Please note that we may running SUID(ROOT), so be very CAREFUL
536 when adding any stuff between here and the call to INIT_SECMEM()
537 somewhere after the option parsing */
538 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX
|JNLIB_LOG_WITH_PID
);
540 /* Make sure that our subsystems are ready. */
542 init_common_subsystems ();
545 /* Libgcrypt requires us to register the threading model first.
546 Note that this will also do the pth_init. */
547 gcry_threads_pth
.init
= fixed_gcry_pth_init
;
548 err
= gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pth
);
551 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
556 /* Check that the libraries are suitable. Do it here because
557 the option parsing may need services of the library. */
558 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION
) )
560 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
561 NEED_LIBGCRYPT_VERSION
, gcry_check_version (NULL
) );
564 assuan_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
565 assuan_set_assuan_log_stream (log_get_stream ());
566 assuan_set_assuan_log_prefix (log_get_prefix (NULL
));
567 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT
);
569 setup_libgcrypt_logging ();
570 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL
);
572 may_coredump
= disable_core_dumps ();
574 /* Set default options. */
575 parse_rereadable_options (NULL
, 0); /* Reset them to default values. */
576 #ifdef HAVE_W32_SYSTEM
577 use_standard_socket
= 1; /* Under Windows we always use a standard
581 shell
= getenv ("SHELL");
582 if (shell
&& strlen (shell
) >= 3 && !strcmp (shell
+strlen (shell
)-3, "csh") )
585 opt
.homedir
= default_homedir ();
587 /* Record some of the original environment strings. */
588 opt
.startup_display
= getenv ("DISPLAY");
589 if (opt
.startup_display
)
590 opt
.startup_display
= xstrdup (opt
.startup_display
);
591 opt
.startup_ttyname
= ttyname (0);
592 if (opt
.startup_ttyname
)
593 opt
.startup_ttyname
= xstrdup (opt
.startup_ttyname
);
594 opt
.startup_ttytype
= getenv ("TERM");
595 if (opt
.startup_ttytype
)
596 opt
.startup_ttytype
= xstrdup (opt
.startup_ttytype
);
597 /* Fixme: Better use the locale function here. */
598 opt
.startup_lc_ctype
= getenv ("LC_CTYPE");
599 if (opt
.startup_lc_ctype
)
600 opt
.startup_lc_ctype
= xstrdup (opt
.startup_lc_ctype
);
601 opt
.startup_lc_messages
= getenv ("LC_MESSAGES");
602 if (opt
.startup_lc_messages
)
603 opt
.startup_lc_messages
= xstrdup (opt
.startup_lc_messages
);
604 opt
.startup_xauthority
= getenv ("XAUTHORITY");
605 if (opt
.startup_xauthority
)
606 opt
.startup_xauthority
= xstrdup (opt
.startup_xauthority
);
607 opt
.startup_pinentry_user_data
= getenv ("PINENTRY_USER_DATA");
608 if (opt
.startup_pinentry_user_data
)
609 opt
.startup_pinentry_user_data
= xstrdup (opt
.startup_pinentry_user_data
);
611 /* Check whether we have a config file on the commandline */
616 pargs
.flags
= 1|(1<<6); /* do not remove the args, ignore version */
617 while (arg_parse( &pargs
, opts
))
619 if (pargs
.r_opt
== oDebug
|| pargs
.r_opt
== oDebugAll
)
621 else if (pargs
.r_opt
== oOptions
)
622 { /* yes there is one, so we do not try the default one, but
623 read the option file when it is encountered at the
627 else if (pargs
.r_opt
== oNoOptions
)
628 default_config
= 0; /* --no-options */
629 else if (pargs
.r_opt
== oHomedir
)
630 opt
.homedir
= pargs
.r
.ret_str
;
633 /* Initialize the secure memory. */
634 gcry_control (GCRYCTL_INIT_SECMEM
, 32768, 0);
638 Now we are now working under our real uid
642 configname
= make_filename (opt
.homedir
, "gpg-agent.conf", NULL
);
648 pargs
.flags
= 1; /* do not remove the args */
653 configfp
= fopen (configname
, "r");
659 log_info (_("NOTE: no default option file `%s'\n"),
664 log_error (_("option file `%s': %s\n"),
665 configname
, strerror(errno
) );
671 if (parse_debug
&& configname
)
672 log_info (_("reading options from `%s'\n"), configname
);
676 while (optfile_parse( configfp
, configname
, &configlineno
, &pargs
, opts
) )
678 if (parse_rereadable_options (&pargs
, 0))
679 continue; /* Already handled */
682 case aGPGConfList
: gpgconf_list
= 1; break;
683 case aGPGConfTest
: gpgconf_list
= 2; break;
684 case oBatch
: opt
.batch
=1; break;
686 case oDebugWait
: debug_wait
= pargs
.r
.ret_int
; break;
689 /* config files may not be nested (silently ignore them) */
693 configname
= xstrdup(pargs
.r
.ret_str
);
697 case oNoGreeting
: nogreeting
= 1; break;
698 case oNoVerbose
: opt
.verbose
= 0; break;
699 case oNoOptions
: break; /* no-options */
700 case oHomedir
: opt
.homedir
= pargs
.r
.ret_str
; break;
701 case oNoDetach
: nodetach
= 1; break;
702 case oLogFile
: logfile
= pargs
.r
.ret_str
; break;
703 case oCsh
: csh_style
= 1; break;
704 case oSh
: csh_style
= 0; break;
705 case oServer
: pipe_server
= 1; break;
706 case oDaemon
: is_daemon
= 1; break;
708 case oDisplay
: default_display
= xstrdup (pargs
.r
.ret_str
); break;
709 case oTTYname
: default_ttyname
= xstrdup (pargs
.r
.ret_str
); break;
710 case oTTYtype
: default_ttytype
= xstrdup (pargs
.r
.ret_str
); break;
711 case oLCctype
: default_lc_ctype
= xstrdup (pargs
.r
.ret_str
); break;
712 case oLCmessages
: default_lc_messages
= xstrdup (pargs
.r
.ret_str
);
713 case oXauthority
: default_xauthority
= xstrdup (pargs
.r
.ret_str
);
716 case oUseStandardSocket
: use_standard_socket
= 1; break;
717 case oNoUseStandardSocket
: use_standard_socket
= 0; break;
719 case oFakedSystemTime
:
721 time_t faked_time
= isotime2epoch (pargs
.r
.ret_str
);
722 if (faked_time
== (time_t)(-1))
723 faked_time
= (time_t)strtoul (pargs
.r
.ret_str
, NULL
, 10);
724 gnupg_set_time (faked_time
, 0);
728 case oKeepTTY
: opt
.keep_tty
= 1; break;
729 case oKeepDISPLAY
: opt
.keep_display
= 1; break;
731 case oSSHSupport
: opt
.ssh_support
= 1; break;
734 env_file_name
= pargs
.r
.ret_str
;
736 env_file_name
= make_filename ("~/.gpg-agent-info", NULL
);
739 default : pargs
.err
= configfp
? 1:2; break;
746 /* Keep a copy of the name so that it can be read on SIGHUP. */
747 config_filename
= configname
;
753 if (log_get_errorcount(0))
760 fprintf (stderr
, "%s %s; %s\n",
761 strusage(11), strusage(13), strusage(14) );
762 fprintf (stderr
, "%s\n", strusage(15) );
764 #ifdef IS_DEVELOPMENT_VERSION
765 /* We don't want to print it here because gpg-agent is useful of its
766 own and quite matured. */
767 /*log_info ("NOTE: this is a development version!\n");*/
772 if (atexit (cleanup
))
774 log_error ("atexit failed\n");
779 initialize_module_call_pinentry ();
780 initialize_module_call_scd ();
781 initialize_module_trustlist ();
783 /* Try to create missing directories. */
784 create_directories ();
786 if (debug_wait
&& pipe_server
)
788 log_debug ("waiting for debugger - my pid is %u .....\n",
789 (unsigned int)getpid());
790 gnupg_sleep (debug_wait
);
791 log_debug ("... okay\n");
794 if (gpgconf_list
== 2)
801 /* List options and default values in the GPG Conf format. */
802 filename
= make_filename (opt
.homedir
, "gpg-agent.conf", NULL
);
803 filename_esc
= percent_escape (filename
, NULL
);
805 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
806 GC_OPT_FLAG_DEFAULT
, filename_esc
);
808 xfree (filename_esc
);
810 printf ("verbose:%lu:\n"
812 "debug-level:%lu:\"none:\n"
814 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
,
815 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
,
816 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
817 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
818 printf ("default-cache-ttl:%lu:%d:\n",
819 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, DEFAULT_CACHE_TTL
);
820 printf ("default-cache-ttl-ssh:%lu:%d:\n",
821 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, DEFAULT_CACHE_TTL_SSH
);
822 printf ("max-cache-ttl:%lu:%d:\n",
823 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MAX_CACHE_TTL
);
824 printf ("max-cache-ttl-ssh:%lu:%d:\n",
825 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MAX_CACHE_TTL_SSH
);
826 printf ("enforce-passphrase-constraints:%lu:\n",
827 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
828 printf ("min-passphrase-len:%lu:%d:\n",
829 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MIN_PASSPHRASE_LEN
);
830 printf ("min-passphrase-nonalpha:%lu:%d:\n",
831 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
832 MIN_PASSPHRASE_NONALPHA
);
833 printf ("check-passphrase-pattern:%lu:\n",
834 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
);
835 printf ("max-passphrase-days:%lu:%d:\n",
836 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
837 MAX_PASSPHRASE_DAYS
);
838 printf ("enable-passphrase-history:%lu:\n",
839 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
840 printf ("no-grab:%lu:\n",
841 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
842 printf ("ignore-cache-for-signing:%lu:\n",
843 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
844 printf ("allow-mark-trusted:%lu:\n",
845 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
846 printf ("disable-scdaemon:%lu:\n",
847 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
852 /* If this has been called without any options, we merely check
853 whether an agent is already running. We do this here so that we
854 don't clobber a logfile but print it directly to stderr. */
855 if (!pipe_server
&& !is_daemon
)
857 log_set_prefix (NULL
, JNLIB_LOG_WITH_PREFIX
);
858 check_for_running_agent (0, 0);
863 /* gpg-agent usually does not output any messages because it runs in
864 the background. For log files it is acceptable to have messages
865 always encoded in utf-8. We switch here to utf-8, so that
866 commands like --help still give native messages. It is far
867 easier to switch only once instead of for every message and it
868 actually helps when more then one thread is active (avoids an
870 bind_textdomain_codeset (PACKAGE_GT
, "UTF-8");
873 /* Now start with logging to a file if this is desired. */
876 log_set_file (logfile
);
877 log_set_prefix (NULL
, (JNLIB_LOG_WITH_PREFIX
879 |JNLIB_LOG_WITH_PID
));
880 current_logfile
= xstrdup (logfile
);
881 assuan_set_assuan_log_stream (log_get_stream ());
884 /* Make sure that we have a default ttyname. */
885 if (!default_ttyname
&& ttyname (1))
886 default_ttyname
= xstrdup (ttyname (1));
887 if (!default_ttytype
&& getenv ("TERM"))
888 default_ttytype
= xstrdup (getenv ("TERM"));
893 /* This is the simple pipe based server */
896 ctrl
= xtrycalloc (1, sizeof *ctrl
);
899 log_error ("error allocating connection control data: %s\n",
903 agent_init_default_ctrl (ctrl
);
904 start_command_handler (ctrl
, GNUPG_INVALID_FD
, GNUPG_INVALID_FD
);
905 agent_deinit_default_ctrl (ctrl
);
911 { /* Regular server mode */
916 /* Remove the DISPLAY variable so that a pinentry does not
917 default to a specific display. There is still a default
918 display when gpg-agent was started using --display or a
919 client requested this using an OPTION command. Note, that we
920 don't do this when running in reverse daemon mode (i.e. when
921 exec the program given as arguments). */
922 #ifndef HAVE_W32_SYSTEM
923 if (!opt
.keep_display
&& !argc
)
924 unsetenv ("DISPLAY");
928 /* Create the sockets. */
929 socket_name
= create_socket_name
930 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
932 socket_name_ssh
= create_socket_name
933 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
935 fd
= create_server_socket (socket_name
, 0, &socket_nonce
);
937 fd_ssh
= create_server_socket (socket_name_ssh
, 1, &socket_nonce_ssh
);
939 fd_ssh
= GNUPG_INVALID_FD
;
941 /* If we are going to exec a program in the parent, we record
942 the PID, so that the child may check whether the program is
945 parent_pid
= getpid ();
948 #ifdef HAVE_W32_SYSTEM
950 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name
, (ulong
)pid
);
951 #else /*!HAVE_W32_SYSTEM*/
953 if (pid
== (pid_t
)-1)
955 log_fatal ("fork failed: %s\n", strerror (errno
) );
959 { /* We are the parent */
960 char *infostr
, *infostr_ssh_sock
, *infostr_ssh_pid
;
964 /* Create the info string: <name>:<pid>:<protocol_version> */
965 if (asprintf (&infostr
, "GPG_AGENT_INFO=%s:%lu:1",
966 socket_name
, (ulong
)pid
) < 0)
968 log_error ("out of core\n");
974 if (asprintf (&infostr_ssh_sock
, "SSH_AUTH_SOCK=%s",
975 socket_name_ssh
) < 0)
977 log_error ("out of core\n");
981 if (asprintf (&infostr_ssh_pid
, "SSH_AGENT_PID=%u",
984 log_error ("out of core\n");
990 *socket_name
= 0; /* Don't let cleanup() remove the socket -
991 the child should do this from now on */
993 *socket_name_ssh
= 0;
999 fp
= fopen (env_file_name
, "w");
1001 log_error (_("error creating `%s': %s\n"),
1002 env_file_name
, strerror (errno
));
1005 fputs (infostr
, fp
);
1007 if (opt
.ssh_support
)
1009 fputs (infostr_ssh_sock
, fp
);
1011 fputs (infostr_ssh_pid
, fp
);
1020 { /* Run the program given on the commandline. */
1021 if (putenv (infostr
))
1023 log_error ("failed to set environment: %s\n",
1025 kill (pid
, SIGTERM
);
1028 if (opt
.ssh_support
&& putenv (infostr_ssh_sock
))
1030 log_error ("failed to set environment: %s\n",
1032 kill (pid
, SIGTERM
);
1035 if (opt
.ssh_support
&& putenv (infostr_ssh_pid
))
1037 log_error ("failed to set environment: %s\n",
1039 kill (pid
, SIGTERM
);
1042 execvp (argv
[0], argv
);
1043 log_error ("failed to run the command: %s\n", strerror (errno
));
1044 kill (pid
, SIGTERM
);
1049 /* Print the environment string, so that the caller can use
1050 shell's eval to set it */
1053 *strchr (infostr
, '=') = ' ';
1054 printf ("setenv %s\n", infostr
);
1055 if (opt
.ssh_support
)
1057 *strchr (infostr_ssh_sock
, '=') = ' ';
1058 printf ("setenv %s\n", infostr_ssh_sock
);
1059 *strchr (infostr_ssh_pid
, '=') = ' ';
1060 printf ("setenv %s\n", infostr_ssh_pid
);
1065 printf ( "%s; export GPG_AGENT_INFO;\n", infostr
);
1066 if (opt
.ssh_support
)
1068 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock
);
1069 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid
);
1073 if (opt
.ssh_support
)
1075 xfree (infostr_ssh_sock
);
1076 xfree (infostr_ssh_pid
);
1087 /* Detach from tty and put process into a new session */
1091 unsigned int oldflags
;
1093 /* Close stdin, stdout and stderr unless it is the log stream */
1094 for (i
=0; i
<= 2; i
++)
1096 if (!log_test_fd (i
) && i
!= fd
)
1099 && open ("/dev/null", i
? O_WRONLY
: O_RDONLY
) == -1)
1101 log_error ("failed to open `%s': %s\n",
1102 "/dev/null", strerror (errno
));
1110 log_error ("setsid() failed: %s\n", strerror(errno
) );
1115 log_get_prefix (&oldflags
);
1116 log_set_prefix (NULL
, oldflags
| JNLIB_LOG_RUN_DETACHED
);
1117 opt
.running_detached
= 1;
1122 log_error ("chdir to / failed: %s\n", strerror (errno
));
1127 struct sigaction sa
;
1129 sa
.sa_handler
= SIG_IGN
;
1130 sigemptyset (&sa
.sa_mask
);
1132 sigaction (SIGPIPE
, &sa
, NULL
);
1134 #endif /*!HAVE_W32_SYSTEM*/
1136 handle_connections (fd
, opt
.ssh_support
? fd_ssh
: GNUPG_INVALID_FD
);
1137 assuan_sock_close (fd
);
1147 /*FIXME: update_random_seed_file();*/
1149 /* at this time a bit annoying */
1150 if (opt
.debug
& DBG_MEMSTAT_VALUE
)
1152 gcry_control( GCRYCTL_DUMP_MEMORY_STATS
);
1153 gcry_control( GCRYCTL_DUMP_RANDOM_STATS
);
1156 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
1158 gcry_control (GCRYCTL_TERM_SECMEM
);
1159 rc
= rc
? rc
: log_get_errorcount(0)? 2 : 0;
1164 agent_init_default_ctrl (ctrl_t ctrl
)
1166 /* Note we ignore malloc errors because we can't do much about it
1167 and the request will fail anyway shortly after this
1170 xfree (ctrl
->display
);
1171 ctrl
->display
= default_display
? xtrystrdup (default_display
) : NULL
;
1174 xfree (ctrl
->ttyname
);
1175 ctrl
->ttyname
= default_ttyname
? xtrystrdup (default_ttyname
) : NULL
;
1178 xfree (ctrl
->ttytype
);
1179 ctrl
->ttytype
= default_ttytype
? xtrystrdup (default_ttytype
) : NULL
;
1182 xfree (ctrl
->lc_ctype
);
1183 ctrl
->lc_ctype
= default_lc_ctype
? xtrystrdup (default_lc_ctype
) : NULL
;
1185 if (ctrl
->lc_messages
)
1186 xfree (ctrl
->lc_messages
);
1187 ctrl
->lc_messages
= default_lc_messages
? xtrystrdup (default_lc_messages
)
1190 if (ctrl
->xauthority
)
1191 xfree (ctrl
->xauthority
);
1192 ctrl
->xauthority
= default_xauthority
? xtrystrdup (default_xauthority
)
1195 if (ctrl
->pinentry_user_data
)
1196 xfree (ctrl
->pinentry_user_data
);
1197 ctrl
->pinentry_user_data
= NULL
;
1202 agent_deinit_default_ctrl (ctrl_t ctrl
)
1205 xfree (ctrl
->display
);
1207 xfree (ctrl
->ttyname
);
1209 xfree (ctrl
->ttytype
);
1211 xfree (ctrl
->lc_ctype
);
1212 if (ctrl
->lc_messages
)
1213 xfree (ctrl
->lc_messages
);
1214 if (ctrl
->xauthority
)
1215 xfree (ctrl
->xauthority
);
1216 if (ctrl
->pinentry_user_data
)
1217 xfree (ctrl
->pinentry_user_data
);
1220 /* Reread parts of the configuration. Note, that this function is
1221 obviously not thread-safe and should only be called from the PTH
1224 Fixme: Due to the way the argument parsing works, we create a
1225 memory leak here for all string type arguments. There is currently
1226 no clean way to tell whether the memory for the argument has been
1227 allocated or points into the process' original arguments. Unless
1228 we have a mechanism to tell this, we need to live on with this. */
1230 reread_configuration (void)
1232 ARGPARSE_ARGS pargs
;
1234 unsigned int configlineno
= 0;
1237 if (!config_filename
)
1238 return; /* No config file. */
1240 fp
= fopen (config_filename
, "r");
1243 log_error (_("option file `%s': %s\n"),
1244 config_filename
, strerror(errno
) );
1248 parse_rereadable_options (NULL
, 1); /* Start from the default values. */
1250 memset (&pargs
, 0, sizeof pargs
);
1252 pargs
.argc
= &dummy
;
1253 pargs
.flags
= 1; /* do not remove the args */
1254 while (optfile_parse (fp
, config_filename
, &configlineno
, &pargs
, opts
) )
1256 if (pargs
.r_opt
< -1)
1257 pargs
.err
= 1; /* Print a warning. */
1258 else /* Try to parse this option - ignore unchangeable ones. */
1259 parse_rereadable_options (&pargs
, 1);
1266 /* Return the file name of the socket we are using for native
1269 get_agent_socket_name (void)
1271 const char *s
= socket_name
;
1273 return (s
&& *s
)? s
: NULL
;
1276 /* Return the file name of the socket we are using for SSH
1279 get_agent_ssh_socket_name (void)
1281 const char *s
= socket_name_ssh
;
1283 return (s
&& *s
)? s
: NULL
;
1287 /* Under W32, this function returns the handle of the scdaemon
1288 notification event. Calling it the first time creates that
1290 #ifdef HAVE_W32_SYSTEM
1292 get_agent_scd_notify_event (void)
1294 static HANDLE the_event
;
1299 SECURITY_ATTRIBUTES sa
= { sizeof (SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1301 /* We need to use manual reset evet object due to the way our
1302 w32-pth wait function works: If we would use an automatic
1303 reset event we are not able to figure out which handle has
1304 been signaled because at the time we single out the signaled
1305 handles using WFSO the event has already been reset due to
1307 h
= CreateEvent (&sa
, TRUE
, FALSE
, NULL
);
1309 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1310 else if (!DuplicateHandle (GetCurrentProcess(), h
,
1311 GetCurrentProcess(), &h2
,
1312 EVENT_MODIFY_STATE
|SYNCHRONIZE
, TRUE
, 0))
1314 log_error ("setting syncronize for scd notify event failed: %s\n",
1315 w32_strerror (-1) );
1325 log_debug ("returning notify handle %p\n", the_event
);
1328 #endif /*HAVE_W32_SYSTEM*/
1332 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1333 true using STANDARD_NAME in the home directory or if given as
1334 false from the mkdir type name TEMPLATE. In the latter case a
1335 unique name in a unique new directory will be created. In both
1336 cases check for valid characters as well as against a maximum
1337 allowed length for a unix domain socket is done. The function
1338 terminates the process in case of an error. Returns: Pointer to an
1339 allocated string with the absolute name of the socket used. */
1341 create_socket_name (char *standard_name
, char *template)
1345 if (use_standard_socket
)
1346 name
= make_filename (opt
.homedir
, standard_name
, NULL
);
1349 name
= xstrdup (template);
1350 p
= strrchr (name
, '/');
1354 if (!mkdtemp (name
))
1356 log_error (_("can't create directory `%s': %s\n"),
1357 name
, strerror (errno
));
1363 if (strchr (name
, PATHSEP_C
))
1365 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S
);
1368 if (strlen (name
) + 1 >= DIMof (struct sockaddr_un
, sun_path
) )
1370 log_error (_("name of socket too long\n"));
1378 /* Create a Unix domain socket with NAME. Returns the file descriptor
1379 or terminates the process in case of an error. Not that this
1380 function needs to be used for the regular socket first and only
1381 then for the ssh socket. */
1383 create_server_socket (char *name
, int is_ssh
, assuan_sock_nonce_t
*nonce
)
1385 struct sockaddr_un
*serv_addr
;
1390 fd
= assuan_sock_new (AF_UNIX
, SOCK_STREAM
, 0);
1391 if (fd
== ASSUAN_INVALID_FD
)
1393 log_error (_("can't create socket: %s\n"), strerror (errno
));
1397 serv_addr
= xmalloc (sizeof (*serv_addr
));
1398 memset (serv_addr
, 0, sizeof *serv_addr
);
1399 serv_addr
->sun_family
= AF_UNIX
;
1400 if (strlen (name
) + 1 >= sizeof (serv_addr
->sun_path
))
1402 log_error (_("socket name `%s' is too long\n"), name
);
1405 strcpy (serv_addr
->sun_path
, name
);
1406 len
= (offsetof (struct sockaddr_un
, sun_path
)
1407 + strlen (serv_addr
->sun_path
) + 1);
1409 rc
= assuan_sock_bind (fd
, (struct sockaddr
*) serv_addr
, len
);
1410 if (use_standard_socket
&& rc
== -1 && errno
== EADDRINUSE
)
1412 /* Check whether a gpg-agent is already running on the standard
1413 socket. We do this test only if this is not the ssh socket.
1414 For ssh we assume that a test for gpg-agent has already been
1415 done and reuse the requested ssh socket. Testing the
1416 ssh-socket is not possible because at this point, though we
1417 know the new Assuan socket, the Assuan server and thus the
1418 ssh-agent server is not yet operational. This would lead to
1420 if (!is_ssh
&& !check_for_running_agent (1, 1))
1422 log_error (_("a gpg-agent is already running - "
1423 "not starting a new one\n"));
1424 *name
= 0; /* Inhibit removal of the socket by cleanup(). */
1425 assuan_sock_close (fd
);
1429 rc
= assuan_sock_bind (fd
, (struct sockaddr
*) serv_addr
, len
);
1432 && (rc
=assuan_sock_get_nonce ((struct sockaddr
*)serv_addr
, len
, nonce
)))
1433 log_error (_("error getting nonce for the socket\n"));
1436 /* We use gpg_strerror here because it allows us to get strings
1437 for some W32 socket error codes. */
1438 log_error (_("error binding socket to `%s': %s\n"),
1439 serv_addr
->sun_path
,
1440 gpg_strerror (gpg_error_from_errno (errno
)));
1442 assuan_sock_close (fd
);
1443 if (use_standard_socket
)
1444 *name
= 0; /* Inhibit removal of the socket by cleanup(). */
1448 if (listen (FD2INT(fd
), 5 ) == -1)
1450 log_error (_("listen() failed: %s\n"), strerror (errno
));
1451 assuan_sock_close (fd
);
1456 log_info (_("listening on socket `%s'\n"), serv_addr
->sun_path
);
1462 /* Check that the directory for storing the private keys exists and
1463 create it if not. This function won't fail as it is only a
1464 convenience function and not strictly necessary. */
1466 create_private_keys_directory (const char *home
)
1469 struct stat statbuf
;
1471 fname
= make_filename (home
, GNUPG_PRIVATE_KEYS_DIR
, NULL
);
1472 if (stat (fname
, &statbuf
) && errno
== ENOENT
)
1474 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1475 if (!CreateDirectory (fname
, NULL
))
1476 log_error (_("can't create directory `%s': %s\n"),
1477 fname
, w32_strerror (-1) );
1479 if (mkdir (fname
, S_IRUSR
|S_IWUSR
|S_IXUSR
))
1480 log_error (_("can't create directory `%s': %s\n"),
1481 fname
, strerror (errno
) );
1483 else if (!opt
.quiet
)
1484 log_info (_("directory `%s' created\n"), fname
);
1489 /* Create the directory only if the supplied directory name is the
1490 same as the default one. This way we avoid to create arbitrary
1491 directories when a non-default home directory is used. To cope
1492 with HOME, we compare only the suffix if we see that the default
1493 homedir does start with a tilde. We don't stop here in case of
1494 problems because other functions will throw an error anyway.*/
1496 create_directories (void)
1498 struct stat statbuf
;
1499 const char *defhome
= standard_homedir ();
1502 home
= make_filename (opt
.homedir
, NULL
);
1503 if ( stat (home
, &statbuf
) )
1505 if (errno
== ENOENT
)
1508 #ifdef HAVE_W32_SYSTEM
1509 ( !compare_filenames (home
, defhome
) )
1512 && (strlen (home
) >= strlen (defhome
+1)
1513 && !strcmp (home
+ strlen(home
)
1514 - strlen (defhome
+1), defhome
+1)))
1515 || (*defhome
!= '~' && !strcmp (home
, defhome
) )
1519 #ifdef HAVE_W32_SYSTEM
1520 if (!CreateDirectory (home
, NULL
))
1521 log_error (_("can't create directory `%s': %s\n"),
1522 home
, w32_strerror (-1) );
1524 if (mkdir (home
, S_IRUSR
|S_IWUSR
|S_IXUSR
))
1525 log_error (_("can't create directory `%s': %s\n"),
1526 home
, strerror (errno
) );
1531 log_info (_("directory `%s' created\n"), home
);
1532 create_private_keys_directory (home
);
1537 log_error (_("stat() failed for `%s': %s\n"), home
, strerror (errno
));
1539 else if ( !S_ISDIR(statbuf
.st_mode
))
1541 log_error (_("can't use `%s' as home directory\n"), home
);
1543 else /* exists and is a directory. */
1545 create_private_keys_directory (home
);
1552 /* This is the worker for the ticker. It is called every few seconds
1553 and may only do fast operations. */
1557 static time_t last_minute
;
1560 last_minute
= time (NULL
);
1562 /* Check whether the scdaemon has died and cleanup in this case. */
1563 agent_scd_check_aliveness ();
1565 /* If we are running as a child of another process, check whether
1566 the parent is still alive and shutdown if not. */
1567 #ifndef HAVE_W32_SYSTEM
1568 if (parent_pid
!= (pid_t
)(-1))
1570 if (kill (parent_pid
, 0))
1572 shutdown_pending
= 2;
1573 log_info ("parent process died - shutting down\n");
1574 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1579 #endif /*HAVE_W32_SYSTEM*/
1581 /* Code to be run every minute. */
1582 if (last_minute
+ 60 <= time (NULL
))
1584 check_own_socket ();
1585 last_minute
= time (NULL
);
1591 /* A global function which allows us to call the reload stuff from
1592 other places too. This is only used when build for W32. */
1594 agent_sighup_action (void)
1596 log_info ("SIGHUP received - "
1597 "re-reading configuration and flushing cache\n");
1598 agent_flush_cache ();
1599 reread_configuration ();
1600 agent_reload_trustlist ();
1605 agent_sigusr2_action (void)
1608 log_info ("SIGUSR2 received - updating card event counter\n");
1609 /* Nothing to check right now. We only increment a counter. */
1610 bump_card_eventcounter ();
1615 handle_signal (int signo
)
1619 #ifndef HAVE_W32_SYSTEM
1621 agent_sighup_action ();
1625 log_info ("SIGUSR1 received - printing internal information:\n");
1626 pth_ctrl (PTH_CTRL_DUMPSTATE
, log_get_stream ());
1627 agent_query_dump_state ();
1628 agent_scd_dump_state ();
1632 agent_sigusr2_action ();
1636 if (!shutdown_pending
)
1637 log_info ("SIGTERM received - shutting down ...\n");
1639 log_info ("SIGTERM received - still %ld running threads\n",
1640 pth_ctrl( PTH_CTRL_GETTHREADS
));
1642 if (shutdown_pending
> 2)
1644 log_info ("shutdown forced\n");
1645 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1652 log_info ("SIGINT received - immediate shutdown\n");
1653 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1659 log_info ("signal %d received - no action defined\n", signo
);
1664 /* Check the nonce on a new connection. This is a NOP unless we we
1665 are using our Unix domain socket emulation under Windows. */
1667 check_nonce (ctrl_t ctrl
, assuan_sock_nonce_t
*nonce
)
1669 if (assuan_sock_check_nonce (ctrl
->thread_startup
.fd
, nonce
))
1671 log_info (_("error reading nonce on fd %d: %s\n"),
1672 FD2INT(ctrl
->thread_startup
.fd
), strerror (errno
));
1673 assuan_sock_close (ctrl
->thread_startup
.fd
);
1682 /* This is the standard connection thread's main function. */
1684 start_connection_thread (void *arg
)
1688 if (check_nonce (ctrl
, &socket_nonce
))
1691 agent_init_default_ctrl (ctrl
);
1693 log_info (_("handler 0x%lx for fd %d started\n"),
1694 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1696 start_command_handler (ctrl
, GNUPG_INVALID_FD
, ctrl
->thread_startup
.fd
);
1698 log_info (_("handler 0x%lx for fd %d terminated\n"),
1699 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1701 agent_deinit_default_ctrl (ctrl
);
1707 /* This is the ssh connection thread's main function. */
1709 start_connection_thread_ssh (void *arg
)
1713 if (check_nonce (ctrl
, &socket_nonce_ssh
))
1716 agent_init_default_ctrl (ctrl
);
1718 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1719 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1721 start_command_handler_ssh (ctrl
, ctrl
->thread_startup
.fd
);
1723 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1724 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1726 agent_deinit_default_ctrl (ctrl
);
1732 /* Connection handler loop. Wait for connection requests and spawn a
1733 thread after accepting a connection. */
1735 handle_connections (gnupg_fd_t listen_fd
, gnupg_fd_t listen_fd_ssh
)
1738 pth_event_t ev
, time_ev
;
1741 struct sockaddr_un paddr
;
1743 fd_set fdset
, read_fdset
;
1748 tattr
= pth_attr_new();
1749 pth_attr_set (tattr
, PTH_ATTR_JOINABLE
, 0);
1750 pth_attr_set (tattr
, PTH_ATTR_STACK_SIZE
, 256*1024);
1752 #ifndef HAVE_W32_SYSTEM /* fixme */
1753 /* Make sure that the signals we are going to handle are not blocked
1754 and create an event object for them. We also set the default
1755 action to ignore because we use an Pth event to get notified
1756 about signals. This avoids that the default action is taken in
1757 case soemthing goes wrong within Pth. The problem might also be
1759 sigemptyset (&sigs
);
1761 static const int mysigs
[] = { SIGHUP
, SIGUSR1
, SIGUSR2
, SIGINT
, SIGTERM
};
1762 struct sigaction sa
;
1765 for (i
=0; i
< DIM (mysigs
); i
++)
1767 sigemptyset (&sa
.sa_mask
);
1768 sa
.sa_handler
= SIG_IGN
;
1770 sigaction (mysigs
[i
], &sa
, NULL
);
1772 sigaddset (&sigs
, mysigs
[i
]);
1776 pth_sigmask (SIG_UNBLOCK
, &sigs
, NULL
);
1777 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1779 # ifdef PTH_EVENT_HANDLE
1781 ev
= pth_event (PTH_EVENT_HANDLE
, get_agent_scd_notify_event ());
1784 /* Use a dummy event. */
1786 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1792 FD_SET (FD2INT (listen_fd
), &fdset
);
1793 nfd
= FD2INT (listen_fd
);
1794 if (listen_fd_ssh
!= GNUPG_INVALID_FD
)
1796 FD_SET ( FD2INT(listen_fd_ssh
), &fdset
);
1797 if (FD2INT (listen_fd_ssh
) > nfd
)
1798 nfd
= FD2INT (listen_fd_ssh
);
1803 /* Make sure that our signals are not blocked. */
1804 pth_sigmask (SIG_UNBLOCK
, &sigs
, NULL
);
1806 /* Shutdown test. */
1807 if (shutdown_pending
)
1809 if (pth_ctrl (PTH_CTRL_GETTHREADS
) == 1)
1812 /* Do not accept new connections but keep on running the
1813 loop to cope with the timer events. */
1817 /* Create a timeout event if needed. To help with power saving
1818 we syncronize the ticks to the next full second. */
1821 pth_time_t nexttick
;
1823 nexttick
= pth_timeout (TIMERTICK_INTERVAL
, 0);
1824 if (nexttick
.tv_usec
> 10) /* Use a 10 usec threshhold. */
1827 nexttick
.tv_usec
= 0;
1829 time_ev
= pth_event (PTH_EVENT_TIME
, nexttick
);
1832 /* POSIX says that fd_set should be implemented as a structure,
1833 thus a simple assignment is fine to copy the entire set. */
1837 pth_event_concat (ev
, time_ev
, NULL
);
1838 ret
= pth_select_ev (nfd
+1, &read_fdset
, NULL
, NULL
, NULL
, ev
);
1840 pth_event_isolate (time_ev
);
1844 if (pth_event_occurred (ev
)
1845 || (time_ev
&& pth_event_occurred (time_ev
)))
1847 if (pth_event_occurred (ev
))
1849 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1850 agent_sigusr2_action ();
1852 handle_signal (signo
);
1855 if (time_ev
&& pth_event_occurred (time_ev
))
1857 pth_event_free (time_ev
, PTH_FREE_ALL
);
1863 log_error (_("pth_select failed: %s - waiting 1s\n"),
1869 if (pth_event_occurred (ev
))
1871 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1872 agent_sigusr2_action ();
1874 handle_signal (signo
);
1878 if (time_ev
&& pth_event_occurred (time_ev
))
1880 pth_event_free (time_ev
, PTH_FREE_ALL
);
1886 /* We now might create new threads and because we don't want any
1887 signals (as we are handling them here) to be delivered to a
1888 new thread. Thus we need to block those signals. */
1889 pth_sigmask (SIG_BLOCK
, &sigs
, NULL
);
1891 if (!shutdown_pending
&& FD_ISSET (FD2INT (listen_fd
), &read_fdset
))
1895 plen
= sizeof paddr
;
1896 fd
= INT2FD (pth_accept (FD2INT(listen_fd
),
1897 (struct sockaddr
*)&paddr
, &plen
));
1898 if (fd
== GNUPG_INVALID_FD
)
1900 log_error ("accept failed: %s\n", strerror (errno
));
1902 else if ( !(ctrl
= xtrycalloc (1, sizeof *ctrl
)) )
1904 log_error ("error allocating connection control data: %s\n",
1906 assuan_sock_close (fd
);
1910 char threadname
[50];
1912 snprintf (threadname
, sizeof threadname
-1,
1913 "conn fd=%d (gpg)", FD2INT(fd
));
1914 threadname
[sizeof threadname
-1] = 0;
1915 pth_attr_set (tattr
, PTH_ATTR_NAME
, threadname
);
1916 ctrl
->thread_startup
.fd
= fd
;
1917 if (!pth_spawn (tattr
, start_connection_thread
, ctrl
))
1919 log_error ("error spawning connection handler: %s\n",
1921 assuan_sock_close (fd
);
1925 fd
= GNUPG_INVALID_FD
;
1928 if (!shutdown_pending
&& listen_fd_ssh
!= GNUPG_INVALID_FD
1929 && FD_ISSET ( FD2INT (listen_fd_ssh
), &read_fdset
))
1933 plen
= sizeof paddr
;
1934 fd
= INT2FD(pth_accept (FD2INT(listen_fd_ssh
),
1935 (struct sockaddr
*)&paddr
, &plen
));
1936 if (fd
== GNUPG_INVALID_FD
)
1938 log_error ("accept failed for ssh: %s\n", strerror (errno
));
1940 else if ( !(ctrl
= xtrycalloc (1, sizeof *ctrl
)) )
1942 log_error ("error allocating connection control data: %s\n",
1944 assuan_sock_close (fd
);
1948 char threadname
[50];
1950 agent_init_default_ctrl (ctrl
);
1951 snprintf (threadname
, sizeof threadname
-1,
1952 "conn fd=%d (ssh)", FD2INT(fd
));
1953 threadname
[sizeof threadname
-1] = 0;
1954 pth_attr_set (tattr
, PTH_ATTR_NAME
, threadname
);
1955 ctrl
->thread_startup
.fd
= fd
;
1956 if (!pth_spawn (tattr
, start_connection_thread_ssh
, ctrl
) )
1958 log_error ("error spawning ssh connection handler: %s\n",
1960 assuan_sock_close (fd
);
1964 fd
= GNUPG_INVALID_FD
;
1968 pth_event_free (ev
, PTH_FREE_ALL
);
1970 pth_event_free (time_ev
, PTH_FREE_ALL
);
1972 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1977 /* Helper for check_own_socket. */
1979 check_own_socket_pid_cb (void *opaque
, const void *buffer
, size_t length
)
1981 membuf_t
*mb
= opaque
;
1982 put_membuf (mb
, buffer
, length
);
1987 /* The thread running the actual check. We need to run this in a
1988 separate thread so that check_own_thread can be called from the
1991 check_own_socket_thread (void *arg
)
1994 char *sockname
= arg
;
1995 assuan_context_t ctx
;
1999 check_own_socket_running
++;
2001 rc
= assuan_socket_connect (&ctx
, sockname
, (pid_t
)(-1));
2005 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc
));
2009 init_membuf (&mb
, 100);
2010 rc
= assuan_transact (ctx
, "GETINFO pid", check_own_socket_pid_cb
, &mb
,
2011 NULL
, NULL
, NULL
, NULL
);
2012 put_membuf (&mb
, "", 1);
2013 buffer
= get_membuf (&mb
, NULL
);
2016 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2017 "GETINFO pid", gpg_strerror (rc
));
2020 else if ( (pid_t
)strtoul (buffer
, NULL
, 10) != getpid ())
2022 log_error ("socket is now serviced by another server\n");
2025 else if (opt
.verbose
> 1)
2026 log_error ("socket is still served by this server\n");
2029 assuan_disconnect (ctx
);
2034 /* We may not remove the socket as it is now in use by another
2035 server. Setting the name to empty does this. */
2038 if (socket_name_ssh
)
2039 *socket_name_ssh
= 0;
2040 shutdown_pending
= 2;
2041 log_info ("this process is useless - shutting down\n");
2043 check_own_socket_running
--;
2048 /* Check whether we are still listening on our own socket. In case
2049 another gpg-agent process started after us has taken ownership of
2050 our socket, we woul linger around without any real taks. Thus we
2051 better check once in a while whether we are really needed. */
2053 check_own_socket (void)
2058 if (!use_standard_socket
)
2059 return; /* This check makes only sense in standard socket mode. */
2061 if (check_own_socket_running
|| shutdown_pending
)
2062 return; /* Still running or already shutting down. */
2064 sockname
= make_filename (opt
.homedir
, "S.gpg-agent", NULL
);
2066 return; /* Out of memory. */
2068 tattr
= pth_attr_new();
2069 pth_attr_set (tattr
, PTH_ATTR_JOINABLE
, 0);
2070 pth_attr_set (tattr
, PTH_ATTR_STACK_SIZE
, 256*1024);
2071 pth_attr_set (tattr
, PTH_ATTR_NAME
, "check-own-socket");
2073 if (!pth_spawn (tattr
, check_own_socket_thread
, sockname
))
2074 log_error ("error spawning check_own_socket_thread: %s\n",
2076 pth_attr_destroy (tattr
);
2081 /* Figure out whether an agent is available and running. Prints an
2082 error if not. If SILENT is true, no messages are printed. Usually
2083 started with MODE 0. Returns 0 if the agent is running. */
2085 check_for_running_agent (int silent
, int mode
)
2089 assuan_context_t ctx
;
2094 infostr
= getenv ("GPG_AGENT_INFO");
2095 if (!infostr
|| !*infostr
)
2097 if (!check_for_running_agent (silent
, 1))
2098 return 0; /* Okay, its running on the standard socket. */
2100 log_error (_("no gpg-agent running in this session\n"));
2104 infostr
= xstrdup (infostr
);
2105 if ( !(p
= strchr (infostr
, PATHSEP_C
)) || p
== infostr
)
2108 if (!check_for_running_agent (silent
, 1))
2109 return 0; /* Okay, its running on the standard socket. */
2111 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2117 while (*p
&& *p
!= PATHSEP_C
)
2119 prot
= *p
? atoi (p
+1) : 0;
2124 log_error (_("gpg-agent protocol version %d is not supported\n"),
2126 if (!check_for_running_agent (silent
, 1))
2127 return 0; /* Okay, its running on the standard socket. */
2131 else /* MODE != 0 */
2133 infostr
= make_filename (opt
.homedir
, "S.gpg-agent", NULL
);
2138 rc
= assuan_socket_connect (&ctx
, infostr
, pid
);
2142 if (!mode
&& !check_for_running_agent (silent
, 1))
2143 return 0; /* Okay, its running on the standard socket. */
2145 if (!mode
&& !silent
)
2146 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc
));
2150 if (!opt
.quiet
&& !silent
)
2151 log_info ("gpg-agent running and available\n");
2153 assuan_disconnect (ctx
);