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
42 #define JNLIB_NEED_AFLOCAL
44 #include <assuan.h> /* Malloc hooks and socket wrappers. */
47 #include "mkdtemp.h" /* Gnulib replacement. */
50 #include "gc-opt-flags.h"
54 enum cmd_and_opt_values
92 oEnforcePassphraseConstraints
,
94 oMinPassphraseNonalpha
,
95 oCheckPassphrasePattern
,
97 oEnablePassphraseHistory
,
102 oIgnoreCacheForSigning
,
104 oAllowPresetPassphrase
,
114 static ARGPARSE_OPTS opts
[] = {
116 { aGPGConfList
, "gpgconf-list", 256, "@" },
117 { aGPGConfTest
, "gpgconf-test", 256, "@" },
119 { 301, NULL
, 0, N_("@Options:\n ") },
121 { oServer
, "server", 0, N_("run in server mode (foreground)") },
122 { oDaemon
, "daemon", 0, N_("run in daemon mode (background)") },
123 { oVerbose
, "verbose", 0, N_("verbose") },
124 { oQuiet
, "quiet", 0, N_("be somewhat more quiet") },
125 { oSh
, "sh", 0, N_("sh-style command output") },
126 { oCsh
, "csh", 0, N_("csh-style command output") },
127 { oOptions
, "options" , 2, N_("|FILE|read options from FILE")},
128 { oDebug
, "debug" ,4|16, "@"},
129 { oDebugAll
, "debug-all" ,0, "@"},
130 { oDebugLevel
, "debug-level" ,2, "@"},
131 { oDebugWait
,"debug-wait",1, "@"},
132 { oNoDetach
, "no-detach" ,0, N_("do not detach from the console")},
133 { oNoGrab
, "no-grab" ,0, N_("do not grab keyboard and mouse")},
134 { oLogFile
, "log-file" ,2, N_("use a log file for the server")},
135 { oUseStandardSocket
, "use-standard-socket", 0,
136 N_("use a standard location for the socket")},
137 { oNoUseStandardSocket
, "no-use-standard-socket", 0, "@"},
138 { oPinentryProgram
, "pinentry-program", 2 ,
139 N_("|PGM|use PGM as the PIN-Entry program") },
140 { oPinentryTouchFile
, "pinentry-touch-file", 2 , "@" },
141 { oScdaemonProgram
, "scdaemon-program", 2 ,
142 N_("|PGM|use PGM as the SCdaemon program") },
143 { oDisableScdaemon
, "disable-scdaemon", 0, N_("do not use the SCdaemon") },
144 { oFakedSystemTime
, "faked-system-time", 2, "@" }, /* (epoch time) */
146 { oBatch
, "batch", 0, "@" },
147 { oHomedir
, "homedir", 2, "@"},
149 { oDisplay
, "display", 2, "@" },
150 { oTTYname
, "ttyname", 2, "@" },
151 { oTTYtype
, "ttytype", 2, "@" },
152 { oLCctype
, "lc-ctype", 2, "@" },
153 { oLCmessages
, "lc-messages", 2, "@" },
154 { oXauthority
, "xauthority", 2, "@" },
155 { oKeepTTY
, "keep-tty", 0, N_("ignore requests to change the TTY")},
156 { oKeepDISPLAY
, "keep-display",
157 0, N_("ignore requests to change the X display")},
159 { oDefCacheTTL
, "default-cache-ttl", 4,
160 N_("|N|expire cached PINs after N seconds")},
161 { oDefCacheTTLSSH
, "default-cache-ttl-ssh", 4, "@" },
162 { oMaxCacheTTL
, "max-cache-ttl", 4, "@" },
163 { oMaxCacheTTLSSH
, "max-cache-ttl-ssh", 4, "@" },
165 { oEnforcePassphraseConstraints
, "enforce-passphrase-constraints", 0, "@"},
166 { oMinPassphraseLen
, "min-passphrase-len", 4, "@" },
167 { oMinPassphraseNonalpha
, "min-passphrase-nonalpha", 4, "@" },
168 { oCheckPassphrasePattern
, "check-passphrase-pattern", 2, "@" },
169 { oMaxPassphraseDays
, "max-passphrase-days", 4, "@" },
170 { oEnablePassphraseHistory
, "enable-passphrase-history", 0, "@" },
172 { oIgnoreCacheForSigning
, "ignore-cache-for-signing", 0,
173 N_("do not use the PIN cache when signing")},
174 { oAllowMarkTrusted
, "allow-mark-trusted", 0,
175 N_("allow clients to mark keys as \"trusted\"")},
176 { oAllowPresetPassphrase
, "allow-preset-passphrase", 0,
177 N_("allow presetting passphrase")},
178 { oSSHSupport
, "enable-ssh-support", 0, N_("enable ssh-agent emulation") },
179 { oWriteEnvFile
, "write-env-file", 2|8,
180 N_("|FILE|write environment settings also to FILE")},
185 #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
186 #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
187 #define MAX_CACHE_TTL (120*60) /* 2 hours */
188 #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
189 #define MIN_PASSPHRASE_LEN (8)
190 #define MIN_PASSPHRASE_NONALPHA (1)
191 #define MAX_PASSPHRASE_DAYS (0)
193 /* The timer tick used for housekeeping stuff. For Windows we use a
194 longer period as the SetWaitableTimer seems to signal earlier than
196 #ifdef HAVE_W32_SYSTEM
197 #define TIMERTICK_INTERVAL (4)
199 #define TIMERTICK_INTERVAL (2) /* Seconds. */
203 /* The list of open file descriptors at startup. Note that this list
204 has been allocated using the standard malloc. */
205 static int *startup_fd_list
;
207 /* The signal mask at startup and a flag telling whether it is valid. */
208 #ifdef HAVE_SIGPROCMASK
209 static sigset_t startup_signal_mask
;
210 static int startup_signal_mask_valid
;
213 /* Flag to indicate that a shutdown was requested. */
214 static int shutdown_pending
;
216 /* Counter for the currently running own socket checks. */
217 static int check_own_socket_running
;
219 /* True if we are listening on the standard socket. */
220 static int use_standard_socket
;
222 /* It is possible that we are currently running under setuid permissions */
223 static int maybe_setuid
= 1;
225 /* Name of the communication socket used for native gpg-agent requests. */
226 static char *socket_name
;
228 /* Name of the communication socket used for ssh-agent-emulation. */
229 static char *socket_name_ssh
;
231 /* We need to keep track of the server's nonces (these are dummies for
233 static assuan_sock_nonce_t socket_nonce
;
234 static assuan_sock_nonce_t socket_nonce_ssh
;
237 /* Default values for options passed to the pinentry. */
238 static char *default_display
;
239 static char *default_ttyname
;
240 static char *default_ttytype
;
241 static char *default_lc_ctype
;
242 static char *default_lc_messages
;
243 static char *default_xauthority
;
245 /* Name of a config file, which will be reread on a HUP if it is not NULL. */
246 static char *config_filename
;
248 /* Helper to implement --debug-level */
249 static const char *debug_level
;
251 /* Keep track of the current log file so that we can avoid updating
252 the log file after a SIGHUP if it didn't changed. Malloced. */
253 static char *current_logfile
;
255 /* The handle_tick() function may test whether a parent is still
256 running. We record the PID of the parent here or -1 if it should be
258 static pid_t parent_pid
= (pid_t
)(-1);
265 static char *create_socket_name (char *standard_name
, char *template);
266 static gnupg_fd_t
create_server_socket (char *name
, int is_ssh
,
267 assuan_sock_nonce_t
*nonce
);
268 static void create_directories (void);
270 static void agent_init_default_ctrl (ctrl_t ctrl
);
271 static void agent_deinit_default_ctrl (ctrl_t ctrl
);
273 static void handle_connections (gnupg_fd_t listen_fd
,
274 gnupg_fd_t listen_fd_ssh
);
275 static void check_own_socket (void);
276 static int check_for_running_agent (int silent
, int mode
);
278 /* Pth wrapper function definitions. */
279 GCRY_THREAD_OPTION_PTH_IMPL
;
280 static int fixed_gcry_pth_init (void)
282 return pth_self ()? 0 : (pth_init () == FALSE
) ? errno
: 0;
286 #ifndef PTH_HAVE_PTH_THREAD_ID
287 static unsigned long pth_thread_id (void)
289 return (unsigned long)pth_self ();
300 make_libversion (const char *libname
, const char *(*getfnc
)(const char*))
307 gcry_control (GCRYCTL_INIT_SECMEM
, 0, 0); /* Drop setuid. */
311 result
= xmalloc (strlen (libname
) + 1 + strlen (s
) + 1);
312 strcpy (stpcpy (stpcpy (result
, libname
), " "), s
);
318 my_strusage (int level
)
320 static char *ver_gcry
;
325 case 11: p
= "gpg-agent (GnuPG)";
327 case 13: p
= VERSION
; break;
328 case 17: p
= PRINTABLE_OS_NAME
; break;
329 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
330 reporting address. This is so that we can change the
331 reporting address without breaking the translations. */
332 case 19: p
= _("Please report bugs to <@EMAIL@>.\n"); break;
336 ver_gcry
= make_libversion ("libgcrypt", gcry_check_version
);
341 case 40: p
= _("Usage: gpg-agent [options] (-h for help)");
343 case 41: p
= _("Syntax: gpg-agent [options] [command [args]]\n"
344 "Secret key management for GnuPG\n");
354 /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
355 only the active debug flags are propagated to the subsystems. With
356 DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
357 all flags already set. Note that we don't fail here, because it is
358 important to keep gpg-agent running even after re-reading the
359 options due to a SIGHUP. */
365 else if (!strcmp (debug_level
, "none"))
367 else if (!strcmp (debug_level
, "basic"))
368 opt
.debug
= DBG_ASSUAN_VALUE
;
369 else if (!strcmp (debug_level
, "advanced"))
370 opt
.debug
= DBG_ASSUAN_VALUE
|DBG_COMMAND_VALUE
;
371 else if (!strcmp (debug_level
, "expert"))
372 opt
.debug
= (DBG_ASSUAN_VALUE
|DBG_COMMAND_VALUE
374 else if (!strcmp (debug_level
, "guru"))
378 log_error (_("invalid debug-level `%s' given\n"), debug_level
);
379 opt
.debug
= 0; /* Reset debugging, so that prior debug
380 statements won't have an undesired effect. */
383 if (opt
.debug
&& !opt
.verbose
)
385 if (opt
.debug
&& opt
.quiet
)
388 if (opt
.debug
& DBG_MPI_VALUE
)
389 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 2);
390 if (opt
.debug
& DBG_CRYPTO_VALUE
)
391 gcry_control (GCRYCTL_SET_DEBUG_FLAGS
, 1);
392 gcry_control (GCRYCTL_SET_VERBOSITY
, (int)opt
.verbose
);
396 /* Helper for cleanup to remove one socket with NAME. */
398 remove_socket (char *name
)
405 p
= strrchr (name
, '/');
419 remove_socket (socket_name
);
420 remove_socket (socket_name_ssh
);
425 /* Handle options which are allowed to be reset after program start.
426 Return true when the current option in PARGS could be handled and
427 false if not. As a special feature, passing a value of NULL for
428 PARGS, resets the options to the default. REREAD should be set
429 true if it is not the initial option parsing. */
431 parse_rereadable_options (ARGPARSE_ARGS
*pargs
, int reread
)
439 opt
.pinentry_program
= NULL
;
440 opt
.pinentry_touch_file
= NULL
;
441 opt
.scdaemon_program
= NULL
;
442 opt
.def_cache_ttl
= DEFAULT_CACHE_TTL
;
443 opt
.def_cache_ttl_ssh
= DEFAULT_CACHE_TTL_SSH
;
444 opt
.max_cache_ttl
= MAX_CACHE_TTL
;
445 opt
.max_cache_ttl_ssh
= MAX_CACHE_TTL_SSH
;
446 opt
.enforce_passphrase_constraints
= 0;
447 opt
.min_passphrase_len
= MIN_PASSPHRASE_LEN
;
448 opt
.min_passphrase_nonalpha
= MIN_PASSPHRASE_NONALPHA
;
449 opt
.check_passphrase_pattern
= NULL
;
450 opt
.max_passphrase_days
= MAX_PASSPHRASE_DAYS
;
451 opt
.enable_passhrase_history
= 0;
452 opt
.ignore_cache_for_signing
= 0;
453 opt
.allow_mark_trusted
= 0;
454 opt
.disable_scdaemon
= 0;
458 switch (pargs
->r_opt
)
460 case oQuiet
: opt
.quiet
= 1; break;
461 case oVerbose
: opt
.verbose
++; break;
463 case oDebug
: opt
.debug
|= pargs
->r
.ret_ulong
; break;
464 case oDebugAll
: opt
.debug
= ~0; break;
465 case oDebugLevel
: debug_level
= pargs
->r
.ret_str
; break;
469 return 0; /* not handeld */
470 if (!current_logfile
|| !pargs
->r
.ret_str
471 || strcmp (current_logfile
, pargs
->r
.ret_str
))
473 log_set_file (pargs
->r
.ret_str
);
474 xfree (current_logfile
);
475 current_logfile
= xtrystrdup (pargs
->r
.ret_str
);
479 case oNoGrab
: opt
.no_grab
= 1; break;
481 case oPinentryProgram
: opt
.pinentry_program
= pargs
->r
.ret_str
; break;
482 case oPinentryTouchFile
: opt
.pinentry_touch_file
= pargs
->r
.ret_str
; break;
483 case oScdaemonProgram
: opt
.scdaemon_program
= pargs
->r
.ret_str
; break;
484 case oDisableScdaemon
: opt
.disable_scdaemon
= 1; break;
486 case oDefCacheTTL
: opt
.def_cache_ttl
= pargs
->r
.ret_ulong
; break;
487 case oDefCacheTTLSSH
: opt
.def_cache_ttl_ssh
= pargs
->r
.ret_ulong
; break;
488 case oMaxCacheTTL
: opt
.max_cache_ttl
= pargs
->r
.ret_ulong
; break;
489 case oMaxCacheTTLSSH
: opt
.max_cache_ttl_ssh
= pargs
->r
.ret_ulong
; break;
491 case oEnforcePassphraseConstraints
:
492 opt
.enforce_passphrase_constraints
=1;
494 case oMinPassphraseLen
: opt
.min_passphrase_len
= pargs
->r
.ret_ulong
; break;
495 case oMinPassphraseNonalpha
:
496 opt
.min_passphrase_nonalpha
= pargs
->r
.ret_ulong
;
498 case oCheckPassphrasePattern
:
499 opt
.check_passphrase_pattern
= pargs
->r
.ret_str
;
501 case oMaxPassphraseDays
:
502 opt
.max_passphrase_days
= pargs
->r
.ret_ulong
;
504 case oEnablePassphraseHistory
:
505 opt
.enable_passhrase_history
= 1;
508 case oIgnoreCacheForSigning
: opt
.ignore_cache_for_signing
= 1; break;
510 case oAllowMarkTrusted
: opt
.allow_mark_trusted
= 1; break;
512 case oAllowPresetPassphrase
: opt
.allow_preset_passphrase
= 1; break;
515 return 0; /* not handled */
518 return 1; /* handled */
522 /* The main entry point. */
524 main (int argc
, char **argv
)
530 FILE *configfp
= NULL
;
531 char *configname
= NULL
;
533 unsigned configlineno
;
535 int default_config
=1;
542 char *logfile
= NULL
;
544 int gpgconf_list
= 0;
546 const char *env_file_name
= NULL
;
547 struct assuan_malloc_hooks malloc_hooks
;
549 /* Before we do anything else we save the list of currently open
550 file descriptors and the signal mask. This info is required to
551 do the exec call properly. */
552 startup_fd_list
= get_all_open_fds ();
553 #ifdef HAVE_SIGPROCMASK
554 if (!sigprocmask (SIG_UNBLOCK
, NULL
, &startup_signal_mask
))
555 startup_signal_mask_valid
= 1;
556 #endif /*HAVE_SIGPROCMASK*/
558 /* Set program name etc. */
559 set_strusage (my_strusage
);
560 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN
);
561 /* Please note that we may running SUID(ROOT), so be very CAREFUL
562 when adding any stuff between here and the call to INIT_SECMEM()
563 somewhere after the option parsing */
564 log_set_prefix ("gpg-agent", JNLIB_LOG_WITH_PREFIX
|JNLIB_LOG_WITH_PID
);
566 /* Make sure that our subsystems are ready. */
568 init_common_subsystems ();
571 /* Libgcrypt requires us to register the threading model first.
572 Note that this will also do the pth_init. */
573 gcry_threads_pth
.init
= fixed_gcry_pth_init
;
574 err
= gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pth
);
577 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
582 /* Check that the libraries are suitable. Do it here because
583 the option parsing may need services of the library. */
584 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION
) )
586 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
587 NEED_LIBGCRYPT_VERSION
, gcry_check_version (NULL
) );
590 malloc_hooks
.malloc
= gcry_malloc
;
591 malloc_hooks
.realloc
= gcry_realloc
;
592 malloc_hooks
.free
= gcry_free
;
593 assuan_set_malloc_hooks (&malloc_hooks
);
594 assuan_set_assuan_log_prefix (log_get_prefix (NULL
));
595 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT
);
597 setup_libgcrypt_logging ();
598 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL
);
600 may_coredump
= disable_core_dumps ();
602 /* Set default options. */
603 parse_rereadable_options (NULL
, 0); /* Reset them to default values. */
604 #ifdef HAVE_W32_SYSTEM
605 use_standard_socket
= 1; /* Under Windows we always use a standard
609 shell
= getenv ("SHELL");
610 if (shell
&& strlen (shell
) >= 3 && !strcmp (shell
+strlen (shell
)-3, "csh") )
613 opt
.homedir
= default_homedir ();
615 /* Record some of the original environment strings. */
619 static const char *names
[] =
620 { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL
};
623 opt
.startup_env
= session_env_new ();
624 if (!opt
.startup_env
)
625 err
= gpg_error_from_syserror ();
626 for (idx
=0; !err
&& names
[idx
]; idx
++)
628 s
= getenv (names
[idx
]);
630 err
= session_env_setenv (opt
.startup_env
, names
[idx
], s
);
636 err
= session_env_setenv (opt
.startup_env
, "GPG_TTY", s
);
639 log_fatal ("error recording startup environment: %s\n",
642 /* Fixme: Better use the locale function here. */
643 opt
.startup_lc_ctype
= getenv ("LC_CTYPE");
644 if (opt
.startup_lc_ctype
)
645 opt
.startup_lc_ctype
= xstrdup (opt
.startup_lc_ctype
);
646 opt
.startup_lc_messages
= getenv ("LC_MESSAGES");
647 if (opt
.startup_lc_messages
)
648 opt
.startup_lc_messages
= xstrdup (opt
.startup_lc_messages
);
651 /* Check whether we have a config file on the commandline */
656 pargs
.flags
= 1|(1<<6); /* do not remove the args, ignore version */
657 while (arg_parse( &pargs
, opts
))
659 if (pargs
.r_opt
== oDebug
|| pargs
.r_opt
== oDebugAll
)
661 else if (pargs
.r_opt
== oOptions
)
662 { /* yes there is one, so we do not try the default one, but
663 read the option file when it is encountered at the
667 else if (pargs
.r_opt
== oNoOptions
)
668 default_config
= 0; /* --no-options */
669 else if (pargs
.r_opt
== oHomedir
)
670 opt
.homedir
= pargs
.r
.ret_str
;
673 /* Initialize the secure memory. */
674 gcry_control (GCRYCTL_INIT_SECMEM
, 32768, 0);
678 Now we are now working under our real uid
682 configname
= make_filename (opt
.homedir
, "gpg-agent.conf", NULL
);
688 pargs
.flags
= 1; /* do not remove the args */
693 configfp
= fopen (configname
, "r");
699 log_info (_("NOTE: no default option file `%s'\n"),
704 log_error (_("option file `%s': %s\n"),
705 configname
, strerror(errno
) );
711 if (parse_debug
&& configname
)
712 log_info (_("reading options from `%s'\n"), configname
);
716 while (optfile_parse( configfp
, configname
, &configlineno
, &pargs
, opts
) )
718 if (parse_rereadable_options (&pargs
, 0))
719 continue; /* Already handled */
722 case aGPGConfList
: gpgconf_list
= 1; break;
723 case aGPGConfTest
: gpgconf_list
= 2; break;
724 case oBatch
: opt
.batch
=1; break;
726 case oDebugWait
: debug_wait
= pargs
.r
.ret_int
; break;
729 /* config files may not be nested (silently ignore them) */
733 configname
= xstrdup(pargs
.r
.ret_str
);
737 case oNoGreeting
: nogreeting
= 1; break;
738 case oNoVerbose
: opt
.verbose
= 0; break;
739 case oNoOptions
: break; /* no-options */
740 case oHomedir
: opt
.homedir
= pargs
.r
.ret_str
; break;
741 case oNoDetach
: nodetach
= 1; break;
742 case oLogFile
: logfile
= pargs
.r
.ret_str
; break;
743 case oCsh
: csh_style
= 1; break;
744 case oSh
: csh_style
= 0; break;
745 case oServer
: pipe_server
= 1; break;
746 case oDaemon
: is_daemon
= 1; break;
748 case oDisplay
: default_display
= xstrdup (pargs
.r
.ret_str
); break;
749 case oTTYname
: default_ttyname
= xstrdup (pargs
.r
.ret_str
); break;
750 case oTTYtype
: default_ttytype
= xstrdup (pargs
.r
.ret_str
); break;
751 case oLCctype
: default_lc_ctype
= xstrdup (pargs
.r
.ret_str
); break;
752 case oLCmessages
: default_lc_messages
= xstrdup (pargs
.r
.ret_str
);
753 case oXauthority
: default_xauthority
= xstrdup (pargs
.r
.ret_str
);
756 case oUseStandardSocket
: use_standard_socket
= 1; break;
757 case oNoUseStandardSocket
: use_standard_socket
= 0; break;
759 case oFakedSystemTime
:
761 time_t faked_time
= isotime2epoch (pargs
.r
.ret_str
);
762 if (faked_time
== (time_t)(-1))
763 faked_time
= (time_t)strtoul (pargs
.r
.ret_str
, NULL
, 10);
764 gnupg_set_time (faked_time
, 0);
768 case oKeepTTY
: opt
.keep_tty
= 1; break;
769 case oKeepDISPLAY
: opt
.keep_display
= 1; break;
771 case oSSHSupport
: opt
.ssh_support
= 1; break;
774 env_file_name
= pargs
.r
.ret_str
;
776 env_file_name
= make_filename ("~/.gpg-agent-info", NULL
);
779 default : pargs
.err
= configfp
? 1:2; break;
786 /* Keep a copy of the name so that it can be read on SIGHUP. */
787 config_filename
= configname
;
793 if (log_get_errorcount(0))
800 fprintf (stderr
, "%s %s; %s\n",
801 strusage(11), strusage(13), strusage(14) );
802 fprintf (stderr
, "%s\n", strusage(15) );
804 #ifdef IS_DEVELOPMENT_VERSION
805 /* We don't want to print it here because gpg-agent is useful of its
806 own and quite matured. */
807 /*log_info ("NOTE: this is a development version!\n");*/
812 if (atexit (cleanup
))
814 log_error ("atexit failed\n");
819 initialize_module_call_pinentry ();
820 initialize_module_call_scd ();
821 initialize_module_trustlist ();
823 /* Try to create missing directories. */
824 create_directories ();
826 if (debug_wait
&& pipe_server
)
828 log_debug ("waiting for debugger - my pid is %u .....\n",
829 (unsigned int)getpid());
830 gnupg_sleep (debug_wait
);
831 log_debug ("... okay\n");
834 if (gpgconf_list
== 2)
841 /* List options and default values in the GPG Conf format. */
842 filename
= make_filename (opt
.homedir
, "gpg-agent.conf", NULL
);
843 filename_esc
= percent_escape (filename
, NULL
);
845 printf ("gpgconf-gpg-agent.conf:%lu:\"%s\n",
846 GC_OPT_FLAG_DEFAULT
, filename_esc
);
848 xfree (filename_esc
);
850 printf ("verbose:%lu:\n"
852 "debug-level:%lu:\"none:\n"
854 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
,
855 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
,
856 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
857 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
858 printf ("default-cache-ttl:%lu:%d:\n",
859 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, DEFAULT_CACHE_TTL
);
860 printf ("default-cache-ttl-ssh:%lu:%d:\n",
861 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, DEFAULT_CACHE_TTL_SSH
);
862 printf ("max-cache-ttl:%lu:%d:\n",
863 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MAX_CACHE_TTL
);
864 printf ("max-cache-ttl-ssh:%lu:%d:\n",
865 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MAX_CACHE_TTL_SSH
);
866 printf ("enforce-passphrase-constraints:%lu:\n",
867 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
868 printf ("min-passphrase-len:%lu:%d:\n",
869 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
, MIN_PASSPHRASE_LEN
);
870 printf ("min-passphrase-nonalpha:%lu:%d:\n",
871 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
872 MIN_PASSPHRASE_NONALPHA
);
873 printf ("check-passphrase-pattern:%lu:\n",
874 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
);
875 printf ("max-passphrase-days:%lu:%d:\n",
876 GC_OPT_FLAG_DEFAULT
|GC_OPT_FLAG_RUNTIME
,
877 MAX_PASSPHRASE_DAYS
);
878 printf ("enable-passphrase-history:%lu:\n",
879 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
880 printf ("no-grab:%lu:\n",
881 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
882 printf ("ignore-cache-for-signing:%lu:\n",
883 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
884 printf ("allow-mark-trusted:%lu:\n",
885 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
886 printf ("disable-scdaemon:%lu:\n",
887 GC_OPT_FLAG_NONE
|GC_OPT_FLAG_RUNTIME
);
892 /* If this has been called without any options, we merely check
893 whether an agent is already running. We do this here so that we
894 don't clobber a logfile but print it directly to stderr. */
895 if (!pipe_server
&& !is_daemon
)
897 log_set_prefix (NULL
, JNLIB_LOG_WITH_PREFIX
);
898 check_for_running_agent (0, 0);
903 /* gpg-agent usually does not output any messages because it runs in
904 the background. For log files it is acceptable to have messages
905 always encoded in utf-8. We switch here to utf-8, so that
906 commands like --help still give native messages. It is far
907 easier to switch only once instead of for every message and it
908 actually helps when more then one thread is active (avoids an
910 bind_textdomain_codeset (PACKAGE_GT
, "UTF-8");
913 /* Now start with logging to a file if this is desired. */
916 log_set_file (logfile
);
917 log_set_prefix (NULL
, (JNLIB_LOG_WITH_PREFIX
919 |JNLIB_LOG_WITH_PID
));
920 current_logfile
= xstrdup (logfile
);
923 /* Make sure that we have a default ttyname. */
924 if (!default_ttyname
&& ttyname (1))
925 default_ttyname
= xstrdup (ttyname (1));
926 if (!default_ttytype
&& getenv ("TERM"))
927 default_ttytype
= xstrdup (getenv ("TERM"));
932 /* This is the simple pipe based server */
935 ctrl
= xtrycalloc (1, sizeof *ctrl
);
938 log_error ("error allocating connection control data: %s\n",
942 ctrl
->session_env
= session_env_new ();
943 if (!ctrl
->session_env
)
945 log_error ("error allocating session environment block: %s\n",
950 agent_init_default_ctrl (ctrl
);
951 start_command_handler (ctrl
, GNUPG_INVALID_FD
, GNUPG_INVALID_FD
);
952 agent_deinit_default_ctrl (ctrl
);
958 { /* Regular server mode */
963 /* Remove the DISPLAY variable so that a pinentry does not
964 default to a specific display. There is still a default
965 display when gpg-agent was started using --display or a
966 client requested this using an OPTION command. Note, that we
967 don't do this when running in reverse daemon mode (i.e. when
968 exec the program given as arguments). */
969 #ifndef HAVE_W32_SYSTEM
970 if (!opt
.keep_display
&& !argc
)
971 unsetenv ("DISPLAY");
975 /* Create the sockets. */
976 socket_name
= create_socket_name
977 ("S.gpg-agent", "/tmp/gpg-XXXXXX/S.gpg-agent");
979 socket_name_ssh
= create_socket_name
980 ("S.gpg-agent.ssh", "/tmp/gpg-XXXXXX/S.gpg-agent.ssh");
982 fd
= create_server_socket (socket_name
, 0, &socket_nonce
);
984 fd_ssh
= create_server_socket (socket_name_ssh
, 1, &socket_nonce_ssh
);
986 fd_ssh
= GNUPG_INVALID_FD
;
988 /* If we are going to exec a program in the parent, we record
989 the PID, so that the child may check whether the program is
992 parent_pid
= getpid ();
995 #ifdef HAVE_W32_SYSTEM
997 printf ("set GPG_AGENT_INFO=%s;%lu;1\n", socket_name
, (ulong
)pid
);
998 #else /*!HAVE_W32_SYSTEM*/
1000 if (pid
== (pid_t
)-1)
1002 log_fatal ("fork failed: %s\n", strerror (errno
) );
1006 { /* We are the parent */
1007 char *infostr
, *infostr_ssh_sock
, *infostr_ssh_pid
;
1009 /* Close the socket FD. */
1012 /* Note that we used a standard fork so that Pth runs in
1013 both the parent and the child. The pth_fork would
1014 terminate Pth in the child but that is not the way we
1015 want it. Thus we use a plain fork and terminate Pth here
1016 in the parent. The pth_kill may or may not work reliable
1017 but it should not harm to call it. Because Pth fiddles
1018 with the signal mask the signal mask might not be correct
1019 right now and thus we restore it. That is not strictly
1020 necessary but some programs falsely assume a cleared
1023 log_error ("pth_kill failed in forked process\n");
1025 #ifdef HAVE_SIGPROCMASK
1026 if (startup_signal_mask_valid
)
1028 if (sigprocmask (SIG_SETMASK
, &startup_signal_mask
, NULL
))
1029 log_error ("error restoring signal mask: %s\n",
1033 log_info ("no saved signal mask\n");
1034 #endif /*HAVE_SIGPROCMASK*/
1036 /* Create the info string: <name>:<pid>:<protocol_version> */
1037 if (asprintf (&infostr
, "GPG_AGENT_INFO=%s:%lu:1",
1038 socket_name
, (ulong
)pid
) < 0)
1040 log_error ("out of core\n");
1041 kill (pid
, SIGTERM
);
1044 if (opt
.ssh_support
)
1046 if (asprintf (&infostr_ssh_sock
, "SSH_AUTH_SOCK=%s",
1047 socket_name_ssh
) < 0)
1049 log_error ("out of core\n");
1050 kill (pid
, SIGTERM
);
1053 if (asprintf (&infostr_ssh_pid
, "SSH_AGENT_PID=%u",
1056 log_error ("out of core\n");
1057 kill (pid
, SIGTERM
);
1062 *socket_name
= 0; /* Don't let cleanup() remove the socket -
1063 the child should do this from now on */
1064 if (opt
.ssh_support
)
1065 *socket_name_ssh
= 0;
1071 fp
= fopen (env_file_name
, "w");
1073 log_error (_("error creating `%s': %s\n"),
1074 env_file_name
, strerror (errno
));
1077 fputs (infostr
, fp
);
1079 if (opt
.ssh_support
)
1081 fputs (infostr_ssh_sock
, fp
);
1083 fputs (infostr_ssh_pid
, fp
);
1092 { /* Run the program given on the commandline. */
1093 if (putenv (infostr
))
1095 log_error ("failed to set environment: %s\n",
1097 kill (pid
, SIGTERM
);
1100 if (opt
.ssh_support
&& putenv (infostr_ssh_sock
))
1102 log_error ("failed to set environment: %s\n",
1104 kill (pid
, SIGTERM
);
1107 if (opt
.ssh_support
&& putenv (infostr_ssh_pid
))
1109 log_error ("failed to set environment: %s\n",
1111 kill (pid
, SIGTERM
);
1115 /* Close all the file descriptors except the standard
1116 ones and those open at startup. We explicitly don't
1117 close 0,1,2 in case something went wrong collecting
1119 close_all_fds (3, startup_fd_list
);
1121 /* Run the command. */
1122 execvp (argv
[0], argv
);
1123 log_error ("failed to run the command: %s\n", strerror (errno
));
1124 kill (pid
, SIGTERM
);
1129 /* Print the environment string, so that the caller can use
1130 shell's eval to set it */
1133 *strchr (infostr
, '=') = ' ';
1134 printf ("setenv %s\n", infostr
);
1135 if (opt
.ssh_support
)
1137 *strchr (infostr_ssh_sock
, '=') = ' ';
1138 printf ("setenv %s\n", infostr_ssh_sock
);
1139 *strchr (infostr_ssh_pid
, '=') = ' ';
1140 printf ("setenv %s\n", infostr_ssh_pid
);
1145 printf ( "%s; export GPG_AGENT_INFO;\n", infostr
);
1146 if (opt
.ssh_support
)
1148 printf ("%s; export SSH_AUTH_SOCK;\n", infostr_ssh_sock
);
1149 printf ("%s; export SSH_AGENT_PID;\n", infostr_ssh_pid
);
1153 if (opt
.ssh_support
)
1155 xfree (infostr_ssh_sock
);
1156 xfree (infostr_ssh_pid
);
1167 /* Detach from tty and put process into a new session */
1171 unsigned int oldflags
;
1173 /* Close stdin, stdout and stderr unless it is the log stream */
1174 for (i
=0; i
<= 2; i
++)
1176 if (!log_test_fd (i
) && i
!= fd
)
1179 && open ("/dev/null", i
? O_WRONLY
: O_RDONLY
) == -1)
1181 log_error ("failed to open `%s': %s\n",
1182 "/dev/null", strerror (errno
));
1190 log_error ("setsid() failed: %s\n", strerror(errno
) );
1195 log_get_prefix (&oldflags
);
1196 log_set_prefix (NULL
, oldflags
| JNLIB_LOG_RUN_DETACHED
);
1197 opt
.running_detached
= 1;
1202 log_error ("chdir to / failed: %s\n", strerror (errno
));
1207 struct sigaction sa
;
1209 sa
.sa_handler
= SIG_IGN
;
1210 sigemptyset (&sa
.sa_mask
);
1212 sigaction (SIGPIPE
, &sa
, NULL
);
1214 #endif /*!HAVE_W32_SYSTEM*/
1216 log_info ("%s %s started\n", strusage(11), strusage(13) );
1217 handle_connections (fd
, opt
.ssh_support
? fd_ssh
: GNUPG_INVALID_FD
);
1218 assuan_sock_close (fd
);
1228 /*FIXME: update_random_seed_file();*/
1230 /* at this time a bit annoying */
1231 if (opt
.debug
& DBG_MEMSTAT_VALUE
)
1233 gcry_control( GCRYCTL_DUMP_MEMORY_STATS
);
1234 gcry_control( GCRYCTL_DUMP_RANDOM_STATS
);
1237 gcry_control (GCRYCTL_DUMP_SECMEM_STATS
);
1239 gcry_control (GCRYCTL_TERM_SECMEM
);
1240 rc
= rc
? rc
: log_get_errorcount(0)? 2 : 0;
1246 agent_init_default_ctrl (ctrl_t ctrl
)
1248 /* Note we ignore malloc errors because we can't do much about it
1249 and the request will fail anyway shortly after this
1251 session_env_setenv (ctrl
->session_env
, "DISPLAY", default_display
);
1252 session_env_setenv (ctrl
->session_env
, "GPG_TTY", default_ttyname
);
1253 session_env_setenv (ctrl
->session_env
, "TERM", default_ttytype
);
1254 session_env_setenv (ctrl
->session_env
, "XAUTHORITY", default_xauthority
);
1255 session_env_setenv (ctrl
->session_env
, "PINENTRY_USER_DATA", NULL
);
1258 xfree (ctrl
->lc_ctype
);
1259 ctrl
->lc_ctype
= default_lc_ctype
? xtrystrdup (default_lc_ctype
) : NULL
;
1261 if (ctrl
->lc_messages
)
1262 xfree (ctrl
->lc_messages
);
1263 ctrl
->lc_messages
= default_lc_messages
? xtrystrdup (default_lc_messages
)
1270 agent_deinit_default_ctrl (ctrl_t ctrl
)
1272 session_env_release (ctrl
->session_env
);
1275 xfree (ctrl
->lc_ctype
);
1276 if (ctrl
->lc_messages
)
1277 xfree (ctrl
->lc_messages
);
1281 /* Reread parts of the configuration. Note, that this function is
1282 obviously not thread-safe and should only be called from the PTH
1285 Fixme: Due to the way the argument parsing works, we create a
1286 memory leak here for all string type arguments. There is currently
1287 no clean way to tell whether the memory for the argument has been
1288 allocated or points into the process' original arguments. Unless
1289 we have a mechanism to tell this, we need to live on with this. */
1291 reread_configuration (void)
1293 ARGPARSE_ARGS pargs
;
1295 unsigned int configlineno
= 0;
1298 if (!config_filename
)
1299 return; /* No config file. */
1301 fp
= fopen (config_filename
, "r");
1304 log_error (_("option file `%s': %s\n"),
1305 config_filename
, strerror(errno
) );
1309 parse_rereadable_options (NULL
, 1); /* Start from the default values. */
1311 memset (&pargs
, 0, sizeof pargs
);
1313 pargs
.argc
= &dummy
;
1314 pargs
.flags
= 1; /* do not remove the args */
1315 while (optfile_parse (fp
, config_filename
, &configlineno
, &pargs
, opts
) )
1317 if (pargs
.r_opt
< -1)
1318 pargs
.err
= 1; /* Print a warning. */
1319 else /* Try to parse this option - ignore unchangeable ones. */
1320 parse_rereadable_options (&pargs
, 1);
1327 /* Return the file name of the socket we are using for native
1330 get_agent_socket_name (void)
1332 const char *s
= socket_name
;
1334 return (s
&& *s
)? s
: NULL
;
1337 /* Return the file name of the socket we are using for SSH
1340 get_agent_ssh_socket_name (void)
1342 const char *s
= socket_name_ssh
;
1344 return (s
&& *s
)? s
: NULL
;
1348 /* Under W32, this function returns the handle of the scdaemon
1349 notification event. Calling it the first time creates that
1351 #ifdef HAVE_W32_SYSTEM
1353 get_agent_scd_notify_event (void)
1355 static HANDLE the_event
;
1360 SECURITY_ATTRIBUTES sa
= { sizeof (SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1362 /* We need to use manual reset evet object due to the way our
1363 w32-pth wait function works: If we would use an automatic
1364 reset event we are not able to figure out which handle has
1365 been signaled because at the time we single out the signaled
1366 handles using WFSO the event has already been reset due to
1368 h
= CreateEvent (&sa
, TRUE
, FALSE
, NULL
);
1370 log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
1371 else if (!DuplicateHandle (GetCurrentProcess(), h
,
1372 GetCurrentProcess(), &h2
,
1373 EVENT_MODIFY_STATE
|SYNCHRONIZE
, TRUE
, 0))
1375 log_error ("setting syncronize for scd notify event failed: %s\n",
1376 w32_strerror (-1) );
1386 log_debug ("returning notify handle %p\n", the_event
);
1389 #endif /*HAVE_W32_SYSTEM*/
1393 /* Create a name for the socket. With USE_STANDARD_SOCKET given as
1394 true using STANDARD_NAME in the home directory or if given as
1395 false from the mkdir type name TEMPLATE. In the latter case a
1396 unique name in a unique new directory will be created. In both
1397 cases check for valid characters as well as against a maximum
1398 allowed length for a unix domain socket is done. The function
1399 terminates the process in case of an error. Returns: Pointer to an
1400 allocated string with the absolute name of the socket used. */
1402 create_socket_name (char *standard_name
, char *template)
1406 if (use_standard_socket
)
1407 name
= make_filename (opt
.homedir
, standard_name
, NULL
);
1410 name
= xstrdup (template);
1411 p
= strrchr (name
, '/');
1415 if (!mkdtemp (name
))
1417 log_error (_("can't create directory `%s': %s\n"),
1418 name
, strerror (errno
));
1424 if (strchr (name
, PATHSEP_C
))
1426 log_error (("`%s' are not allowed in the socket name\n"), PATHSEP_S
);
1429 if (strlen (name
) + 1 >= DIMof (struct sockaddr_un
, sun_path
) )
1431 log_error (_("name of socket too long\n"));
1439 /* Create a Unix domain socket with NAME. Returns the file descriptor
1440 or terminates the process in case of an error. Not that this
1441 function needs to be used for the regular socket first and only
1442 then for the ssh socket. */
1444 create_server_socket (char *name
, int is_ssh
, assuan_sock_nonce_t
*nonce
)
1446 struct sockaddr_un
*serv_addr
;
1451 fd
= assuan_sock_new (AF_UNIX
, SOCK_STREAM
, 0);
1452 if (fd
== ASSUAN_INVALID_FD
)
1454 log_error (_("can't create socket: %s\n"), strerror (errno
));
1458 serv_addr
= xmalloc (sizeof (*serv_addr
));
1459 memset (serv_addr
, 0, sizeof *serv_addr
);
1460 serv_addr
->sun_family
= AF_UNIX
;
1461 if (strlen (name
) + 1 >= sizeof (serv_addr
->sun_path
))
1463 log_error (_("socket name `%s' is too long\n"), name
);
1466 strcpy (serv_addr
->sun_path
, name
);
1467 len
= SUN_LEN (serv_addr
);
1468 rc
= assuan_sock_bind (fd
, (struct sockaddr
*) serv_addr
, len
);
1469 if (use_standard_socket
&& rc
== -1 && errno
== EADDRINUSE
)
1471 /* Check whether a gpg-agent is already running on the standard
1472 socket. We do this test only if this is not the ssh socket.
1473 For ssh we assume that a test for gpg-agent has already been
1474 done and reuse the requested ssh socket. Testing the
1475 ssh-socket is not possible because at this point, though we
1476 know the new Assuan socket, the Assuan server and thus the
1477 ssh-agent server is not yet operational. This would lead to
1479 if (!is_ssh
&& !check_for_running_agent (1, 1))
1481 log_error (_("a gpg-agent is already running - "
1482 "not starting a new one\n"));
1483 *name
= 0; /* Inhibit removal of the socket by cleanup(). */
1484 assuan_sock_close (fd
);
1488 rc
= assuan_sock_bind (fd
, (struct sockaddr
*) serv_addr
, len
);
1491 && (rc
=assuan_sock_get_nonce ((struct sockaddr
*)serv_addr
, len
, nonce
)))
1492 log_error (_("error getting nonce for the socket\n"));
1495 /* We use gpg_strerror here because it allows us to get strings
1496 for some W32 socket error codes. */
1497 log_error (_("error binding socket to `%s': %s\n"),
1498 serv_addr
->sun_path
,
1499 gpg_strerror (gpg_error_from_errno (errno
)));
1501 assuan_sock_close (fd
);
1502 if (use_standard_socket
)
1503 *name
= 0; /* Inhibit removal of the socket by cleanup(). */
1507 if (listen (FD2INT(fd
), 5 ) == -1)
1509 log_error (_("listen() failed: %s\n"), strerror (errno
));
1510 assuan_sock_close (fd
);
1515 log_info (_("listening on socket `%s'\n"), serv_addr
->sun_path
);
1521 /* Check that the directory for storing the private keys exists and
1522 create it if not. This function won't fail as it is only a
1523 convenience function and not strictly necessary. */
1525 create_private_keys_directory (const char *home
)
1528 struct stat statbuf
;
1530 fname
= make_filename (home
, GNUPG_PRIVATE_KEYS_DIR
, NULL
);
1531 if (stat (fname
, &statbuf
) && errno
== ENOENT
)
1533 #ifdef HAVE_W32_SYSTEM /*FIXME: Setup proper permissions. */
1534 if (!CreateDirectory (fname
, NULL
))
1535 log_error (_("can't create directory `%s': %s\n"),
1536 fname
, w32_strerror (-1) );
1538 if (mkdir (fname
, S_IRUSR
|S_IWUSR
|S_IXUSR
))
1539 log_error (_("can't create directory `%s': %s\n"),
1540 fname
, strerror (errno
) );
1542 else if (!opt
.quiet
)
1543 log_info (_("directory `%s' created\n"), fname
);
1548 /* Create the directory only if the supplied directory name is the
1549 same as the default one. This way we avoid to create arbitrary
1550 directories when a non-default home directory is used. To cope
1551 with HOME, we compare only the suffix if we see that the default
1552 homedir does start with a tilde. We don't stop here in case of
1553 problems because other functions will throw an error anyway.*/
1555 create_directories (void)
1557 struct stat statbuf
;
1558 const char *defhome
= standard_homedir ();
1561 home
= make_filename (opt
.homedir
, NULL
);
1562 if ( stat (home
, &statbuf
) )
1564 if (errno
== ENOENT
)
1567 #ifdef HAVE_W32_SYSTEM
1568 ( !compare_filenames (home
, defhome
) )
1571 && (strlen (home
) >= strlen (defhome
+1)
1572 && !strcmp (home
+ strlen(home
)
1573 - strlen (defhome
+1), defhome
+1)))
1574 || (*defhome
!= '~' && !strcmp (home
, defhome
) )
1578 #ifdef HAVE_W32_SYSTEM
1579 if (!CreateDirectory (home
, NULL
))
1580 log_error (_("can't create directory `%s': %s\n"),
1581 home
, w32_strerror (-1) );
1583 if (mkdir (home
, S_IRUSR
|S_IWUSR
|S_IXUSR
))
1584 log_error (_("can't create directory `%s': %s\n"),
1585 home
, strerror (errno
) );
1590 log_info (_("directory `%s' created\n"), home
);
1591 create_private_keys_directory (home
);
1596 log_error (_("stat() failed for `%s': %s\n"), home
, strerror (errno
));
1598 else if ( !S_ISDIR(statbuf
.st_mode
))
1600 log_error (_("can't use `%s' as home directory\n"), home
);
1602 else /* exists and is a directory. */
1604 create_private_keys_directory (home
);
1611 /* This is the worker for the ticker. It is called every few seconds
1612 and may only do fast operations. */
1616 static time_t last_minute
;
1619 last_minute
= time (NULL
);
1621 /* Check whether the scdaemon has died and cleanup in this case. */
1622 agent_scd_check_aliveness ();
1624 /* If we are running as a child of another process, check whether
1625 the parent is still alive and shutdown if not. */
1626 #ifndef HAVE_W32_SYSTEM
1627 if (parent_pid
!= (pid_t
)(-1))
1629 if (kill (parent_pid
, 0))
1631 shutdown_pending
= 2;
1632 log_info ("parent process died - shutting down\n");
1633 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1638 #endif /*HAVE_W32_SYSTEM*/
1640 /* Code to be run every minute. */
1641 if (last_minute
+ 60 <= time (NULL
))
1643 check_own_socket ();
1644 last_minute
= time (NULL
);
1650 /* A global function which allows us to call the reload stuff from
1651 other places too. This is only used when build for W32. */
1653 agent_sighup_action (void)
1655 log_info ("SIGHUP received - "
1656 "re-reading configuration and flushing cache\n");
1657 agent_flush_cache ();
1658 reread_configuration ();
1659 agent_reload_trustlist ();
1664 agent_sigusr2_action (void)
1667 log_info ("SIGUSR2 received - updating card event counter\n");
1668 /* Nothing to check right now. We only increment a counter. */
1669 bump_card_eventcounter ();
1674 handle_signal (int signo
)
1678 #ifndef HAVE_W32_SYSTEM
1680 agent_sighup_action ();
1684 log_info ("SIGUSR1 received - printing internal information:\n");
1685 pth_ctrl (PTH_CTRL_DUMPSTATE
, log_get_stream ());
1686 agent_query_dump_state ();
1687 agent_scd_dump_state ();
1691 agent_sigusr2_action ();
1695 if (!shutdown_pending
)
1696 log_info ("SIGTERM received - shutting down ...\n");
1698 log_info ("SIGTERM received - still %ld running threads\n",
1699 pth_ctrl( PTH_CTRL_GETTHREADS
));
1701 if (shutdown_pending
> 2)
1703 log_info ("shutdown forced\n");
1704 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1711 log_info ("SIGINT received - immediate shutdown\n");
1712 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1718 log_info ("signal %d received - no action defined\n", signo
);
1723 /* Check the nonce on a new connection. This is a NOP unless we we
1724 are using our Unix domain socket emulation under Windows. */
1726 check_nonce (ctrl_t ctrl
, assuan_sock_nonce_t
*nonce
)
1728 if (assuan_sock_check_nonce (ctrl
->thread_startup
.fd
, nonce
))
1730 log_info (_("error reading nonce on fd %d: %s\n"),
1731 FD2INT(ctrl
->thread_startup
.fd
), strerror (errno
));
1732 assuan_sock_close (ctrl
->thread_startup
.fd
);
1741 /* This is the standard connection thread's main function. */
1743 start_connection_thread (void *arg
)
1747 if (check_nonce (ctrl
, &socket_nonce
))
1750 agent_init_default_ctrl (ctrl
);
1752 log_info (_("handler 0x%lx for fd %d started\n"),
1753 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1755 start_command_handler (ctrl
, GNUPG_INVALID_FD
, ctrl
->thread_startup
.fd
);
1757 log_info (_("handler 0x%lx for fd %d terminated\n"),
1758 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1760 agent_deinit_default_ctrl (ctrl
);
1766 /* This is the ssh connection thread's main function. */
1768 start_connection_thread_ssh (void *arg
)
1772 if (check_nonce (ctrl
, &socket_nonce_ssh
))
1775 agent_init_default_ctrl (ctrl
);
1777 log_info (_("ssh handler 0x%lx for fd %d started\n"),
1778 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1780 start_command_handler_ssh (ctrl
, ctrl
->thread_startup
.fd
);
1782 log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
1783 pth_thread_id (), FD2INT(ctrl
->thread_startup
.fd
));
1785 agent_deinit_default_ctrl (ctrl
);
1791 /* Connection handler loop. Wait for connection requests and spawn a
1792 thread after accepting a connection. */
1794 handle_connections (gnupg_fd_t listen_fd
, gnupg_fd_t listen_fd_ssh
)
1797 pth_event_t ev
, time_ev
;
1800 struct sockaddr_un paddr
;
1802 fd_set fdset
, read_fdset
;
1807 tattr
= pth_attr_new();
1808 pth_attr_set (tattr
, PTH_ATTR_JOINABLE
, 0);
1809 pth_attr_set (tattr
, PTH_ATTR_STACK_SIZE
, 256*1024);
1811 #ifndef HAVE_W32_SYSTEM /* fixme */
1812 /* Make sure that the signals we are going to handle are not blocked
1813 and create an event object for them. We also set the default
1814 action to ignore because we use an Pth event to get notified
1815 about signals. This avoids that the default action is taken in
1816 case soemthing goes wrong within Pth. The problem might also be
1818 sigemptyset (&sigs
);
1820 static const int mysigs
[] = { SIGHUP
, SIGUSR1
, SIGUSR2
, SIGINT
, SIGTERM
};
1821 struct sigaction sa
;
1824 for (i
=0; i
< DIM (mysigs
); i
++)
1826 sigemptyset (&sa
.sa_mask
);
1827 sa
.sa_handler
= SIG_IGN
;
1829 sigaction (mysigs
[i
], &sa
, NULL
);
1831 sigaddset (&sigs
, mysigs
[i
]);
1835 pth_sigmask (SIG_UNBLOCK
, &sigs
, NULL
);
1836 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1838 # ifdef PTH_EVENT_HANDLE
1840 ev
= pth_event (PTH_EVENT_HANDLE
, get_agent_scd_notify_event ());
1843 /* Use a dummy event. */
1845 ev
= pth_event (PTH_EVENT_SIGS
, &sigs
, &signo
);
1851 FD_SET (FD2INT (listen_fd
), &fdset
);
1852 nfd
= FD2INT (listen_fd
);
1853 if (listen_fd_ssh
!= GNUPG_INVALID_FD
)
1855 FD_SET ( FD2INT(listen_fd_ssh
), &fdset
);
1856 if (FD2INT (listen_fd_ssh
) > nfd
)
1857 nfd
= FD2INT (listen_fd_ssh
);
1862 /* Make sure that our signals are not blocked. */
1863 pth_sigmask (SIG_UNBLOCK
, &sigs
, NULL
);
1865 /* Shutdown test. */
1866 if (shutdown_pending
)
1868 if (pth_ctrl (PTH_CTRL_GETTHREADS
) == 1)
1871 /* Do not accept new connections but keep on running the
1872 loop to cope with the timer events. */
1876 /* Create a timeout event if needed. To help with power saving
1877 we syncronize the ticks to the next full second. */
1880 pth_time_t nexttick
;
1882 nexttick
= pth_timeout (TIMERTICK_INTERVAL
, 0);
1883 if (nexttick
.tv_usec
> 10) /* Use a 10 usec threshhold. */
1886 nexttick
.tv_usec
= 0;
1888 time_ev
= pth_event (PTH_EVENT_TIME
, nexttick
);
1891 /* POSIX says that fd_set should be implemented as a structure,
1892 thus a simple assignment is fine to copy the entire set. */
1896 pth_event_concat (ev
, time_ev
, NULL
);
1897 ret
= pth_select_ev (nfd
+1, &read_fdset
, NULL
, NULL
, NULL
, ev
);
1899 pth_event_isolate (time_ev
);
1903 if (pth_event_occurred (ev
)
1904 || (time_ev
&& pth_event_occurred (time_ev
)))
1906 if (pth_event_occurred (ev
))
1908 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1909 agent_sigusr2_action ();
1911 handle_signal (signo
);
1914 if (time_ev
&& pth_event_occurred (time_ev
))
1916 pth_event_free (time_ev
, PTH_FREE_ALL
);
1922 log_error (_("pth_select failed: %s - waiting 1s\n"),
1928 if (pth_event_occurred (ev
))
1930 #if defined(HAVE_W32_SYSTEM) && defined(PTH_EVENT_HANDLE)
1931 agent_sigusr2_action ();
1933 handle_signal (signo
);
1937 if (time_ev
&& pth_event_occurred (time_ev
))
1939 pth_event_free (time_ev
, PTH_FREE_ALL
);
1945 /* We now might create new threads and because we don't want any
1946 signals (as we are handling them here) to be delivered to a
1947 new thread. Thus we need to block those signals. */
1948 pth_sigmask (SIG_BLOCK
, &sigs
, NULL
);
1950 if (!shutdown_pending
&& FD_ISSET (FD2INT (listen_fd
), &read_fdset
))
1954 plen
= sizeof paddr
;
1955 fd
= INT2FD (pth_accept (FD2INT(listen_fd
),
1956 (struct sockaddr
*)&paddr
, &plen
));
1957 if (fd
== GNUPG_INVALID_FD
)
1959 log_error ("accept failed: %s\n", strerror (errno
));
1961 else if ( !(ctrl
= xtrycalloc (1, sizeof *ctrl
)) )
1963 log_error ("error allocating connection control data: %s\n",
1965 assuan_sock_close (fd
);
1967 else if ( !(ctrl
->session_env
= session_env_new ()) )
1969 log_error ("error allocating session environment block: %s\n",
1972 assuan_sock_close (fd
);
1976 char threadname
[50];
1978 snprintf (threadname
, sizeof threadname
-1,
1979 "conn fd=%d (gpg)", FD2INT(fd
));
1980 threadname
[sizeof threadname
-1] = 0;
1981 pth_attr_set (tattr
, PTH_ATTR_NAME
, threadname
);
1982 ctrl
->thread_startup
.fd
= fd
;
1983 if (!pth_spawn (tattr
, start_connection_thread
, ctrl
))
1985 log_error ("error spawning connection handler: %s\n",
1987 assuan_sock_close (fd
);
1991 fd
= GNUPG_INVALID_FD
;
1994 if (!shutdown_pending
&& listen_fd_ssh
!= GNUPG_INVALID_FD
1995 && FD_ISSET ( FD2INT (listen_fd_ssh
), &read_fdset
))
1999 plen
= sizeof paddr
;
2000 fd
= INT2FD(pth_accept (FD2INT(listen_fd_ssh
),
2001 (struct sockaddr
*)&paddr
, &plen
));
2002 if (fd
== GNUPG_INVALID_FD
)
2004 log_error ("accept failed for ssh: %s\n", strerror (errno
));
2006 else if ( !(ctrl
= xtrycalloc (1, sizeof *ctrl
)) )
2008 log_error ("error allocating connection control data: %s\n",
2010 assuan_sock_close (fd
);
2012 else if ( !(ctrl
->session_env
= session_env_new ()) )
2014 log_error ("error allocating session environment block: %s\n",
2017 assuan_sock_close (fd
);
2021 char threadname
[50];
2023 agent_init_default_ctrl (ctrl
);
2024 snprintf (threadname
, sizeof threadname
-1,
2025 "conn fd=%d (ssh)", FD2INT(fd
));
2026 threadname
[sizeof threadname
-1] = 0;
2027 pth_attr_set (tattr
, PTH_ATTR_NAME
, threadname
);
2028 ctrl
->thread_startup
.fd
= fd
;
2029 if (!pth_spawn (tattr
, start_connection_thread_ssh
, ctrl
) )
2031 log_error ("error spawning ssh connection handler: %s\n",
2033 assuan_sock_close (fd
);
2037 fd
= GNUPG_INVALID_FD
;
2041 pth_event_free (ev
, PTH_FREE_ALL
);
2043 pth_event_free (time_ev
, PTH_FREE_ALL
);
2045 log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2050 /* Helper for check_own_socket. */
2052 check_own_socket_pid_cb (void *opaque
, const void *buffer
, size_t length
)
2054 membuf_t
*mb
= opaque
;
2055 put_membuf (mb
, buffer
, length
);
2060 /* The thread running the actual check. We need to run this in a
2061 separate thread so that check_own_thread can be called from the
2064 check_own_socket_thread (void *arg
)
2067 char *sockname
= arg
;
2068 assuan_context_t ctx
= NULL
;
2072 check_own_socket_running
++;
2074 rc
= assuan_new (&ctx
);
2078 log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc
));
2082 rc
= assuan_socket_connect (ctx
, sockname
, (pid_t
)(-1));
2085 log_error ("can't connect my own socket: %s\n", gpg_strerror (rc
));
2089 init_membuf (&mb
, 100);
2090 rc
= assuan_transact (ctx
, "GETINFO pid", check_own_socket_pid_cb
, &mb
,
2091 NULL
, NULL
, NULL
, NULL
);
2092 put_membuf (&mb
, "", 1);
2093 buffer
= get_membuf (&mb
, NULL
);
2096 log_error ("sending command \"%s\" to my own socket failed: %s\n",
2097 "GETINFO pid", gpg_strerror (rc
));
2100 else if ( (pid_t
)strtoul (buffer
, NULL
, 10) != getpid ())
2102 log_error ("socket is now serviced by another server\n");
2105 else if (opt
.verbose
> 1)
2106 log_error ("socket is still served by this server\n");
2112 assuan_release (ctx
);
2115 /* We may not remove the socket as it is now in use by another
2116 server. Setting the name to empty does this. */
2119 if (socket_name_ssh
)
2120 *socket_name_ssh
= 0;
2121 shutdown_pending
= 2;
2122 log_info ("this process is useless - shutting down\n");
2124 check_own_socket_running
--;
2129 /* Check whether we are still listening on our own socket. In case
2130 another gpg-agent process started after us has taken ownership of
2131 our socket, we woul linger around without any real taks. Thus we
2132 better check once in a while whether we are really needed. */
2134 check_own_socket (void)
2139 if (!use_standard_socket
)
2140 return; /* This check makes only sense in standard socket mode. */
2142 if (check_own_socket_running
|| shutdown_pending
)
2143 return; /* Still running or already shutting down. */
2145 sockname
= make_filename (opt
.homedir
, "S.gpg-agent", NULL
);
2147 return; /* Out of memory. */
2149 tattr
= pth_attr_new();
2150 pth_attr_set (tattr
, PTH_ATTR_JOINABLE
, 0);
2151 pth_attr_set (tattr
, PTH_ATTR_STACK_SIZE
, 256*1024);
2152 pth_attr_set (tattr
, PTH_ATTR_NAME
, "check-own-socket");
2154 if (!pth_spawn (tattr
, check_own_socket_thread
, sockname
))
2155 log_error ("error spawning check_own_socket_thread: %s\n",
2157 pth_attr_destroy (tattr
);
2162 /* Figure out whether an agent is available and running. Prints an
2163 error if not. If SILENT is true, no messages are printed. Usually
2164 started with MODE 0. Returns 0 if the agent is running. */
2166 check_for_running_agent (int silent
, int mode
)
2170 assuan_context_t ctx
= NULL
;
2175 infostr
= getenv ("GPG_AGENT_INFO");
2176 if (!infostr
|| !*infostr
)
2178 if (!check_for_running_agent (silent
, 1))
2179 return 0; /* Okay, its running on the standard socket. */
2181 log_error (_("no gpg-agent running in this session\n"));
2185 infostr
= xstrdup (infostr
);
2186 if ( !(p
= strchr (infostr
, PATHSEP_C
)) || p
== infostr
)
2189 if (!check_for_running_agent (silent
, 1))
2190 return 0; /* Okay, its running on the standard socket. */
2192 log_error (_("malformed GPG_AGENT_INFO environment variable\n"));
2198 while (*p
&& *p
!= PATHSEP_C
)
2200 prot
= *p
? atoi (p
+1) : 0;
2205 log_error (_("gpg-agent protocol version %d is not supported\n"),
2207 if (!check_for_running_agent (silent
, 1))
2208 return 0; /* Okay, its running on the standard socket. */
2212 else /* MODE != 0 */
2214 infostr
= make_filename (opt
.homedir
, "S.gpg-agent", NULL
);
2218 rc
= assuan_new (&ctx
);
2220 rc
= assuan_socket_connect (&ctx
, infostr
, pid
);
2224 if (!mode
&& !check_for_running_agent (silent
, 1))
2225 return 0; /* Okay, its running on the standard socket. */
2227 if (!mode
&& !silent
)
2228 log_error ("can't connect to the agent: %s\n", gpg_strerror (rc
));
2231 assuan_release (ctx
);
2235 if (!opt
.quiet
&& !silent
)
2236 log_info ("gpg-agent running and available\n");
2238 assuan_release (ctx
);