1 /* gpg-agent.c - The GnuPG Agent
2 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007 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 { oDisplay
, "display", 2, "@" },
145 { oTTYname
, "ttyname", 2, "@" },
146 { oTTYtype
, "ttytype", 2, "@" },
147 { oLCctype
, "lc-ctype", 2, "@" },
148 { oLCmessages
, "lc-messages", 2, "@" },
149 { oXauthority
, "xauthority", 2, "@" },
150 { oKeepTTY
, "keep-tty", 0, N_("ignore requests to change the TTY")},
151 { oKeepDISPLAY
, "keep-display",
152 0, N_("ignore requests to change the X display")},
154 { oDefCacheTTL
, "default-cache-ttl", 4,
155 N_("|N|expire cached PINs after N seconds")},
156 { oDefCacheTTLSSH
, "default-cache-ttl-ssh", 4, "@" },
157 { oMaxCacheTTL
, "max-cache-ttl", 4, "@" },
158 { oMaxCacheTTLSSH
, "max-cache-ttl-ssh", 4, "@" },
160 { oEnforcePassphraseConstraints
, "enforce-passphrase-constraints", 0, "@"},
161 { oMinPassphraseLen
, "min-passphrase-len", 4, "@" },
162 { oMinPassphraseNonalpha
, "min-passphrase-nonalpha", 4, "@" },
163 { oCheckPassphrasePattern
, "check-passphrase-pattern", 2, "@" },
164 { oMaxPassphraseDays
, "max-passphrase-days", 4, "@" },
165 { oEnablePassphraseHistory
, "enable-passphrase-history", 0, "@" },
167 { oIgnoreCacheForSigning
, "ignore-cache-for-signing", 0,
168 N_("do not use the PIN cache when signing")},
169 { oAllowMarkTrusted
, "allow-mark-trusted", 0,
170 N_("allow clients to mark keys as \"trusted\"")},
171 { oAllowPresetPassphrase
, "allow-preset-passphrase", 0,
172 N_("allow presetting passphrase")},
173 { oSSHSupport
, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
174 { oWriteEnvFile
, "write-env-file", 2|8,
175 N_("|FILE|write environment settings also to FILE")},
180 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
181 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
182 #define MAX_CACHE_TTL (120*60) /* 2 hours */
183 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
184 #define MIN_PASSPHRASE_LEN (8)
185 #define MIN_PASSPHRASE_NONALPHA (1)
186 #define MAX_PASSPHRASE_DAYS (0)
188 /* The timer tick used for housekeeping stuff. For Windows we use a
189 longer period as the SetWaitableTimer seems to signal earlier than
191 #ifdef HAVE_W32_SYSTEM
192 #define TIMERTICK_INTERVAL (4)
194 #define TIMERTICK_INTERVAL (2) /* Seconds. */
197 /* flag to indicate that a shutdown was requested */
198 static int shutdown_pending
;
201 /* It is possible that we are currently running under setuid permissions */
202 static int maybe_setuid
= 1;
204 /* Name of the communication socket used for native gpg-agent requests. */
205 static char *socket_name
;
207 /* Name of the communication socket used for ssh-agent-emulation. */
208 static char *socket_name_ssh
;
210 /* We need to keep track of the server's nonces (these are dummies for
212 static assuan_sock_nonce_t socket_nonce
;
213 static assuan_sock_nonce_t socket_nonce_ssh
;
216 /* Default values for options passed to the pinentry. */
217 static char *default_display
;
218 static char *default_ttyname
;
219 static char *default_ttytype
;
220 static char *default_lc_ctype
;
221 static char *default_lc_messages
;
222 static char *default_xauthority
;
224 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
225 static char *config_filename
;
227 /* Helper to implement --debug-level */
228 static const char *debug_level
;
230 /* Keep track of the current log file so that we can avoid updating
231 the log file after a SIGHUP if it didn't changed. Malloced. */
232 static char *current_logfile
;
234 /* The handle_tick() function may test whether a parent is still
235 running. We record the PID of the parent here or -1 if it should be
237 static pid_t parent_pid
= (pid_t
)(-1);
244 static char *create_socket_name (int use_standard_socket
,
245 char *standard_name
, char *template);
246 static gnupg_fd_t
create_server_socket (int is_standard_name
, char *name
,
248 assuan_sock_nonce_t
*nonce
);
249 static void create_directories (void);
251 static void agent_init_default_ctrl (ctrl_t ctrl
);
252 static void agent_deinit_default_ctrl (ctrl_t ctrl
);
254 static void handle_connections (gnupg_fd_t listen_fd
,
255 gnupg_fd_t listen_fd_ssh
);
256 static int check_for_running_agent (int silent
, int mode
);
258 /* Pth wrapper function definitions. */
259 GCRY_THREAD_OPTION_PTH_IMPL
;
260 static int fixed_gcry_pth_init (void)
262 return pth_self ()? 0 : (pth_init () == FALSE
) ? errno
: 0;
274 my_strusage (int level
)
279 case 11: p
= "gpg-agent (GnuPG)";
281 case 13: p
= VERSION
; break;
282 case 17: p
= PRINTABLE_OS_NAME
; break;
283 case 19: p
= _("Please report bugs to <" PACKAGE_BUGREPORT
">.\n");
286 case 40: p
= _("Usage: gpg-agent [options] (-h for help)");
288 case 41: p
= _("Syntax: gpg-agent [options] [command [args]]\n"
289 "Secret key management for GnuPG\n");
299 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
300 only the active debug flags are propagated to the subsystems. With
301 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
302 all flags already set. Note that we don't fail here, because it is
303 important to keep gpg-agent running even after re-reading the
304 options due to a SIGHUP. */
310 else if (!strcmp (debug_level
, "none"))
312 else if (!strcmp (debug_level
, "basic"))
313 opt
.debug
= DBG_ASSUAN_VALUE
;
314 else if (!strcmp (debug_level
, "advanced"))
315 opt
.debug
= DBG_ASSUAN_VALUE
|DBG_COMMAND_VALUE
;
316 else if (!strcmp (debug_level
, "expert"))
317 opt
.debug
= (DBG_ASSUAN_VALUE
|DBG_COMMAND_VALUE
319 else if (!strcmp (debug_level
, "guru"))
323 log_error (_("invalid debug-level `%s' given\n"), debug_level
);
324 opt
.debug
= 0; /* Reset debugging, so that prior debug
325 statements won't have an undesired effect. */
328 if (opt
.debug
&& !opt
.verbose
)
330 if (opt
.debug
&& opt
.quiet
)
333 if (opt
.debug
& DBG_MPI_VALUE
)
334 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 2);
335 if (opt
.debug
& DBG_CRYPTO_VALUE
)
336 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 1);
337 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
341 /* Helper for cleanup to remove one socket with NAME. */
343 remove_socket (char *name
)
350 p
= strrchr (name
, '/');
364 remove_socket (socket_name
);
365 remove_socket (socket_name_ssh
);
370 /* Handle options which are allowed to be reset after program start.
371 Return true when the current option in PARGS could be handled and
372 false if not. As a special feature, passing a value of NULL for
373 PARGS, resets the options to the default. REREAD should be set
374 true if it is not the initial option parsing. */
376 parse_rereadable_options (ARGPARSE_ARGS
*pargs
, int reread
)
384 opt
.pinentry_program
= NULL
;
385 opt
.pinentry_touch_file
= NULL
;
386 opt
.scdaemon_program
= NULL
;
387 opt
.def_cache_ttl
= DEFAULT_CACHE_TTL
;
388 opt
.def_cache_ttl_ssh
= DEFAULT_CACHE_TTL_SSH
;
389 opt
.max_cache_ttl
= MAX_CACHE_TTL
;
390 opt
.max_cache_ttl_ssh
= MAX_CACHE_TTL_SSH
;
391 opt
.enforce_passphrase_constraints
= 0;
392 opt
.min_passphrase_len
= MIN_PASSPHRASE_LEN
;
393 opt
.min_passphrase_nonalpha
= MIN_PASSPHRASE_NONALPHA
;
394 opt
.check_passphrase_pattern
= NULL
;
395 opt
.max_passphrase_days
= MAX_PASSPHRASE_DAYS
;
396 opt
.enable_passhrase_history
= 0;
397 opt
.ignore_cache_for_signing
= 0;
398 opt
.allow_mark_trusted
= 0;
399 opt
.disable_scdaemon
= 0;
403 switch (pargs
->r_opt
)
405 case oQuiet
: opt
.quiet
= 1; break;
406 case oVerbose
: opt
.verbose
++; break;
408 case oDebug
: opt
.debug
|= pargs
->r
.ret_ulong
; break;
409 case oDebugAll
: opt
.debug
= ~0; break;
410 case oDebugLevel
: debug_level
= pargs
->r
.ret_str
; break;
414 return 0; /* not handeld */
415 if (!current_logfile
|| !pargs
->r
.ret_str
416 || strcmp (current_logfile
, pargs
->r
.ret_str
))
418 log_set_file (pargs
->r
.ret_str
);
419 xfree (current_logfile
);
420 current_logfile
= xtrystrdup (pargs
->r
.ret_str
);
424 case oNoGrab
: opt
.no_grab
= 1; break;
426 case oPinentryProgram
: opt
.pinentry_program
= pargs
->r
.ret_str
; break;
427 case oPinentryTouchFile
: opt
.pinentry_touch_file
= pargs
->r
.ret_str
; break;
428 case oScdaemonProgram
: opt
.scdaemon_program
= pargs
->r
.ret_str
; break;
429 case oDisableScdaemon
: opt
.disable_scdaemon
= 1; break;
431 case oDefCacheTTL
: opt
.def_cache_ttl
= pargs
->r
.ret_ulong
; break;
432 case oDefCacheTTLSSH
: opt
.def_cache_ttl_ssh
= pargs
->r
.ret_ulong
; break;
433 case oMaxCacheTTL
: opt
.max_cache_ttl
= pargs
->r
.ret_ulong
; break;
434 case oMaxCacheTTLSSH
: opt
.max_cache_ttl_ssh
= pargs
->r
.ret_ulong
; break;
436 case oEnforcePassphraseConstraints
:
437 opt
.enforce_passphrase_constraints
=1;
439 case oMinPassphraseLen
: opt
.min_passphrase_len
= pargs
->r
.ret_ulong
; break;
440 case oMinPassphraseNonalpha
:
441 opt
.min_passphrase_nonalpha
= pargs
->r
.ret_ulong
;
443 case oCheckPassphrasePattern
:
444 opt
.check_passphrase_pattern
= pargs
->r
.ret_str
;
446 case oMaxPassphraseDays
:
447 opt
.max_passphrase_days
= pargs
->r
.ret_ulong
;
449 case oEnablePassphraseHistory
:
450 opt
.enable_passhrase_history
= 1;
453 case oIgnoreCacheForSigning
: opt
.ignore_cache_for_signing
= 1; break;
455 case oAllowMarkTrusted
: opt
.allow_mark_trusted
= 1; break;
457 case oAllowPresetPassphrase
: opt
.allow_preset_passphrase
= 1; break;
460 return 0; /* not handled */
463 return 1; /* handled */
467 /* The main entry point. */
469 main (int argc
, char **argv
)
475 FILE *configfp
= NULL
;
476 char *configname
= NULL
;
478 unsigned configlineno
;
480 int default_config
=1;
487 char *logfile
= NULL
;
489 int gpgconf_list
= 0;
490 int use_standard_socket
= 0;
492 const char *env_file_name
= NULL
;
495 set_strusage (my_strusage
);
496 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN
);
497 /* Please note that we may running SUID(ROOT), so be very CAREFUL
498 when adding any stuff between here and the call to INIT_SECMEM()
499 somewhere after the option parsing */
500 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX
|JNLIB_LOG_WITH_PID
);
502 /* Make sure that our subsystems are ready. */
503 init_common_subsystems ();
507 /* Libgcrypt requires us to register the threading model first.
508 Note that this will also do the pth_init. */
509 gcry_threads_pth
.init
= fixed_gcry_pth_init
;
510 err
= gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pth
);
513 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
518 /* Check that the libraries are suitable. Do it here because
519 the option parsing may need services of the library. */
520 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION
) )
522 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
523 NEED_LIBGCRYPT_VERSION
, gcry_check_version (NULL
) );
526 assuan_set_malloc_hooks (gcry_malloc
, gcry_realloc
, gcry_free
);
527 assuan_set_assuan_log_stream (log_get_stream ());
528 assuan_set_assuan_log_prefix (log_get_prefix (NULL
));
529 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT
);
531 setup_libgcrypt_logging ();
532 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL
);
534 may_coredump
= disable_core_dumps ();
536 /* Set default options. */
537 parse_rereadable_options (NULL
, 0); /* Reset them to default values. */
538 #ifdef HAVE_W32_SYSTEM
539 use_standard_socket
= 1; /* Under Windows we always use a standard
543 shell
= getenv ("SHELL");
544 if (shell
&& strlen (shell
) >= 3 && !strcmp (shell
+strlen (shell
)-3, "csh") )
547 opt
.homedir
= default_homedir ();
549 /* Record some of the original environment strings. */
550 opt
.startup_display
= getenv ("DISPLAY");
551 if (opt
.startup_display
)
552 opt
.startup_display
= xstrdup (opt
.startup_display
);
553 opt
.startup_ttyname
= ttyname (0);
554 if (opt
.startup_ttyname
)
555 opt
.startup_ttyname
= xstrdup (opt
.startup_ttyname
);
556 opt
.startup_ttytype
= getenv ("TERM");
557 if (opt
.startup_ttytype
)
558 opt
.startup_ttytype
= xstrdup (opt
.startup_ttytype
);
559 /* Fixme: Better use the locale function here. */
560 opt
.startup_lc_ctype
= getenv ("LC_CTYPE");
561 if (opt
.startup_lc_ctype
)
562 opt
.startup_lc_ctype
= xstrdup (opt
.startup_lc_ctype
);
563 opt
.startup_lc_messages
= getenv ("LC_MESSAGES");
564 if (opt
.startup_lc_messages
)
565 opt
.startup_lc_messages
= xstrdup (opt
.startup_lc_messages
);
566 opt
.startup_xauthority
= getenv ("XAUTHORITY");
567 if (opt
.startup_xauthority
)
568 opt
.startup_xauthority
= xstrdup (opt
.startup_xauthority
);
569 opt
.startup_pinentry_user_data
= getenv ("PINENTRY_USER_DATA");
570 if (opt
.startup_pinentry_user_data
)
571 opt
.startup_pinentry_user_data
= xstrdup (opt
.startup_pinentry_user_data
);
573 /* Check whether we have a config file on the commandline */
578 pargs
.flags
= 1|(1<<6); /* do not remove the args, ignore version */
579 while (arg_parse( &pargs
, opts
))
581 if (pargs
.r_opt
== oDebug
|| pargs
.r_opt
== oDebugAll
)
583 else if (pargs
.r_opt
== oOptions
)
584 { /* yes there is one, so we do not try the default one, but
585 read the option file when it is encountered at the
589 else if (pargs
.r_opt
== oNoOptions
)
590 default_config
= 0; /* --no-options */
591 else if (pargs
.r_opt
== oHomedir
)
592 opt
.homedir
= pargs
.r
.ret_str
;
595 /* Initialize the secure memory. */
596 gcry_control (GCRYCTL_INIT_SECMEM
, 32768, 0);
600 Now we are now working under our real uid
604 configname
= make_filename (opt
.homedir
, "gpg-agent.conf", NULL
);
610 pargs
.flags
= 1; /* do not remove the args */
615 configfp
= fopen (configname
, "r");
621 log_info (_("NOTE: no default option file `%s'\n"),
626 log_error (_("option file `%s': %s\n"),
627 configname
, strerror(errno
) );
633 if (parse_debug
&& configname
)
634 log_info (_("reading options from `%s'\n"), configname
);
638 while (optfile_parse( configfp
, configname
, &configlineno
, &pargs
, opts
) )
640 if (parse_rereadable_options (&pargs
, 0))
641 continue; /* Already handled */
644 case aGPGConfList
: gpgconf_list
= 1; break;
645 case aGPGConfTest
: gpgconf_list
= 2; break;
646 case oBatch
: opt
.batch
=1; break;
648 case oDebugWait
: debug_wait
= pargs
.r
.ret_int
; break;
651 /* config files may not be nested (silently ignore them) */
655 configname
= xstrdup(pargs
.r
.ret_str
);
659 case oNoGreeting
: nogreeting
= 1; break;
660 case oNoVerbose
: opt
.verbose
= 0; break;
661 case oNoOptions
: break; /* no-options */
662 case oHomedir
: opt
.homedir
= pargs
.r
.ret_str
; break;
663 case oNoDetach
: nodetach
= 1; break;
664 case oLogFile
: logfile
= pargs
.r
.ret_str
; break;
665 case oCsh
: csh_style
= 1; break;
666 case oSh
: csh_style
= 0; break;
667 case oServer
: pipe_server
= 1; break;
668 case oDaemon
: is_daemon
= 1; break;
670 case oDisplay
: default_display
= xstrdup (pargs
.r
.ret_str
); break;
671 case oTTYname
: default_ttyname
= xstrdup (pargs
.r
.ret_str
); break;
672 case oTTYtype
: default_ttytype
= xstrdup (pargs
.r
.ret_str
); break;
673 case oLCctype
: default_lc_ctype
= xstrdup (pargs
.r
.ret_str
); break;
674 case oLCmessages
: default_lc_messages
= xstrdup (pargs
.r
.ret_str
);
675 case oXauthority
: default_xauthority
= xstrdup (pargs
.r
.ret_str
);
678 case oUseStandardSocket
: use_standard_socket
= 1; break;
679 case oNoUseStandardSocket
: use_standard_socket
= 0; break;
681 case oFakedSystemTime
:
683 time_t faked_time
= isotime2epoch (pargs
.r
.ret_str
);
684 if (faked_time
== (time_t)(-1))
685 faked_time
= (time_t)strtoul (pargs
.r
.ret_str
, NULL
, 10);
686 gnupg_set_time (faked_time
, 0);
690 case oKeepTTY
: opt
.keep_tty
= 1; break;
691 case oKeepDISPLAY
: opt
.keep_display
= 1; break;
693 case oSSHSupport
: opt
.ssh_support
= 1; break;
696 env_file_name
= pargs
.r
.ret_str
;
698 env_file_name
= make_filename ("~/.gpg-agent-info", NULL
);
701 default : pargs
.err
= configfp
? 1:2; break;
708 /* Keep a copy of the name so that it can be read on SIGHUP. */
709 config_filename
= configname
;
715 if (log_get_errorcount(0))
722 fprintf (stderr
, "%s %s; %s\n",
723 strusage(11), strusage(13), strusage(14) );
724 fprintf (stderr
, "%s\n", strusage(15) );
726 #ifdef IS_DEVELOPMENT_VERSION
727 /* We don't want to print it here because gpg-agent is useful of its
728 own and quite matured. */
729 /*log_info ("NOTE: this is a development version!\n");*/
734 if (atexit (cleanup
))
736 log_error ("atexit failed\n");
741 initialize_module_call_pinentry ();
742 initialize_module_call_scd ();
743 initialize_module_trustlist ();
745 /* Try to create missing directories. */
746 create_directories ();
748 if (debug_wait
&& pipe_server
)
750 log_debug ("waiting for debugger - my pid is %u .....\n",
751 (unsigned int)getpid());
752 gnupg_sleep (debug_wait
);
753 log_debug ("... okay\n");
756 if (gpgconf_list
== 2)
763 /* List options and default values in the GPG Conf format. */
764 filename
= make_filename (opt
.homedir
, "gpg-agent.conf", NULL
);
765 filename_esc
= percent_escape (filename
, NULL
);
767 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
768 GC_OPT_FLAG_DEFAULT
, filename_esc
);
770 xfree (filename_esc
);
772 printf ("verbose:%lu:\n"
774 "debug-level:%lu:\"none:\n"
776 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
,
777 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
,
778 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
779 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
780 printf ("default-cache-ttl:%lu:%d:\n",
781 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, DEFAULT_CACHE_TTL
);
782 printf ("default-cache-ttl-ssh:%lu:%d:\n",
783 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, DEFAULT_CACHE_TTL_SSH
);
784 printf ("max-cache-ttl:%lu:%d:\n",
785 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MAX_CACHE_TTL
);
786 printf ("max-cache-ttl-ssh:%lu:%d:\n",
787 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MAX_CACHE_TTL_SSH
);
788 printf ("enforce-passphrase-constraints:%lu:\n",
789 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
790 printf ("min-passphrase-len:%lu:%d:\n",
791 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MIN_PASSPHRASE_LEN
);
792 printf ("min-passphrase-nonalpha:%lu:%d:\n",
793 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
794 MIN_PASSPHRASE_NONALPHA
);
795 printf ("check-passphrase-pattern:%lu:\n",
796 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
);
797 printf ("max-passphrase-days:%lu:%d:\n",
798 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
799 MAX_PASSPHRASE_DAYS
);
800 printf ("enable-passphrase-history:%lu:\n",
801 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
802 printf ("no-grab:%lu:\n",
803 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
804 printf ("ignore-cache-for-signing:%lu:\n",
805 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
806 printf ("allow-mark-trusted:%lu:\n",
807 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
808 printf ("disable-scdaemon:%lu:\n",
809 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
814 /* If this has been called without any options, we merely check
815 whether an agent is already running. We do this here so that we
816 don't clobber a logfile but print it directly to stderr. */
817 if (!pipe_server
&& !is_daemon
)
819 log_set_prefix (NULL
, JNLIB_LOG_WITH_PREFIX
);
820 check_for_running_agent (0, 0);
825 /* gpg-agent usually does not output any messages because it runs in
826 the background. For log files it is acceptable to have messages
827 always encoded in utf-8. We switch here to utf-8, so that
828 commands like --help still give native messages. It is far
829 easier to switch only once instead of for every message and it
830 actually helps when more then one thread is active (avoids an
832 bind_textdomain_codeset (PACKAGE_GT
, "UTF-8");
835 /* Now start with logging to a file if this is desired. */
838 log_set_file (logfile
);
839 log_set_prefix (NULL
, (JNLIB_LOG_WITH_PREFIX
841 |JNLIB_LOG_WITH_PID
));
842 current_logfile
= xstrdup (logfile
);
845 /* Make sure that we have a default ttyname. */
846 if (!default_ttyname
&& ttyname (1))
847 default_ttyname
= xstrdup (ttyname (1));
848 if (!default_ttytype
&& getenv ("TERM"))
849 default_ttytype
= xstrdup (getenv ("TERM"));
854 /* This is the simple pipe based server */
857 ctrl
= xtrycalloc (1, sizeof *ctrl
);
860 log_error ("error allocating connection control data: %s\n",
864 agent_init_default_ctrl (ctrl
);
865 start_command_handler (ctrl
, GNUPG_INVALID_FD
, GNUPG_INVALID_FD
);
866 agent_deinit_default_ctrl (ctrl
);
872 { /* Regular server mode */
877 /* Remove the DISPLAY variable so that a pinentry does not
878 default to a specific display. There is still a default
879 display when gpg-agent was started using --display or a
880 client requested this using an OPTION command. Note, that we
881 don't do this when running in reverse daemon mode (i.e. when
882 exec the program given as arguments). */
883 #ifndef HAVE_W32_SYSTEM
884 if (!opt
.keep_display
&& !argc
)
885 unsetenv ("DISPLAY");
889 /* Create the sockets. */
890 socket_name
= create_socket_name (use_standard_socket
,
892 "/tmp/gpg-XXXXXX/S.gpg-agent");
894 socket_name_ssh
= create_socket_name (use_standard_socket
,
896 "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
898 fd
= create_server_socket (use_standard_socket
, socket_name
, 0,
901 fd_ssh
= create_server_socket (use_standard_socket
, socket_name_ssh
, 1,
904 fd_ssh
= GNUPG_INVALID_FD
;
906 /* If we are going to exec a program in the parent, we record
907 the PID, so that the child may check whether the program is
910 parent_pid
= getpid ();
913 #ifdef HAVE_W32_SYSTEM
915 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name
, (ulong
)pid
);
916 #else /*!HAVE_W32_SYSTEM*/
918 if (pid
== (pid_t
)-1)
920 log_fatal ("fork failed: %s\n", strerror (errno
) );
924 { /* We are the parent */
925 char *infostr
, *infostr_ssh_sock
, *infostr_ssh_pid
;
929 /* Create the info string: <name>:<pid>:<protocol_version> */
930 if (asprintf (&infostr
, "GPG_AGENT_INFO=%s:%lu:1",
931 socket_name
, (ulong
)pid
) < 0)
933 log_error ("out of core\n");
939 if (asprintf (&infostr_ssh_sock
, "SSH_AUTH_SOCK=%s",
940 socket_name_ssh
) < 0)
942 log_error ("out of core\n");
946 if (asprintf (&infostr_ssh_pid
, "SSH_AGENT_PID=%u",
949 log_error ("out of core\n");
955 *socket_name
= 0; /* Don't let cleanup() remove the socket -
956 the child should do this from now on */
958 *socket_name_ssh
= 0;
964 fp
= fopen (env_file_name
, "w");
966 log_error (_("error creating `%s': %s\n"),
967 env_file_name
, strerror (errno
));
974 fputs (infostr_ssh_sock
, fp
);
976 fputs (infostr_ssh_pid
, fp
);
985 { /* Run the program given on the commandline. */
986 if (putenv (infostr
))
988 log_error ("failed to set environment: %s\n",
990 kill (pid
, SIGTERM
);
993 if (opt
.ssh_support
&& putenv (infostr_ssh_sock
))
995 log_error ("failed to set environment: %s\n",
997 kill (pid
, SIGTERM
);
1000 if (opt
.ssh_support
&& putenv (infostr_ssh_pid
))
1002 log_error ("failed to set environment: %s\n",
1004 kill (pid
, SIGTERM
);
1007 execvp (argv
[0], argv
);
1008 log_error ("failed to run the command: %s\n", strerror (errno
));
1009 kill (pid
, SIGTERM
);
1014 /* Print the environment string, so that the caller can use
1015 shell's eval to set it */
1018 *strchr (infostr
, '=') = ' ';
1019 printf ("setenv %s\n", infostr
);
1020 if (opt
.ssh_support
)
1022 *strchr (infostr_ssh_sock
, '=') = ' ';
1023 printf ("setenv %s\n", infostr_ssh_sock
);
1024 *strchr (infostr_ssh_pid
, '=') = ' ';
1025 printf ("setenv %s\n", infostr_ssh_pid
);
1030 printf ( "%s; export GPG_AGENT_INFO;\n", infostr
);
1031 if (opt
.ssh_support
)
1033 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock
);
1034 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid
);
1037 free (infostr
); /* (Note that a vanilla free is here correct.) */
1038 if (opt
.ssh_support
)
1040 free (infostr_ssh_sock
);
1041 free (infostr_ssh_pid
);
1052 /* Detach from tty and put process into a new session */
1056 unsigned int oldflags
;
1058 /* Close stdin, stdout and stderr unless it is the log stream */
1059 for (i
=0; i
<= 2; i
++)
1061 if (!log_test_fd (i
) && i
!= fd
)
1064 && open ("/dev/null", i
? O_WRONLY
: O_RDONLY
) == -1)
1066 log_error ("failed to open `%s': %s\n",
1067 "/dev/null", strerror (errno
));
1075 log_error ("setsid() failed: %s\n", strerror(errno
) );
1080 log_get_prefix (&oldflags
);
1081 log_set_prefix (NULL
, oldflags
| JNLIB_LOG_RUN_DETACHED
);
1082 opt
.running_detached
= 1;
1087 log_error ("chdir to / failed: %s\n", strerror (errno
));
1092 struct sigaction sa
;
1094 sa
.sa_handler
= SIG_IGN
;
1095 sigemptyset (&sa
.sa_mask
);
1097 sigaction (SIGPIPE
, &sa
, NULL
);
1099 #endif /*!HAVE_W32_SYSTEM*/
1101 handle_connections (fd
, opt
.ssh_support
? fd_ssh
: GNUPG_INVALID_FD
);
1102 assuan_sock_close (fd
);
1112 /*FIXME: update_random_seed_file();*/
1114 /* at this time a bit annoying */
1115 if (opt
.debug
& DBG_MEMSTAT_VALUE
)
1117 gcry_control( GCRYCTL_DUMP_MEMORY_STATS
);
1118 gcry_control( GCRYCTL_DUMP_RANDOM_STATS
);
1121 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
1123 gcry_control (GCRYCTL_TERM_SECMEM
);
1124 rc
= rc
? rc
: log_get_errorcount(0)? 2 : 0;
1129 agent_init_default_ctrl (ctrl_t ctrl
)
1131 /* Note we ignore malloc errors because we can't do much about it
1132 and the request will fail anyway shortly after this
1135 free (ctrl
->display
);
1136 ctrl
->display
= default_display
? strdup (default_display
) : NULL
;
1139 free (ctrl
->ttyname
);
1140 ctrl
->ttyname
= default_ttyname
? strdup (default_ttyname
) : NULL
;
1143 free (ctrl
->ttytype
);
1144 ctrl
->ttytype
= default_ttytype
? strdup (default_ttytype
) : NULL
;
1147 free (ctrl
->lc_ctype
);
1148 ctrl
->lc_ctype
= default_lc_ctype
? strdup (default_lc_ctype
) : NULL
;
1150 if (ctrl
->lc_messages
)
1151 free (ctrl
->lc_messages
);
1152 ctrl
->lc_messages
= default_lc_messages
? strdup (default_lc_messages
) : NULL
;
1154 if (ctrl
->xauthority
)
1155 free (ctrl
->xauthority
);
1156 ctrl
->xauthority
= default_xauthority
? strdup (default_xauthority
) : NULL
;
1158 if (ctrl
->pinentry_user_data
)
1159 free (ctrl
->pinentry_user_data
);
1160 ctrl
->pinentry_user_data
= NULL
;
1165 agent_deinit_default_ctrl (ctrl_t ctrl
)
1168 free (ctrl
->display
);
1170 free (ctrl
->ttyname
);
1172 free (ctrl
->ttytype
);
1174 free (ctrl
->lc_ctype
);
1175 if (ctrl
->lc_messages
)
1176 free (ctrl
->lc_messages
);
1177 if (ctrl
->xauthority
)
1178 free (ctrl
->xauthority
);
1179 if (ctrl
->pinentry_user_data
)
1180 free (ctrl
->pinentry_user_data
);
1183 /* Reread parts of the configuration. Note, that this function is
1184 obviously not thread-safe and should only be called from the PTH
1187 Fixme: Due to the way the argument parsing works, we create a
1188 memory leak here for all string type arguments. There is currently
1189 no clean way to tell whether the memory for the argument has been
1190 allocated or points into the process' original arguments. Unless
1191 we have a mechanism to tell this, we need to live on with this. */
1193 reread_configuration (void)
1195 ARGPARSE_ARGS pargs
;
1197 unsigned int configlineno
= 0;
1200 if (!config_filename
)
1201 return; /* No config file. */
1203 fp
= fopen (config_filename
, "r");
1206 log_error (_("option file `%s': %s\n"),
1207 config_filename
, strerror(errno
) );
1211 parse_rereadable_options (NULL
, 1); /* Start from the default values. */
1213 memset (&pargs
, 0, sizeof pargs
);
1215 pargs
.argc
= &dummy
;
1216 pargs
.flags
= 1; /* do not remove the args */
1217 while (optfile_parse (fp
, config_filename
, &configlineno
, &pargs
, opts
) )
1219 if (pargs
.r_opt
< -1)
1220 pargs
.err
= 1; /* Print a warning. */
1221 else /* Try to parse this option - ignore unchangeable ones. */
1222 parse_rereadable_options (&pargs
, 1);
1229 /* Return the file name of the socket we are using for native
1232 get_agent_socket_name (void)
1234 const char *s
= socket_name
;
1236 return (s
&& *s
)? s
: NULL
;
1239 /* Return the file name of the socket we are using for SSH
1242 get_agent_ssh_socket_name (void)
1244 const char *s
= socket_name_ssh
;
1246 return (s
&& *s
)? s
: NULL
;
1250 /* Under W32, this function returns the handle of the scdaemon
1251 notification event. Calling it the first time creates that
1253 #ifdef HAVE_W32_SYSTEM
1255 get_agent_scd_notify_event (void)
1257 static HANDLE the_event
;
1261 SECURITY_ATTRIBUTES sa
= { sizeof (SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1263 the_event
= CreateEvent ( &sa
, FALSE
, FALSE
, NULL
);
1265 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1269 #endif /*HAVE_W32_SYSTEM*/
1273 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1274 true using STANDARD_NAME in the home directory or if given as
1275 false from the mkdir type name TEMPLATE. In the latter case a
1276 unique name in a unique new directory will be created. In both
1277 cases check for valid characters as well as against a maximum
1278 allowed length for a unix domain socket is done. The function
1279 terminates the process in case of an error. Returns: Pointer to an
1280 allocated string with the absolute name of the socket used. */
1282 create_socket_name (int use_standard_socket
,
1283 char *standard_name
, char *template)
1287 if (use_standard_socket
)
1288 name
= make_filename (opt
.homedir
, standard_name
, NULL
);
1291 name
= xstrdup (template);
1292 p
= strrchr (name
, '/');
1296 if (!mkdtemp (name
))
1298 log_error (_("can't create directory `%s': %s\n"),
1299 name
, strerror (errno
));
1305 if (strchr (name
, PATHSEP_C
))
1307 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S
);
1310 if (strlen (name
) + 1 >= DIMof (struct sockaddr_un
, sun_path
) )
1312 log_error (_("name of socket too long\n"));
1320 /* Create a Unix domain socket with NAME. IS_STANDARD_NAME indicates
1321 whether a non-random socket is used. Returns the file descriptor
1322 or terminates the process in case of an error. Not that this
1323 function needs to be used for the regular socket first and only then
1324 for the ssh socket. */
1326 create_server_socket (int is_standard_name
, char *name
, int is_ssh
,
1327 assuan_sock_nonce_t
*nonce
)
1329 struct sockaddr_un
*serv_addr
;
1334 fd
= assuan_sock_new (AF_UNIX
, SOCK_STREAM
, 0);
1335 if (fd
== ASSUAN_INVALID_FD
)
1337 log_error (_("can't create socket: %s\n"), strerror (errno
));
1341 serv_addr
= xmalloc (sizeof (*serv_addr
));
1342 memset (serv_addr
, 0, sizeof *serv_addr
);
1343 serv_addr
->sun_family
= AF_UNIX
;
1344 if (strlen (name
) + 1 >= sizeof (serv_addr
->sun_path
))
1346 log_error (_("socket name `%s' is too long\n"), name
);
1349 strcpy (serv_addr
->sun_path
, name
);
1350 len
= (offsetof (struct sockaddr_un
, sun_path
)
1351 + strlen (serv_addr
->sun_path
) + 1);
1353 rc
= assuan_sock_bind (fd
, (struct sockaddr
*) serv_addr
, len
);
1354 if (is_standard_name
&& rc
== -1 && errno
== EADDRINUSE
)
1356 /* Check whether a gpg-agent is already running on the standard
1357 socket. We do this test only if this is not the ssh socket.
1358 For ssh we assume that a test for gpg-agent has already been
1359 done and reuse the requested ssh socket. Testing the
1360 ssh-socket is not possible because at this point, though we
1361 know the new Assuan socket, the Assuan server and thus the
1362 ssh-agent server is not yet operational. This would lead to
1364 if (!is_ssh
&& !check_for_running_agent (1, 1))
1366 log_error (_("a gpg-agent is already running - "
1367 "not starting a new one\n"));
1368 *name
= 0; /* Inhibit removal of the socket by cleanup(). */
1369 assuan_sock_close (fd
);
1373 rc
= assuan_sock_bind (fd
, (struct sockaddr
*) serv_addr
, len
);
1376 && (rc
=assuan_sock_get_nonce ((struct sockaddr
*)serv_addr
, len
, nonce
)))
1377 log_error (_("error getting nonce for the socket\n"));
1380 /* We use gpg_strerror here because it allows us to get strings
1381 for some W32 socket error codes. */
1382 log_error (_("error binding socket to `%s': %s\n"),
1383 serv_addr
->sun_path
,
1384 gpg_strerror (gpg_error_from_errno (errno
)));
1386 assuan_sock_close (fd
);
1387 if (is_standard_name
)
1388 *name
= 0; /* Inhibit removal of the socket by cleanup(). */
1392 if (listen (FD2INT(fd
), 5 ) == -1)
1394 log_error (_("listen() failed: %s\n"), strerror (errno
));
1395 assuan_sock_close (fd
);
1400 log_info (_("listening on socket `%s'\n"), serv_addr
->sun_path
);
1406 /* Check that the directory for storing the private keys exists and
1407 create it if not. This function won't fail as it is only a
1408 convenience function and not strictly necessary. */
1410 create_private_keys_directory (const char *home
)
1413 struct stat statbuf
;
1415 fname
= make_filename (home
, GNUPG_PRIVATE_KEYS_DIR
, NULL
);
1416 if (stat (fname
, &statbuf
) && errno
== ENOENT
)
1418 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1419 if (!CreateDirectory (fname
, NULL
))
1420 log_error (_("can't create directory `%s': %s\n"),
1421 fname
, w32_strerror (-1) );
1423 if (mkdir (fname
, S_IRUSR
|S_IWUSR
|S_IXUSR
))
1424 log_error (_("can't create directory `%s': %s\n"),
1425 fname
, strerror (errno
) );
1427 else if (!opt
.quiet
)
1428 log_info (_("directory `%s' created\n"), fname
);
1433 /* Create the directory only if the supplied directory name is the
1434 same as the default one. This way we avoid to create arbitrary
1435 directories when a non-default home directory is used. To cope
1436 with HOME, we compare only the suffix if we see that the default
1437 homedir does start with a tilde. We don't stop here in case of
1438 problems because other functions will throw an error anyway.*/
1440 create_directories (void)
1442 struct stat statbuf
;
1443 const char *defhome
= standard_homedir ();
1446 home
= make_filename (opt
.homedir
, NULL
);
1447 if ( stat (home
, &statbuf
) )
1449 if (errno
== ENOENT
)
1452 #ifdef HAVE_W32_SYSTEM
1453 ( !compare_filenames (home
, defhome
) )
1456 && (strlen (home
) >= strlen (defhome
+1)
1457 && !strcmp (home
+ strlen(home
)
1458 - strlen (defhome
+1), defhome
+1)))
1459 || (*defhome
!= '~' && !strcmp (home
, defhome
) )
1463 #ifdef HAVE_W32_SYSTEM
1464 if (!CreateDirectory (home
, NULL
))
1465 log_error (_("can't create directory `%s': %s\n"),
1466 home
, w32_strerror (-1) );
1468 if (mkdir (home
, S_IRUSR
|S_IWUSR
|S_IXUSR
))
1469 log_error (_("can't create directory `%s': %s\n"),
1470 home
, strerror (errno
) );
1475 log_info (_("directory `%s' created\n"), home
);
1476 create_private_keys_directory (home
);
1481 log_error (_("stat() failed for `%s': %s\n"), home
, strerror (errno
));
1483 else if ( !S_ISDIR(statbuf
.st_mode
))
1485 log_error (_("can't use `%s' as home directory\n"), home
);
1487 else /* exists and is a directory. */
1489 create_private_keys_directory (home
);
1496 /* This is the worker for the ticker. It is called every few seconds
1497 and may only do fast operations. */
1501 /* Check whether the scdaemon has died and cleanup in this case. */
1502 agent_scd_check_aliveness ();
1504 /* If we are running as a child of another process, check whether
1505 the parent is still alive and shutdown if not. */
1506 #ifndef HAVE_W32_SYSTEM
1507 if (parent_pid
!= (pid_t
)(-1))
1509 if (kill (parent_pid
, 0))
1511 shutdown_pending
= 2;
1512 log_info ("parent process died - shutting down\n");
1513 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1518 #endif /*HAVE_W32_SYSTEM*/
1522 /* A global function which allows us to call the reload stuff from
1523 other places too. This is only used when build for W32. */
1525 agent_sighup_action (void)
1527 log_info ("SIGHUP received - "
1528 "re-reading configuration and flushing cache\n");
1529 agent_flush_cache ();
1530 reread_configuration ();
1531 agent_reload_trustlist ();
1536 agent_sigusr2_action (void)
1539 log_info ("SIGUSR2 received - checking smartcard status\n");
1540 /* Nothing to check right now. We only increment a counter. */
1541 bump_card_eventcounter ();
1546 handle_signal (int signo
)
1550 #ifndef HAVE_W32_SYSTEM
1552 agent_sighup_action ();
1556 log_info ("SIGUSR1 received - printing internal information:\n");
1557 pth_ctrl (PTH_CTRL_DUMPSTATE
, log_get_stream ());
1558 agent_query_dump_state ();
1559 agent_scd_dump_state ();
1563 agent_sigusr2_action ();
1567 if (!shutdown_pending
)
1568 log_info ("SIGTERM received - shutting down ...\n");
1570 log_info ("SIGTERM received - still %ld running threads\n",
1571 pth_ctrl( PTH_CTRL_GETTHREADS
));
1573 if (shutdown_pending
> 2)
1575 log_info ("shutdown forced\n");
1576 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1583 log_info ("SIGINT received - immediate shutdown\n");
1584 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1590 log_info ("signal %d received - no action defined\n", signo
);
1595 /* Check the nonce on a new connection. This is a NOP unless we we
1596 are using our Unix domain socket emulation under Windows. */
1598 check_nonce (ctrl_t ctrl
, assuan_sock_nonce_t
*nonce
)
1600 if (assuan_sock_check_nonce (ctrl
->thread_startup
.fd
, nonce
))
1602 log_info (_("error reading nonce on fd %d: %s\n"),
1603 FD2INT(ctrl
->thread_startup
.fd
), strerror (errno
));
1604 assuan_sock_close (ctrl
->thread_startup
.fd
);
1613 /* This is the standard connection thread's main function. */
1615 start_connection_thread (void *arg
)
1619 if (check_nonce (ctrl
, &socket_nonce
))
1622 agent_init_default_ctrl (ctrl
);
1624 log_info (_("handler 0x%lx for fd %d started\n"),
1625 (long)pth_self (), FD2INT(ctrl
->thread_startup
.fd
));
1627 start_command_handler (ctrl
, GNUPG_INVALID_FD
, ctrl
->thread_startup
.fd
);
1629 log_info (_("handler 0x%lx for fd %d terminated\n"),
1630 (long)pth_self (), FD2INT(ctrl
->thread_startup
.fd
));
1632 agent_deinit_default_ctrl (ctrl
);
1638 /* This is the ssh connection thread's main function. */
1640 start_connection_thread_ssh (void *arg
)
1644 if (check_nonce (ctrl
, &socket_nonce_ssh
))
1647 agent_init_default_ctrl (ctrl
);
1649 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1650 (long)pth_self (), FD2INT(ctrl
->thread_startup
.fd
));
1652 start_command_handler_ssh (ctrl
, ctrl
->thread_startup
.fd
);
1654 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1655 (long)pth_self (), FD2INT(ctrl
->thread_startup
.fd
));
1657 agent_deinit_default_ctrl (ctrl
);
1663 /* Connection handler loop. Wait for connection requests and spawn a
1664 thread after accepting a connection. */
1666 handle_connections (gnupg_fd_t listen_fd
, gnupg_fd_t listen_fd_ssh
)
1669 pth_event_t ev
, time_ev
;
1672 struct sockaddr_un paddr
;
1674 fd_set fdset
, read_fdset
;
1679 tattr
= pth_attr_new();
1680 pth_attr_set (tattr
, PTH_ATTR_JOINABLE
, 0);
1681 pth_attr_set (tattr
, PTH_ATTR_STACK_SIZE
, 256*1024);
1683 #ifndef HAVE_W32_SYSTEM /* fixme */
1684 /* Make sure that the signals we are going to handle are not blocked
1685 and create an event object for them. */
1686 sigemptyset (&sigs
);
1687 sigaddset (&sigs
, SIGHUP
);
1688 sigaddset (&sigs
, SIGUSR1
);
1689 sigaddset (&sigs
, SIGUSR2
);
1690 sigaddset (&sigs
, SIGINT
);
1691 sigaddset (&sigs
, SIGTERM
);
1692 pth_sigmask (SIG_UNBLOCK
, &sigs
, NULL
);
1693 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1695 # ifdef PTH_EVENT_HANDLE
1697 ev
= pth_event (PTH_EVENT_HANDLE
, get_agent_scd_notify_event ());
1700 /* Use a dummy event. */
1702 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1708 FD_SET (FD2INT (listen_fd
), &fdset
);
1709 nfd
= FD2INT (listen_fd
);
1710 if (listen_fd_ssh
!= GNUPG_INVALID_FD
)
1712 FD_SET ( FD2INT(listen_fd_ssh
), &fdset
);
1713 if (FD2INT (listen_fd_ssh
) > nfd
)
1714 nfd
= FD2INT (listen_fd_ssh
);
1721 if (shutdown_pending
)
1723 if (pth_ctrl (PTH_CTRL_GETTHREADS
) == 1)
1726 /* Do not accept anymore connections and wait for existing
1727 connections to terminate */
1730 if (pth_event_occurred (ev
) && signo
)
1731 handle_signal (signo
);
1735 /* Create a timeout event if needed. */
1737 time_ev
= pth_event (PTH_EVENT_TIME
,
1738 pth_timeout (TIMERTICK_INTERVAL
, 0));
1740 /* POSIX says that fd_set should be implemented as a structure,
1741 thus a simple assignment is fine to copy the entire set. */
1745 pth_event_concat (ev
, time_ev
, NULL
);
1746 ret
= pth_select_ev (nfd
+1, &read_fdset
, NULL
, NULL
, NULL
, ev
);
1748 pth_event_isolate (time_ev
);
1752 if (pth_event_occurred (ev
)
1753 || (time_ev
&& pth_event_occurred (time_ev
)))
1755 if (pth_event_occurred (ev
))
1757 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1758 agent_sigusr2_action ();
1760 handle_signal (signo
);
1763 if (time_ev
&& pth_event_occurred (time_ev
))
1765 pth_event_free (time_ev
, PTH_FREE_ALL
);
1771 log_error (_("pth_select failed: %s - waiting 1s\n"),
1777 if (pth_event_occurred (ev
))
1779 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1780 agent_sigusr2_action ();
1782 handle_signal (signo
);
1786 if (time_ev
&& pth_event_occurred (time_ev
))
1788 pth_event_free (time_ev
, PTH_FREE_ALL
);
1794 /* We now might create new threads and because we don't want any
1795 signals (as we are handling them here) to be delivered to a
1796 new thread. Thus we need to block those signals. */
1797 pth_sigmask (SIG_BLOCK
, &sigs
, &oldsigs
);
1799 if (FD_ISSET (FD2INT (listen_fd
), &read_fdset
))
1803 plen
= sizeof paddr
;
1804 fd
= INT2FD (pth_accept (FD2INT(listen_fd
),
1805 (struct sockaddr
*)&paddr
, &plen
));
1806 if (fd
== GNUPG_INVALID_FD
)
1808 log_error ("accept failed: %s\n", strerror (errno
));
1810 else if ( !(ctrl
= xtrycalloc (1, sizeof *ctrl
)) )
1812 log_error ("error allocating connection control data: %s\n",
1814 assuan_sock_close (fd
);
1818 char threadname
[50];
1820 snprintf (threadname
, sizeof threadname
-1,
1821 "conn fd=%d (gpg)", FD2INT(fd
));
1822 threadname
[sizeof threadname
-1] = 0;
1823 pth_attr_set (tattr
, PTH_ATTR_NAME
, threadname
);
1824 ctrl
->thread_startup
.fd
= fd
;
1825 if (!pth_spawn (tattr
, start_connection_thread
, ctrl
))
1827 log_error ("error spawning connection handler: %s\n",
1829 assuan_sock_close (fd
);
1833 fd
= GNUPG_INVALID_FD
;
1836 if (listen_fd_ssh
!= GNUPG_INVALID_FD
1837 && FD_ISSET ( FD2INT (listen_fd_ssh
), &read_fdset
))
1841 plen
= sizeof paddr
;
1842 fd
= INT2FD(pth_accept (FD2INT(listen_fd_ssh
),
1843 (struct sockaddr
*)&paddr
, &plen
));
1844 if (fd
== GNUPG_INVALID_FD
)
1846 log_error ("accept failed for ssh: %s\n", strerror (errno
));
1848 else if ( !(ctrl
= xtrycalloc (1, sizeof *ctrl
)) )
1850 log_error ("error allocating connection control data: %s\n",
1852 assuan_sock_close (fd
);
1856 char threadname
[50];
1858 agent_init_default_ctrl (ctrl
);
1859 snprintf (threadname
, sizeof threadname
-1,
1860 "conn fd=%d (ssh)", FD2INT(fd
));
1861 threadname
[sizeof threadname
-1] = 0;
1862 pth_attr_set (tattr
, PTH_ATTR_NAME
, threadname
);
1863 ctrl
->thread_startup
.fd
= fd
;
1864 if (!pth_spawn (tattr
, start_connection_thread_ssh
, ctrl
) )
1866 log_error ("error spawning ssh connection handler: %s\n",
1868 assuan_sock_close (fd
);
1872 fd
= GNUPG_INVALID_FD
;
1875 /* Restore the signal mask. */
1876 pth_sigmask (SIG_SETMASK
, &oldsigs
, NULL
);
1880 pth_event_free (ev
, PTH_FREE_ALL
);
1882 pth_event_free (time_ev
, PTH_FREE_ALL
);
1884 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
1888 /* Figure out whether an agent is available and running. Prints an
1889 error if not. If SILENT is true, no messages are printed. Usually
1890 started with MODE 0. Returns 0 if the agent is running. */
1892 check_for_running_agent (int silent
, int mode
)
1896 assuan_context_t ctx
;
1901 infostr
= getenv ("GPG_AGENT_INFO");
1902 if (!infostr
|| !*infostr
)
1904 if (!check_for_running_agent (silent
, 1))
1905 return 0; /* Okay, its running on the standard socket. */
1907 log_error (_("no gpg-agent running in this session\n"));
1911 infostr
= xstrdup (infostr
);
1912 if ( !(p
= strchr (infostr
, PATHSEP_C
)) || p
== infostr
)
1915 if (!check_for_running_agent (silent
, 1))
1916 return 0; /* Okay, its running on the standard socket. */
1918 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
1924 while (*p
&& *p
!= PATHSEP_C
)
1926 prot
= *p
? atoi (p
+1) : 0;
1931 log_error (_("gpg-agent protocol version %d is not supported\n"),
1933 if (!check_for_running_agent (silent
, 1))
1934 return 0; /* Okay, its running on the standard socket. */
1938 else /* MODE != 0 */
1940 infostr
= make_filename (opt
.homedir
, "S.gpg-agent", NULL
);
1945 rc
= assuan_socket_connect (&ctx
, infostr
, pid
);
1949 if (!mode
&& !check_for_running_agent (silent
, 1))
1950 return 0; /* Okay, its running on the standard socket. */
1952 if (!mode
&& !silent
)
1953 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc
));
1957 if (!opt
.quiet
&& !silent
)
1958 log_info ("gpg-agent running and available\n");
1960 assuan_disconnect (ctx
);