Line data Source code
1 : /* gpg-agent.c - The GnuPG Agent
2 : * Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc.
3 : * Copyright (C) 2000-2016 Werner Koch
4 : *
5 : * This file is part of GnuPG.
6 : *
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.
11 : *
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.
16 : *
17 : * You should have received a copy of the GNU General Public License
18 : * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 : */
20 :
21 : #include <config.h>
22 :
23 : #include <stdio.h>
24 : #include <stdlib.h>
25 : #include <stddef.h>
26 : #include <stdarg.h>
27 : #include <string.h>
28 : #include <errno.h>
29 : #include <assert.h>
30 : #include <time.h>
31 : #include <fcntl.h>
32 : #include <sys/stat.h>
33 : #ifdef HAVE_W32_SYSTEM
34 : # ifndef WINVER
35 : # define WINVER 0x0500 /* Same as in common/sysutils.c */
36 : # endif
37 : # ifdef HAVE_WINSOCK2_H
38 : # include <winsock2.h>
39 : # endif
40 : # include <aclapi.h>
41 : # include <sddl.h>
42 : #else /*!HAVE_W32_SYSTEM*/
43 : # include <sys/socket.h>
44 : # include <sys/un.h>
45 : #endif /*!HAVE_W32_SYSTEM*/
46 : #include <unistd.h>
47 : #ifdef HAVE_SIGNAL_H
48 : # include <signal.h>
49 : #endif
50 : #include <npth.h>
51 :
52 : #define GNUPG_COMMON_NEED_AFLOCAL
53 : #include "agent.h"
54 : #include <assuan.h> /* Malloc hooks and socket wrappers. */
55 :
56 : #include "i18n.h"
57 : #include "sysutils.h"
58 : #include "gc-opt-flags.h"
59 : #include "exechelp.h"
60 : #include "asshelp.h"
61 : #include "../common/init.h"
62 :
63 :
64 : enum cmd_and_opt_values
65 : { aNull = 0,
66 : oCsh = 'c',
67 : oQuiet = 'q',
68 : oSh = 's',
69 : oVerbose = 'v',
70 :
71 : oNoVerbose = 500,
72 : aGPGConfList,
73 : aGPGConfTest,
74 : aUseStandardSocketP,
75 : oOptions,
76 : oDebug,
77 : oDebugAll,
78 : oDebugLevel,
79 : oDebugWait,
80 : oDebugQuickRandom,
81 : oDebugPinentry,
82 : oNoGreeting,
83 : oNoOptions,
84 : oHomedir,
85 : oNoDetach,
86 : oNoGrab,
87 : oLogFile,
88 : oServer,
89 : oDaemon,
90 : oSupervised,
91 : oBatch,
92 :
93 : oPinentryProgram,
94 : oPinentryTouchFile,
95 : oPinentryInvisibleChar,
96 : oPinentryTimeout,
97 : oDisplay,
98 : oTTYname,
99 : oTTYtype,
100 : oLCctype,
101 : oLCmessages,
102 : oXauthority,
103 : oScdaemonProgram,
104 : oDefCacheTTL,
105 : oDefCacheTTLSSH,
106 : oMaxCacheTTL,
107 : oMaxCacheTTLSSH,
108 : oEnforcePassphraseConstraints,
109 : oMinPassphraseLen,
110 : oMinPassphraseNonalpha,
111 : oCheckPassphrasePattern,
112 : oMaxPassphraseDays,
113 : oEnablePassphraseHistory,
114 : oUseStandardSocket,
115 : oNoUseStandardSocket,
116 : oExtraSocket,
117 : oBrowserSocket,
118 : oFakedSystemTime,
119 :
120 : oIgnoreCacheForSigning,
121 : oAllowMarkTrusted,
122 : oNoAllowMarkTrusted,
123 : oAllowPresetPassphrase,
124 : oAllowLoopbackPinentry,
125 : oNoAllowLoopbackPinentry,
126 : oNoAllowExternalCache,
127 : oAllowEmacsPinentry,
128 : oKeepTTY,
129 : oKeepDISPLAY,
130 : oSSHSupport,
131 : oPuttySupport,
132 : oDisableScdaemon,
133 : oDisableCheckOwnSocket,
134 : oWriteEnvFile
135 : };
136 :
137 :
138 : #ifndef ENAMETOOLONG
139 : # define ENAMETOOLONG EINVAL
140 : #endif
141 :
142 :
143 : static ARGPARSE_OPTS opts[] = {
144 :
145 : ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
146 : ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
147 : ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
148 :
149 : ARGPARSE_group (301, N_("@Options:\n ")),
150 :
151 : ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
152 : ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
153 : #ifndef HAVE_W32_SYSTEM
154 : ARGPARSE_s_n (oSupervised, "supervised", N_("run in supervised mode")),
155 : #endif
156 : ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
157 : ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
158 : ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
159 : ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
160 : ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
161 :
162 : ARGPARSE_s_s (oDebug, "debug", "@"),
163 : ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
164 : ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
165 : ARGPARSE_s_i (oDebugWait," debug-wait", "@"),
166 : ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
167 : ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
168 :
169 : ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
170 : ARGPARSE_s_n (oNoGrab, "no-grab", N_("do not grab keyboard and mouse")),
171 : ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
172 : ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
173 : /* */ N_("|PGM|use PGM as the PIN-Entry program")),
174 : ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
175 : ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
176 : ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
177 : ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
178 : /* */ N_("|PGM|use PGM as the SCdaemon program") ),
179 : ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
180 : /* */ N_("do not use the SCdaemon") ),
181 : ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
182 :
183 : ARGPARSE_s_s (oExtraSocket, "extra-socket",
184 : /* */ N_("|NAME|accept some commands via NAME")),
185 :
186 : ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
187 :
188 : ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
189 :
190 : ARGPARSE_s_n (oBatch, "batch", "@"),
191 : ARGPARSE_s_s (oHomedir, "homedir", "@"),
192 :
193 : ARGPARSE_s_s (oDisplay, "display", "@"),
194 : ARGPARSE_s_s (oTTYname, "ttyname", "@"),
195 : ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
196 : ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
197 : ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
198 : ARGPARSE_s_s (oXauthority, "xauthority", "@"),
199 : ARGPARSE_s_n (oKeepTTY, "keep-tty",
200 : /* */ N_("ignore requests to change the TTY")),
201 : ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
202 : /* */ N_("ignore requests to change the X display")),
203 :
204 : ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
205 : N_("|N|expire cached PINs after N seconds")),
206 : ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
207 : ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
208 : ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
209 :
210 : ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
211 : /* */ "@"),
212 : ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
213 : ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
214 : ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
215 : ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
216 : ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
217 :
218 : ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
219 : /* */ N_("do not use the PIN cache when signing")),
220 : ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
221 : /* */ N_("disallow the use of an external password cache")),
222 : ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
223 : /* */ N_("disallow clients to mark keys as \"trusted\"")),
224 : ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
225 : ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
226 : /* */ N_("allow presetting passphrase")),
227 : ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
228 : N_("disallow caller to override the pinentry")),
229 : ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
230 : ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
231 : /* */ N_("allow passphrase to be prompted through Emacs")),
232 :
233 : ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
234 : ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
235 : #ifdef HAVE_W32_SYSTEM
236 : /* */ N_("enable putty support")
237 : #else
238 : /* */ "@"
239 : #endif
240 : ),
241 :
242 : /* Dummy options for backward compatibility. */
243 : ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
244 : ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
245 : ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
246 :
247 : {0} /* End of list */
248 : };
249 :
250 :
251 : /* The list of supported debug flags. */
252 : static struct debug_flags_s debug_flags [] =
253 : {
254 : { DBG_COMMAND_VALUE, "command" },
255 : { DBG_MPI_VALUE , "mpi" },
256 : { DBG_CRYPTO_VALUE , "crypto" },
257 : { DBG_MEMORY_VALUE , "memory" },
258 : { DBG_CACHE_VALUE , "cache" },
259 : { DBG_MEMSTAT_VALUE, "memstat" },
260 : { DBG_HASHING_VALUE, "hashing" },
261 : { DBG_IPC_VALUE , "ipc" },
262 : { 77, NULL } /* 77 := Do not exit on "help" or "?". */
263 : };
264 :
265 :
266 :
267 : #define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
268 : #define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
269 : #define MAX_CACHE_TTL (120*60) /* 2 hours */
270 : #define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
271 : #define MIN_PASSPHRASE_LEN (8)
272 : #define MIN_PASSPHRASE_NONALPHA (1)
273 : #define MAX_PASSPHRASE_DAYS (0)
274 :
275 : /* The timer tick used for housekeeping stuff. For Windows we use a
276 : longer period as the SetWaitableTimer seems to signal earlier than
277 : the 2 seconds. CHECK_OWN_SOCKET_INTERVAL defines how often we
278 : check our own socket in standard socket mode. If that value is 0
279 : we don't check at all. All values are in seconds. */
280 : #if defined(HAVE_W32CE_SYSTEM)
281 : # define TIMERTICK_INTERVAL (60)
282 : # define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
283 : #elif defined(HAVE_W32_SYSTEM)
284 : # define TIMERTICK_INTERVAL (4)
285 : # define CHECK_OWN_SOCKET_INTERVAL (60)
286 : #else
287 : # define TIMERTICK_INTERVAL (2)
288 : # define CHECK_OWN_SOCKET_INTERVAL (60)
289 : #endif
290 :
291 :
292 : /* Flag indicating that the ssh-agent subsystem has been enabled. */
293 : static int ssh_support;
294 :
295 : #ifdef HAVE_W32_SYSTEM
296 : /* Flag indicating that support for Putty has been enabled. */
297 : static int putty_support;
298 : /* A magic value used with WM_COPYDATA. */
299 : #define PUTTY_IPC_MAGIC 0x804e50ba
300 : /* To avoid surprises we limit the size of the mapped IPC file to this
301 : value. Putty currently (0.62) uses 8k, thus 16k should be enough
302 : for the foreseeable future. */
303 : #define PUTTY_IPC_MAXLEN 16384
304 : #endif /*HAVE_W32_SYSTEM*/
305 :
306 : /* The list of open file descriptors at startup. Note that this list
307 : has been allocated using the standard malloc. */
308 : static int *startup_fd_list;
309 :
310 : /* The signal mask at startup and a flag telling whether it is valid. */
311 : #ifdef HAVE_SIGPROCMASK
312 : static sigset_t startup_signal_mask;
313 : static int startup_signal_mask_valid;
314 : #endif
315 :
316 : /* Flag to indicate that a shutdown was requested. */
317 : static int shutdown_pending;
318 :
319 : /* Counter for the currently running own socket checks. */
320 : static int check_own_socket_running;
321 :
322 : /* Flags to indicate that check_own_socket shall not be called. */
323 : static int disable_check_own_socket;
324 :
325 : /* Flag indicating that we are in supervised mode. */
326 : static int is_supervised;
327 :
328 : /* Flag to inhibit socket removal in cleanup. */
329 : static int inhibit_socket_removal;
330 :
331 : /* It is possible that we are currently running under setuid permissions */
332 : static int maybe_setuid = 1;
333 :
334 : /* Name of the communication socket used for native gpg-agent
335 : requests. The second variable is either NULL or a malloced string
336 : with the real socket name in case it has been redirected. */
337 : static char *socket_name;
338 : static char *redir_socket_name;
339 :
340 : /* Name of the optional extra socket used for native gpg-agent requests. */
341 : static char *socket_name_extra;
342 : static char *redir_socket_name_extra;
343 :
344 : /* Name of the optional browser socket used for native gpg-agent requests. */
345 : static char *socket_name_browser;
346 : static char *redir_socket_name_browser;
347 :
348 : /* Name of the communication socket used for ssh-agent-emulation. */
349 : static char *socket_name_ssh;
350 : static char *redir_socket_name_ssh;
351 :
352 : /* We need to keep track of the server's nonces (these are dummies for
353 : POSIX systems). */
354 : static assuan_sock_nonce_t socket_nonce;
355 : static assuan_sock_nonce_t socket_nonce_extra;
356 : static assuan_sock_nonce_t socket_nonce_browser;
357 : static assuan_sock_nonce_t socket_nonce_ssh;
358 :
359 :
360 : /* Default values for options passed to the pinentry. */
361 : static char *default_display;
362 : static char *default_ttyname;
363 : static char *default_ttytype;
364 : static char *default_lc_ctype;
365 : static char *default_lc_messages;
366 : static char *default_xauthority;
367 :
368 : /* Name of a config file, which will be reread on a HUP if it is not NULL. */
369 : static char *config_filename;
370 :
371 : /* Helper to implement --debug-level */
372 : static const char *debug_level;
373 :
374 : /* Keep track of the current log file so that we can avoid updating
375 : the log file after a SIGHUP if it didn't changed. Malloced. */
376 : static char *current_logfile;
377 :
378 : /* The handle_tick() function may test whether a parent is still
379 : running. We record the PID of the parent here or -1 if it should be
380 : watched. */
381 : static pid_t parent_pid = (pid_t)(-1);
382 :
383 : /* Number of active connections. */
384 : static int active_connections;
385 :
386 : /* This object is used to dispatch progress messages from Libgcrypt to
387 : * the right thread. Given that we will have at max only a few dozen
388 : * connections at a time, using a linked list is the easiest way to
389 : * handle this. */
390 : struct progress_dispatch_s
391 : {
392 : struct progress_dispatch_s *next;
393 : /* The control object of the connection. If this is NULL no
394 : * connection is associated with this item and it is free for reuse
395 : * by new connections. */
396 : ctrl_t ctrl;
397 :
398 : /* The thread id of (npth_self) of the connection. */
399 : npth_t tid;
400 :
401 : /* The callback set by the connection. This is similar to the
402 : * Libgcrypt callback but with the control object passed as the
403 : * first argument. */
404 : void (*cb)(ctrl_t ctrl,
405 : const char *what, int printchar,
406 : int current, int total);
407 : };
408 : struct progress_dispatch_s *progress_dispatch_list;
409 :
410 :
411 :
412 :
413 : /*
414 : Local prototypes.
415 : */
416 :
417 : static char *create_socket_name (char *standard_name, int with_homedir);
418 : static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
419 : char **r_redir_name,
420 : assuan_sock_nonce_t *nonce);
421 : static void create_directories (void);
422 :
423 : static void agent_libgcrypt_progress_cb (void *data, const char *what,
424 : int printchar,
425 : int current, int total);
426 : static void agent_init_default_ctrl (ctrl_t ctrl);
427 : static void agent_deinit_default_ctrl (ctrl_t ctrl);
428 :
429 : static void handle_connections (gnupg_fd_t listen_fd,
430 : gnupg_fd_t listen_fd_extra,
431 : gnupg_fd_t listen_fd_browser,
432 : gnupg_fd_t listen_fd_ssh);
433 : static void check_own_socket (void);
434 : static int check_for_running_agent (int silent);
435 :
436 : /* Pth wrapper function definitions. */
437 31266 : ASSUAN_SYSTEM_NPTH_IMPL;
438 :
439 :
440 : /*
441 : Functions.
442 : */
443 :
444 : /* Allocate a string describing a library version by calling a GETFNC.
445 : This function is expected to be called only once. GETFNC is
446 : expected to have a semantic like gcry_check_version (). */
447 : static char *
448 0 : make_libversion (const char *libname, const char *(*getfnc)(const char*))
449 : {
450 : const char *s;
451 : char *result;
452 :
453 0 : if (maybe_setuid)
454 : {
455 0 : gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
456 0 : maybe_setuid = 0;
457 : }
458 0 : s = getfnc (NULL);
459 0 : result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
460 0 : strcpy (stpcpy (stpcpy (result, libname), " "), s);
461 0 : return result;
462 : }
463 :
464 : /* Return strings describing this program. The case values are
465 : described in common/argparse.c:strusage. The values here override
466 : the default values given by strusage. */
467 : static const char *
468 112 : my_strusage (int level)
469 : {
470 : static char *ver_gcry;
471 : const char *p;
472 :
473 112 : switch (level)
474 : {
475 56 : case 11: p = "@GPG_AGENT@ (@GNUPG@)";
476 56 : break;
477 56 : case 13: p = VERSION; break;
478 0 : case 17: p = PRINTABLE_OS_NAME; break;
479 : /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
480 : reporting address. This is so that we can change the
481 : reporting address without breaking the translations. */
482 0 : case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
483 :
484 : case 20:
485 0 : if (!ver_gcry)
486 0 : ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
487 0 : p = ver_gcry;
488 0 : break;
489 :
490 : case 1:
491 0 : case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
492 0 : break;
493 0 : case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
494 : "Secret key management for @GNUPG@\n");
495 0 : break;
496 :
497 0 : default: p = NULL;
498 : }
499 112 : return p;
500 : }
501 :
502 :
503 :
504 : /* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
505 : only the active debug flags are propagated to the subsystems. With
506 : DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
507 : all flags already set. Note that we don't fail here, because it is
508 : important to keep gpg-agent running even after re-reading the
509 : options due to a SIGHUP. */
510 : static void
511 52 : set_debug (void)
512 : {
513 52 : int numok = (debug_level && digitp (debug_level));
514 52 : int numlvl = numok? atoi (debug_level) : 0;
515 :
516 52 : if (!debug_level)
517 : ;
518 0 : else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
519 0 : opt.debug = 0;
520 0 : else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
521 0 : opt.debug = DBG_IPC_VALUE;
522 0 : else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
523 0 : opt.debug = DBG_IPC_VALUE|DBG_COMMAND_VALUE;
524 0 : else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
525 0 : opt.debug = (DBG_IPC_VALUE|DBG_COMMAND_VALUE
526 : |DBG_CACHE_VALUE);
527 0 : else if (!strcmp (debug_level, "guru") || numok)
528 : {
529 0 : opt.debug = ~0;
530 : /* Unless the "guru" string has been used we don't want to allow
531 : hashing debugging. The rationale is that people tend to
532 : select the highest debug value and would then clutter their
533 : disk with debug files which may reveal confidential data. */
534 0 : if (numok)
535 0 : opt.debug &= ~(DBG_HASHING_VALUE);
536 : }
537 : else
538 : {
539 0 : log_error (_("invalid debug-level '%s' given\n"), debug_level);
540 0 : opt.debug = 0; /* Reset debugging, so that prior debug
541 : statements won't have an undesired effect. */
542 : }
543 :
544 52 : if (opt.debug && !opt.verbose)
545 0 : opt.verbose = 1;
546 52 : if (opt.debug && opt.quiet)
547 0 : opt.quiet = 0;
548 :
549 52 : if (opt.debug & DBG_MPI_VALUE)
550 0 : gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
551 52 : if (opt.debug & DBG_CRYPTO_VALUE )
552 0 : gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
553 52 : gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
554 :
555 52 : if (opt.debug)
556 0 : parse_debug_flag (NULL, &opt.debug, debug_flags);
557 52 : }
558 :
559 :
560 : /* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
561 : the corresponding real name if the socket has been redirected. */
562 : static void
563 416 : remove_socket (char *name, char *redir_name)
564 : {
565 416 : if (name && *name)
566 : {
567 208 : if (redir_name)
568 0 : name = redir_name;
569 :
570 208 : gnupg_remove (name);
571 208 : *name = 0;
572 : }
573 416 : }
574 :
575 :
576 : /* Discover which inherited file descriptors correspond to which
577 : * services/sockets offered by gpg-agent, using the LISTEN_FDS and
578 : * LISTEN_FDNAMES convention. The understood labels are "ssh",
579 : * "extra", and "browser". "std" or other labels will be interpreted
580 : * as the standard socket.
581 : *
582 : * This function is designed to log errors when the expected file
583 : * descriptors don't make sense, but to do its best to continue to
584 : * work even in the face of minor misconfigurations.
585 : *
586 : * For more information on the LISTEN_FDS convention, see
587 : * sd_listen_fds(3) on certain Linux distributions.
588 : */
589 : #ifndef HAVE_W32_SYSTEM
590 : static void
591 0 : map_supervised_sockets (gnupg_fd_t *r_fd,
592 : gnupg_fd_t *r_fd_extra,
593 : gnupg_fd_t *r_fd_browser,
594 : gnupg_fd_t *r_fd_ssh)
595 : {
596 : struct {
597 : const char *label;
598 : int **fdaddr;
599 : char **nameaddr;
600 0 : } tbl[] = {
601 : { "ssh", &r_fd_ssh, &socket_name_ssh },
602 : { "browser", &r_fd_browser, &socket_name_browser },
603 : { "extra", &r_fd_extra, &socket_name_extra },
604 : { "std", &r_fd, &socket_name } /* (Must be the last item.) */
605 : };
606 : const char *envvar;
607 : char **fdnames;
608 : int nfdnames;
609 : int fd_count;
610 :
611 0 : *r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
612 :
613 : /* Print a warning if LISTEN_PID does not match outr pid. */
614 0 : envvar = getenv ("LISTEN_PID");
615 0 : if (!envvar)
616 0 : log_error ("no LISTEN_PID environment variable found in "
617 : "--supervised mode (ignoring)\n");
618 0 : else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
619 0 : log_error ("environment variable LISTEN_PID (%lu) does not match"
620 : " our pid (%lu) in --supervised mode (ignoring)\n",
621 : (unsigned long)strtoul (envvar, NULL, 10),
622 0 : (unsigned long)getpid ());
623 :
624 : /* Parse LISTEN_FDNAMES into the array FDNAMES. */
625 0 : envvar = getenv ("LISTEN_FDNAMES");
626 0 : if (envvar)
627 : {
628 0 : fdnames = strtokenize (envvar, ":");
629 0 : if (!fdnames)
630 : {
631 0 : log_error ("strtokenize failed: %s\n",
632 : gpg_strerror (gpg_error_from_syserror ()));
633 0 : agent_exit (1);
634 : }
635 0 : for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
636 : ;
637 : }
638 : else
639 : {
640 0 : fdnames = NULL;
641 0 : nfdnames = 0;
642 : }
643 :
644 : /* Parse LISTEN_FDS into fd_count or provide a replacement. */
645 0 : envvar = getenv ("LISTEN_FDS");
646 0 : if (envvar)
647 0 : fd_count = atoi (envvar);
648 0 : else if (fdnames)
649 : {
650 0 : log_error ("no LISTEN_FDS environment variable found in --supervised"
651 : " mode (relying on LISTEN_FDNAMES instead)\n");
652 0 : fd_count = nfdnames;
653 : }
654 : else
655 : {
656 0 : log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
657 : "found in --supervised mode"
658 : " (assuming 1 active descriptor)\n");
659 0 : fd_count = 1;
660 : }
661 :
662 0 : if (fd_count < 1)
663 : {
664 0 : log_error ("--supervised mode expects at least one file descriptor"
665 : " (was told %d, carrying on as though it were 1)\n",
666 : fd_count);
667 0 : fd_count = 1;
668 : }
669 :
670 : /* Assign the descriptors to the return values. */
671 0 : if (!fdnames)
672 : {
673 : struct stat statbuf;
674 :
675 0 : if (fd_count != 1)
676 0 : log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
677 : " in --supervised mode."
678 : " (ignoring all sockets but the first one)\n",
679 : fd_count);
680 0 : if (fstat (3, &statbuf) == -1 && errno ==EBADF)
681 0 : log_fatal ("file descriptor 3 must be valid in --supervised mode"
682 : " if LISTEN_FDNAMES is not set\n");
683 0 : *r_fd = 3;
684 0 : socket_name = gnupg_get_socket_name (3);
685 : }
686 0 : else if (fd_count != nfdnames)
687 : {
688 0 : log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
689 : "LISTEN_FDS (%d) in --supervised mode\n",
690 : nfdnames, fd_count);
691 : }
692 : else
693 : {
694 : int i, j, fd;
695 : char *name;
696 :
697 0 : for (i = 0; i < nfdnames; i++)
698 : {
699 0 : for (j = 0; j < DIM (tbl); j++)
700 : {
701 0 : if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
702 : {
703 0 : fd = 3 + i;
704 0 : if (**tbl[j].fdaddr == -1)
705 : {
706 0 : name = gnupg_get_socket_name (fd);
707 0 : if (name)
708 : {
709 0 : **tbl[j].fdaddr = fd;
710 0 : *tbl[j].nameaddr = name;
711 0 : log_info ("using fd %d for %s socket (%s)\n",
712 : fd, tbl[j].label, name);
713 : }
714 : else
715 : {
716 0 : log_error ("cannot listen on fd %d for %s socket\n",
717 : fd, tbl[j].label);
718 0 : close (fd);
719 : }
720 : }
721 : else
722 : {
723 0 : log_error ("cannot listen on more than one %s socket\n",
724 : tbl[j].label);
725 0 : close (fd);
726 : }
727 0 : break;
728 : }
729 : }
730 : }
731 : }
732 :
733 0 : xfree (fdnames);
734 0 : }
735 : #endif /*!HAVE_W32_SYSTEM*/
736 :
737 :
738 : /* Cleanup code for this program. This is either called has an atexit
739 : handler or directly. */
740 : static void
741 156 : cleanup (void)
742 : {
743 : static int done;
744 :
745 156 : if (done)
746 208 : return;
747 104 : done = 1;
748 104 : deinitialize_module_cache ();
749 104 : if (!is_supervised && !inhibit_socket_removal)
750 : {
751 104 : remove_socket (socket_name, redir_socket_name);
752 104 : if (opt.extra_socket > 1)
753 104 : remove_socket (socket_name_extra, redir_socket_name_extra);
754 104 : if (opt.browser_socket > 1)
755 104 : remove_socket (socket_name_browser, redir_socket_name_browser);
756 104 : remove_socket (socket_name_ssh, redir_socket_name_ssh);
757 : }
758 : }
759 :
760 :
761 :
762 : /* Handle options which are allowed to be reset after program start.
763 : Return true when the current option in PARGS could be handled and
764 : false if not. As a special feature, passing a value of NULL for
765 : PARGS, resets the options to the default. REREAD should be set
766 : true if it is not the initial option parsing. */
767 : static int
768 486 : parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
769 : {
770 486 : if (!pargs)
771 : { /* reset mode */
772 52 : opt.quiet = 0;
773 52 : opt.verbose = 0;
774 52 : opt.debug = 0;
775 52 : opt.no_grab = 0;
776 52 : opt.debug_pinentry = 0;
777 52 : opt.pinentry_program = NULL;
778 52 : opt.pinentry_touch_file = NULL;
779 52 : xfree (opt.pinentry_invisible_char);
780 52 : opt.pinentry_invisible_char = NULL;
781 52 : opt.pinentry_timeout = 0;
782 52 : opt.scdaemon_program = NULL;
783 52 : opt.def_cache_ttl = DEFAULT_CACHE_TTL;
784 52 : opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
785 52 : opt.max_cache_ttl = MAX_CACHE_TTL;
786 52 : opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
787 52 : opt.enforce_passphrase_constraints = 0;
788 52 : opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
789 52 : opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
790 52 : opt.check_passphrase_pattern = NULL;
791 52 : opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
792 52 : opt.enable_passphrase_history = 0;
793 52 : opt.ignore_cache_for_signing = 0;
794 52 : opt.allow_mark_trusted = 1;
795 52 : opt.allow_external_cache = 1;
796 52 : opt.allow_loopback_pinentry = 1;
797 52 : opt.allow_emacs_pinentry = 0;
798 52 : opt.disable_scdaemon = 0;
799 52 : disable_check_own_socket = 0;
800 52 : return 1;
801 : }
802 :
803 434 : switch (pargs->r_opt)
804 : {
805 0 : case oQuiet: opt.quiet = 1; break;
806 0 : case oVerbose: opt.verbose++; break;
807 :
808 : case oDebug:
809 0 : parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
810 0 : break;
811 0 : case oDebugAll: opt.debug = ~0; break;
812 0 : case oDebugLevel: debug_level = pargs->r.ret_str; break;
813 0 : case oDebugPinentry: opt.debug_pinentry = 1; break;
814 :
815 : case oLogFile:
816 0 : if (!reread)
817 0 : return 0; /* not handeld */
818 0 : if (!current_logfile || !pargs->r.ret_str
819 0 : || strcmp (current_logfile, pargs->r.ret_str))
820 : {
821 0 : log_set_file (pargs->r.ret_str);
822 0 : xfree (current_logfile);
823 0 : current_logfile = xtrystrdup (pargs->r.ret_str);
824 : }
825 0 : break;
826 :
827 48 : case oNoGrab: opt.no_grab = 1; break;
828 :
829 82 : case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
830 0 : case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
831 : case oPinentryInvisibleChar:
832 0 : xfree (opt.pinentry_invisible_char);
833 0 : opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
834 : break;
835 0 : case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
836 0 : case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
837 0 : case oDisableScdaemon: opt.disable_scdaemon = 1; break;
838 0 : case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
839 :
840 0 : case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
841 0 : case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
842 0 : case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
843 0 : case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
844 :
845 : case oEnforcePassphraseConstraints:
846 0 : opt.enforce_passphrase_constraints=1;
847 0 : break;
848 0 : case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
849 : case oMinPassphraseNonalpha:
850 0 : opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
851 0 : break;
852 : case oCheckPassphrasePattern:
853 0 : opt.check_passphrase_pattern = pargs->r.ret_str;
854 0 : break;
855 : case oMaxPassphraseDays:
856 0 : opt.max_passphrase_days = pargs->r.ret_ulong;
857 0 : break;
858 : case oEnablePassphraseHistory:
859 0 : opt.enable_passphrase_history = 1;
860 0 : break;
861 :
862 0 : case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
863 :
864 0 : case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
865 0 : case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
866 :
867 48 : case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
868 :
869 0 : case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
870 0 : case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
871 :
872 0 : case oNoAllowExternalCache: opt.allow_external_cache = 0;
873 0 : break;
874 :
875 0 : case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
876 0 : break;
877 :
878 : default:
879 256 : return 0; /* not handled */
880 : }
881 :
882 178 : return 1; /* handled */
883 : }
884 :
885 :
886 : /* Fixup some options after all have been processed. */
887 : static void
888 52 : finalize_rereadable_options (void)
889 : {
890 52 : }
891 :
892 :
893 : static void
894 52 : thread_init_once (void)
895 : {
896 : static int npth_initialized = 0;
897 :
898 52 : if (!npth_initialized)
899 : {
900 52 : npth_initialized++;
901 52 : npth_init ();
902 : }
903 52 : gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
904 : /* Now that we have set the syscall clamp we need to tell Libgcrypt
905 : * that it should get them from libgpg-error. Note that Libgcrypt
906 : * has already been initialized but at that point nPth was not
907 : * initialized and thus Libgcrypt could not set its system call
908 : * clamp. */
909 : #if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */
910 : gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
911 : #endif
912 52 : }
913 :
914 :
915 : static void
916 52 : initialize_modules (void)
917 : {
918 52 : thread_init_once ();
919 52 : assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
920 52 : initialize_module_cache ();
921 52 : initialize_module_call_pinentry ();
922 52 : initialize_module_call_scd ();
923 52 : initialize_module_trustlist ();
924 52 : }
925 :
926 :
927 : /* The main entry point. */
928 : int
929 52 : main (int argc, char **argv )
930 : {
931 : ARGPARSE_ARGS pargs;
932 : int orig_argc;
933 : char **orig_argv;
934 52 : FILE *configfp = NULL;
935 52 : char *configname = NULL;
936 : const char *shell;
937 : unsigned configlineno;
938 52 : int parse_debug = 0;
939 52 : int default_config =1;
940 52 : int pipe_server = 0;
941 52 : int is_daemon = 0;
942 52 : int nodetach = 0;
943 52 : int csh_style = 0;
944 52 : char *logfile = NULL;
945 52 : int debug_wait = 0;
946 52 : int gpgconf_list = 0;
947 : gpg_error_t err;
948 : struct assuan_malloc_hooks malloc_hooks;
949 :
950 52 : early_system_init ();
951 :
952 : /* Before we do anything else we save the list of currently open
953 : file descriptors and the signal mask. This info is required to
954 : do the exec call properly. */
955 52 : startup_fd_list = get_all_open_fds ();
956 : #ifdef HAVE_SIGPROCMASK
957 52 : if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
958 52 : startup_signal_mask_valid = 1;
959 : #endif /*HAVE_SIGPROCMASK*/
960 :
961 : /* Set program name etc. */
962 52 : set_strusage (my_strusage);
963 52 : gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
964 : /* Please note that we may running SUID(ROOT), so be very CAREFUL
965 : when adding any stuff between here and the call to INIT_SECMEM()
966 : somewhere after the option parsing */
967 52 : log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
968 :
969 : /* Make sure that our subsystems are ready. */
970 52 : i18n_init ();
971 52 : init_common_subsystems (&argc, &argv);
972 :
973 52 : malloc_hooks.malloc = gcry_malloc;
974 52 : malloc_hooks.realloc = gcry_realloc;
975 52 : malloc_hooks.free = gcry_free;
976 52 : assuan_set_malloc_hooks (&malloc_hooks);
977 52 : assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
978 52 : assuan_sock_init ();
979 52 : setup_libassuan_logging (&opt.debug, NULL);
980 :
981 52 : setup_libgcrypt_logging ();
982 52 : gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
983 52 : gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
984 :
985 52 : disable_core_dumps ();
986 :
987 : /* Set default options. */
988 52 : parse_rereadable_options (NULL, 0); /* Reset them to default values. */
989 :
990 52 : shell = getenv ("SHELL");
991 52 : if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
992 0 : csh_style = 1;
993 :
994 : /* Record some of the original environment strings. */
995 : {
996 : const char *s;
997 : int idx;
998 : static const char *names[] =
999 : { "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
1000 :
1001 52 : err = 0;
1002 52 : opt.startup_env = session_env_new ();
1003 52 : if (!opt.startup_env)
1004 0 : err = gpg_error_from_syserror ();
1005 260 : for (idx=0; !err && names[idx]; idx++)
1006 : {
1007 208 : s = getenv (names[idx]);
1008 208 : if (s)
1009 104 : err = session_env_setenv (opt.startup_env, names[idx], s);
1010 : }
1011 52 : if (!err)
1012 : {
1013 52 : s = gnupg_ttyname (0);
1014 52 : if (s)
1015 0 : err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
1016 : }
1017 52 : if (err)
1018 0 : log_fatal ("error recording startup environment: %s\n",
1019 : gpg_strerror (err));
1020 :
1021 : /* Fixme: Better use the locale function here. */
1022 52 : opt.startup_lc_ctype = getenv ("LC_CTYPE");
1023 52 : if (opt.startup_lc_ctype)
1024 52 : opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
1025 52 : opt.startup_lc_messages = getenv ("LC_MESSAGES");
1026 52 : if (opt.startup_lc_messages)
1027 0 : opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
1028 : }
1029 :
1030 : /* Check whether we have a config file on the commandline */
1031 52 : orig_argc = argc;
1032 52 : orig_argv = argv;
1033 52 : pargs.argc = &argc;
1034 52 : pargs.argv = &argv;
1035 52 : pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1036 312 : while (arg_parse( &pargs, opts))
1037 : {
1038 208 : if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
1039 0 : parse_debug++;
1040 208 : else if (pargs.r_opt == oOptions)
1041 : { /* yes there is one, so we do not try the default one, but
1042 : read the option file when it is encountered at the
1043 : commandline */
1044 0 : default_config = 0;
1045 : }
1046 208 : else if (pargs.r_opt == oNoOptions)
1047 0 : default_config = 0; /* --no-options */
1048 208 : else if (pargs.r_opt == oHomedir)
1049 52 : gnupg_set_homedir (pargs.r.ret_str);
1050 156 : else if (pargs.r_opt == oDebugQuickRandom)
1051 : {
1052 52 : gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
1053 : }
1054 :
1055 : }
1056 :
1057 : /* Initialize the secure memory. */
1058 52 : gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
1059 52 : maybe_setuid = 0;
1060 :
1061 : /*
1062 : Now we are now working under our real uid
1063 : */
1064 :
1065 52 : if (default_config)
1066 52 : configname = make_filename (gnupg_homedir (),
1067 : GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1068 :
1069 52 : argc = orig_argc;
1070 52 : argv = orig_argv;
1071 52 : pargs.argc = &argc;
1072 52 : pargs.argv = &argv;
1073 52 : pargs.flags= 1; /* do not remove the args */
1074 : next_pass:
1075 100 : if (configname)
1076 : {
1077 52 : configlineno = 0;
1078 52 : configfp = fopen (configname, "r");
1079 52 : if (!configfp)
1080 : {
1081 4 : if (default_config)
1082 : {
1083 4 : if( parse_debug )
1084 0 : log_info (_("Note: no default option file '%s'\n"),
1085 : configname );
1086 : /* Save the default conf file name so that
1087 : reread_configuration is able to test whether the
1088 : config file has been created in the meantime. */
1089 4 : xfree (config_filename);
1090 4 : config_filename = configname;
1091 4 : configname = NULL;
1092 : }
1093 : else
1094 : {
1095 0 : log_error (_("option file '%s': %s\n"),
1096 0 : configname, strerror(errno) );
1097 0 : exit(2);
1098 : }
1099 4 : xfree (configname);
1100 4 : configname = NULL;
1101 : }
1102 52 : if (parse_debug && configname )
1103 0 : log_info (_("reading options from '%s'\n"), configname );
1104 52 : default_config = 0;
1105 : }
1106 :
1107 634 : while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
1108 : {
1109 434 : if (parse_rereadable_options (&pargs, 0))
1110 178 : continue; /* Already handled */
1111 256 : switch (pargs.r_opt)
1112 : {
1113 0 : case aGPGConfList: gpgconf_list = 1; break;
1114 0 : case aGPGConfTest: gpgconf_list = 2; break;
1115 0 : case aUseStandardSocketP: gpgconf_list = 3; break;
1116 0 : case oBatch: opt.batch=1; break;
1117 :
1118 0 : case oDebugWait: debug_wait = pargs.r.ret_int; break;
1119 :
1120 : case oOptions:
1121 : /* config files may not be nested (silently ignore them) */
1122 0 : if (!configfp)
1123 : {
1124 0 : xfree(configname);
1125 0 : configname = xstrdup(pargs.r.ret_str);
1126 0 : goto next_pass;
1127 : }
1128 0 : break;
1129 0 : case oNoGreeting: /* Dummy option. */ break;
1130 0 : case oNoVerbose: opt.verbose = 0; break;
1131 0 : case oNoOptions: break; /* no-options */
1132 52 : case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1133 0 : case oNoDetach: nodetach = 1; break;
1134 0 : case oLogFile: logfile = pargs.r.ret_str; break;
1135 0 : case oCsh: csh_style = 1; break;
1136 0 : case oSh: csh_style = 0; break;
1137 0 : case oServer: pipe_server = 1; break;
1138 52 : case oDaemon: is_daemon = 1; break;
1139 0 : case oSupervised: is_supervised = 1; break;
1140 :
1141 0 : case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
1142 0 : case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
1143 0 : case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
1144 0 : case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
1145 0 : case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
1146 0 : break;
1147 0 : case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
1148 0 : break;
1149 :
1150 : case oUseStandardSocket:
1151 : case oNoUseStandardSocket:
1152 52 : obsolete_option (configname, configlineno, "use-standard-socket");
1153 52 : break;
1154 :
1155 : case oFakedSystemTime:
1156 : {
1157 0 : time_t faked_time = isotime2epoch (pargs.r.ret_str);
1158 0 : if (faked_time == (time_t)(-1))
1159 0 : faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1160 0 : gnupg_set_time (faked_time, 0);
1161 : }
1162 0 : break;
1163 :
1164 0 : case oKeepTTY: opt.keep_tty = 1; break;
1165 0 : case oKeepDISPLAY: opt.keep_display = 1; break;
1166 :
1167 : case oSSHSupport:
1168 48 : ssh_support = 1;
1169 48 : break;
1170 : case oPuttySupport:
1171 : # ifdef HAVE_W32_SYSTEM
1172 : putty_support = 1;
1173 : # endif
1174 0 : break;
1175 :
1176 : case oExtraSocket:
1177 0 : opt.extra_socket = 1; /* (1 = points into argv) */
1178 0 : socket_name_extra = pargs.r.ret_str;
1179 0 : break;
1180 :
1181 : case oBrowserSocket:
1182 0 : opt.browser_socket = 1; /* (1 = points into argv) */
1183 0 : socket_name_browser = pargs.r.ret_str;
1184 0 : break;
1185 :
1186 : case oDebugQuickRandom:
1187 : /* Only used by the first stage command line parser. */
1188 52 : break;
1189 :
1190 : case oWriteEnvFile:
1191 0 : obsolete_option (configname, configlineno, "write-env-file");
1192 0 : break;
1193 :
1194 0 : default : pargs.err = configfp? 1:2; break;
1195 : }
1196 : }
1197 100 : if (configfp)
1198 : {
1199 48 : fclose( configfp );
1200 48 : configfp = NULL;
1201 : /* Keep a copy of the name so that it can be read on SIGHUP. */
1202 48 : if (config_filename != configname)
1203 : {
1204 48 : xfree (config_filename);
1205 48 : config_filename = configname;
1206 : }
1207 48 : configname = NULL;
1208 48 : goto next_pass;
1209 : }
1210 :
1211 52 : xfree (configname);
1212 52 : configname = NULL;
1213 52 : if (log_get_errorcount(0))
1214 0 : exit(2);
1215 :
1216 52 : finalize_rereadable_options ();
1217 :
1218 : /* Print a warning if an argument looks like an option. */
1219 52 : if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1220 : {
1221 : int i;
1222 :
1223 52 : for (i=0; i < argc; i++)
1224 0 : if (argv[i][0] == '-' && argv[i][1] == '-')
1225 0 : log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1226 : }
1227 :
1228 : #ifdef ENABLE_NLS
1229 : /* gpg-agent usually does not output any messages because it runs in
1230 : the background. For log files it is acceptable to have messages
1231 : always encoded in utf-8. We switch here to utf-8, so that
1232 : commands like --help still give native messages. It is far
1233 : easier to switch only once instead of for every message and it
1234 : actually helps when more then one thread is active (avoids an
1235 : extra copy step). */
1236 52 : bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
1237 : #endif
1238 :
1239 52 : if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
1240 : {
1241 : /* We have been called without any command and thus we merely
1242 : check whether an agent is already running. We do this right
1243 : here so that we don't clobber a logfile with this check but
1244 : print the status directly to stderr. */
1245 0 : opt.debug = 0;
1246 0 : set_debug ();
1247 0 : check_for_running_agent (0);
1248 0 : agent_exit (0);
1249 : }
1250 :
1251 52 : if (is_supervised)
1252 : ;
1253 52 : else if (!opt.extra_socket)
1254 52 : opt.extra_socket = 1;
1255 0 : else if (socket_name_extra
1256 0 : && (!strcmp (socket_name_extra, "none")
1257 0 : || !strcmp (socket_name_extra, "/dev/null")))
1258 : {
1259 : /* User requested not to create this socket. */
1260 0 : opt.extra_socket = 0;
1261 0 : socket_name_extra = NULL;
1262 : }
1263 :
1264 52 : if (is_supervised)
1265 : ;
1266 52 : else if (!opt.browser_socket)
1267 52 : opt.browser_socket = 1;
1268 0 : else if (socket_name_browser
1269 0 : && (!strcmp (socket_name_browser, "none")
1270 0 : || !strcmp (socket_name_browser, "/dev/null")))
1271 : {
1272 : /* User requested not to create this socket. */
1273 0 : opt.browser_socket = 0;
1274 0 : socket_name_browser = NULL;
1275 : }
1276 :
1277 52 : set_debug ();
1278 :
1279 52 : if (atexit (cleanup))
1280 : {
1281 0 : log_error ("atexit failed\n");
1282 0 : cleanup ();
1283 0 : exit (1);
1284 : }
1285 :
1286 : /* Try to create missing directories. */
1287 52 : create_directories ();
1288 :
1289 52 : if (debug_wait && pipe_server)
1290 : {
1291 0 : thread_init_once ();
1292 0 : log_debug ("waiting for debugger - my pid is %u .....\n",
1293 0 : (unsigned int)getpid());
1294 0 : gnupg_sleep (debug_wait);
1295 0 : log_debug ("... okay\n");
1296 : }
1297 :
1298 52 : if (gpgconf_list == 3)
1299 : {
1300 : /* We now use the standard socket always - return true for
1301 : backward compatibility. */
1302 0 : agent_exit (0);
1303 : }
1304 52 : else if (gpgconf_list == 2)
1305 0 : agent_exit (0);
1306 52 : else if (gpgconf_list)
1307 : {
1308 : char *filename;
1309 : char *filename_esc;
1310 :
1311 : /* List options and default values in the GPG Conf format. */
1312 0 : filename = make_filename (gnupg_homedir (),
1313 : GPG_AGENT_NAME EXTSEP_S "conf", NULL);
1314 0 : filename_esc = percent_escape (filename, NULL);
1315 :
1316 0 : es_printf ("%s-%s.conf:%lu:\"%s\n",
1317 : GPGCONF_NAME, GPG_AGENT_NAME,
1318 : GC_OPT_FLAG_DEFAULT, filename_esc);
1319 0 : xfree (filename);
1320 0 : xfree (filename_esc);
1321 :
1322 0 : es_printf ("verbose:%lu:\n"
1323 : "quiet:%lu:\n"
1324 : "debug-level:%lu:\"none:\n"
1325 : "log-file:%lu:\n",
1326 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1327 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
1328 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1329 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
1330 0 : es_printf ("default-cache-ttl:%lu:%d:\n",
1331 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
1332 0 : es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
1333 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
1334 0 : es_printf ("max-cache-ttl:%lu:%d:\n",
1335 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
1336 0 : es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
1337 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
1338 0 : es_printf ("enforce-passphrase-constraints:%lu:\n",
1339 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1340 0 : es_printf ("min-passphrase-len:%lu:%d:\n",
1341 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
1342 0 : es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
1343 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1344 : MIN_PASSPHRASE_NONALPHA);
1345 0 : es_printf ("check-passphrase-pattern:%lu:\n",
1346 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1347 0 : es_printf ("max-passphrase-days:%lu:%d:\n",
1348 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
1349 : MAX_PASSPHRASE_DAYS);
1350 0 : es_printf ("enable-passphrase-history:%lu:\n",
1351 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1352 0 : es_printf ("no-grab:%lu:\n",
1353 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1354 0 : es_printf ("ignore-cache-for-signing:%lu:\n",
1355 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1356 0 : es_printf ("no-allow-external-cache:%lu:\n",
1357 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1358 0 : es_printf ("no-allow-mark-trusted:%lu:\n",
1359 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1360 0 : es_printf ("disable-scdaemon:%lu:\n",
1361 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1362 0 : es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
1363 : #ifdef HAVE_W32_SYSTEM
1364 : es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
1365 : #endif
1366 0 : es_printf ("no-allow-loopback-pinentry:%lu:\n",
1367 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1368 0 : es_printf ("allow-emacs-pinentry:%lu:\n",
1369 : GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
1370 0 : es_printf ("pinentry-timeout:%lu:0:\n",
1371 : GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
1372 :
1373 0 : agent_exit (0);
1374 : }
1375 :
1376 : /* Now start with logging to a file if this is desired. */
1377 52 : if (logfile)
1378 : {
1379 0 : log_set_file (logfile);
1380 0 : log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1381 : | GPGRT_LOG_WITH_TIME
1382 : | GPGRT_LOG_WITH_PID));
1383 0 : current_logfile = xstrdup (logfile);
1384 : }
1385 :
1386 : /* Make sure that we have a default ttyname. */
1387 52 : if (!default_ttyname && gnupg_ttyname (1))
1388 0 : default_ttyname = xstrdup (gnupg_ttyname (1));
1389 52 : if (!default_ttytype && getenv ("TERM"))
1390 52 : default_ttytype = xstrdup (getenv ("TERM"));
1391 :
1392 :
1393 52 : if (pipe_server)
1394 : {
1395 : /* This is the simple pipe based server */
1396 : ctrl_t ctrl;
1397 :
1398 0 : initialize_modules ();
1399 :
1400 0 : ctrl = xtrycalloc (1, sizeof *ctrl);
1401 0 : if (!ctrl)
1402 : {
1403 0 : log_error ("error allocating connection control data: %s\n",
1404 0 : strerror (errno) );
1405 0 : agent_exit (1);
1406 : }
1407 0 : ctrl->session_env = session_env_new ();
1408 0 : if (!ctrl->session_env)
1409 : {
1410 0 : log_error ("error allocating session environment block: %s\n",
1411 0 : strerror (errno) );
1412 0 : xfree (ctrl);
1413 0 : agent_exit (1);
1414 : }
1415 0 : agent_init_default_ctrl (ctrl);
1416 0 : start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
1417 0 : agent_deinit_default_ctrl (ctrl);
1418 0 : xfree (ctrl);
1419 : }
1420 52 : else if (is_supervised)
1421 : {
1422 : #ifndef HAVE_W32_SYSTEM
1423 : gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
1424 :
1425 0 : initialize_modules ();
1426 :
1427 : /* when supervised and sending logs to stderr, the process
1428 : supervisor should handle log entry metadata (pid, name,
1429 : timestamp) */
1430 0 : if (!logfile)
1431 0 : log_set_prefix (NULL, 0);
1432 :
1433 0 : log_info ("%s %s starting in supervised mode.\n",
1434 : strusage(11), strusage(13) );
1435 :
1436 : /* See below in "regular server mode" on why we remove certain
1437 : * envvars. */
1438 0 : if (!opt.keep_display)
1439 0 : gnupg_unsetenv ("DISPLAY");
1440 0 : gnupg_unsetenv ("INSIDE_EMACS");
1441 :
1442 : /* Virtually create the sockets. Note that we use -1 here
1443 : * because the whole thing works only on Unix. */
1444 0 : map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
1445 0 : if (fd == -1)
1446 0 : log_fatal ("no standard socket provided\n");
1447 :
1448 : #ifdef HAVE_SIGPROCMASK
1449 0 : if (startup_signal_mask_valid)
1450 : {
1451 0 : if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1452 0 : log_error ("error restoring signal mask: %s\n",
1453 0 : strerror (errno));
1454 : }
1455 : else
1456 0 : log_info ("no saved signal mask\n");
1457 : #endif /*HAVE_SIGPROCMASK*/
1458 :
1459 0 : log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
1460 : fd, fd_extra, fd_browser, fd_ssh);
1461 0 : handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1462 : #endif /*!HAVE_W32_SYSTEM*/
1463 : }
1464 52 : else if (!is_daemon)
1465 : ; /* NOTREACHED */
1466 : else
1467 : { /* Regular server mode */
1468 : gnupg_fd_t fd;
1469 52 : gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
1470 52 : gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
1471 52 : gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
1472 : #ifndef HAVE_W32_SYSTEM
1473 : pid_t pid;
1474 : #endif
1475 :
1476 : /* Remove the DISPLAY variable so that a pinentry does not
1477 : default to a specific display. There is still a default
1478 : display when gpg-agent was started using --display or a
1479 : client requested this using an OPTION command. Note, that we
1480 : don't do this when running in reverse daemon mode (i.e. when
1481 : exec the program given as arguments). */
1482 : #ifndef HAVE_W32_SYSTEM
1483 52 : if (!opt.keep_display && !argc)
1484 52 : gnupg_unsetenv ("DISPLAY");
1485 : #endif
1486 :
1487 : /* Remove the INSIDE_EMACS variable so that a pinentry does not
1488 : always try to interact with Emacs. The variable is set when
1489 : a client requested this using an OPTION command. */
1490 52 : gnupg_unsetenv ("INSIDE_EMACS");
1491 :
1492 : /* Create the sockets. */
1493 52 : socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
1494 52 : fd = create_server_socket (socket_name, 1, 0,
1495 : &redir_socket_name, &socket_nonce);
1496 :
1497 52 : if (opt.extra_socket)
1498 : {
1499 52 : if (socket_name_extra)
1500 0 : socket_name_extra = create_socket_name (socket_name_extra, 0);
1501 : else
1502 52 : socket_name_extra = create_socket_name
1503 : /**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1);
1504 52 : opt.extra_socket = 2; /* Indicate that it has been malloced. */
1505 52 : fd_extra = create_server_socket (socket_name_extra, 0, 0,
1506 : &redir_socket_name_extra,
1507 : &socket_nonce_extra);
1508 : }
1509 :
1510 52 : if (opt.browser_socket)
1511 : {
1512 52 : if (socket_name_browser)
1513 0 : socket_name_browser = create_socket_name (socket_name_browser, 0);
1514 : else
1515 52 : socket_name_browser= create_socket_name
1516 : /**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1);
1517 52 : opt.browser_socket = 2; /* Indicate that it has been malloced. */
1518 52 : fd_browser = create_server_socket (socket_name_browser, 0, 0,
1519 : &redir_socket_name_browser,
1520 : &socket_nonce_browser);
1521 : }
1522 :
1523 52 : socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
1524 52 : fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
1525 : &redir_socket_name_ssh,
1526 : &socket_nonce_ssh);
1527 :
1528 : /* If we are going to exec a program in the parent, we record
1529 : the PID, so that the child may check whether the program is
1530 : still alive. */
1531 52 : if (argc)
1532 0 : parent_pid = getpid ();
1533 :
1534 52 : fflush (NULL);
1535 :
1536 : #ifdef HAVE_W32_SYSTEM
1537 :
1538 : (void)csh_style;
1539 : (void)nodetach;
1540 : initialize_modules ();
1541 :
1542 : #else /*!HAVE_W32_SYSTEM*/
1543 :
1544 52 : pid = fork ();
1545 104 : if (pid == (pid_t)-1)
1546 : {
1547 0 : log_fatal ("fork failed: %s\n", strerror (errno) );
1548 : exit (1);
1549 : }
1550 104 : else if (pid)
1551 : { /* We are the parent */
1552 : char *infostr_ssh_sock, *infostr_ssh_valid;
1553 :
1554 : /* Close the socket FD. */
1555 52 : close (fd);
1556 :
1557 : /* The signal mask might not be correct right now and thus
1558 : we restore it. That is not strictly necessary but some
1559 : programs falsely assume a cleared signal mask. */
1560 :
1561 : #ifdef HAVE_SIGPROCMASK
1562 52 : if (startup_signal_mask_valid)
1563 : {
1564 52 : if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
1565 0 : log_error ("error restoring signal mask: %s\n",
1566 0 : strerror (errno));
1567 : }
1568 : else
1569 0 : log_info ("no saved signal mask\n");
1570 : #endif /*HAVE_SIGPROCMASK*/
1571 :
1572 : /* Create the SSH info string if enabled. */
1573 52 : if (ssh_support)
1574 : {
1575 48 : if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
1576 : socket_name_ssh) < 0)
1577 : {
1578 0 : log_error ("out of core\n");
1579 0 : kill (pid, SIGTERM);
1580 0 : exit (1);
1581 : }
1582 48 : if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
1583 48 : (unsigned long)getpid()) < 0)
1584 : {
1585 0 : log_error ("out of core\n");
1586 0 : kill (pid, SIGTERM);
1587 0 : exit (1);
1588 : }
1589 : }
1590 :
1591 52 : *socket_name = 0; /* Don't let cleanup() remove the socket -
1592 : the child should do this from now on */
1593 52 : if (opt.extra_socket)
1594 52 : *socket_name_extra = 0;
1595 52 : if (opt.browser_socket)
1596 52 : *socket_name_browser = 0;
1597 52 : *socket_name_ssh = 0;
1598 :
1599 52 : if (argc)
1600 : { /* Run the program given on the commandline. */
1601 0 : if (ssh_support && (putenv (infostr_ssh_sock)
1602 0 : || putenv (infostr_ssh_valid)))
1603 : {
1604 0 : log_error ("failed to set environment: %s\n",
1605 0 : strerror (errno) );
1606 0 : kill (pid, SIGTERM );
1607 0 : exit (1);
1608 : }
1609 :
1610 : /* Close all the file descriptors except the standard
1611 : ones and those open at startup. We explicitly don't
1612 : close 0,1,2 in case something went wrong collecting
1613 : them at startup. */
1614 0 : close_all_fds (3, startup_fd_list);
1615 :
1616 : /* Run the command. */
1617 0 : execvp (argv[0], argv);
1618 0 : log_error ("failed to run the command: %s\n", strerror (errno));
1619 0 : kill (pid, SIGTERM);
1620 0 : exit (1);
1621 : }
1622 : else
1623 : {
1624 : /* Print the environment string, so that the caller can use
1625 : shell's eval to set it */
1626 52 : if (csh_style)
1627 : {
1628 0 : if (ssh_support)
1629 : {
1630 0 : *strchr (infostr_ssh_sock, '=') = ' ';
1631 0 : es_printf ("setenv %s;\n", infostr_ssh_sock);
1632 : }
1633 : }
1634 : else
1635 : {
1636 52 : if (ssh_support)
1637 : {
1638 48 : es_printf ("%s; export SSH_AUTH_SOCK;\n",
1639 : infostr_ssh_sock);
1640 : }
1641 : }
1642 52 : if (ssh_support)
1643 : {
1644 48 : xfree (infostr_ssh_sock);
1645 48 : xfree (infostr_ssh_valid);
1646 : }
1647 52 : exit (0);
1648 : }
1649 : /*NOTREACHED*/
1650 : } /* End parent */
1651 :
1652 : /*
1653 : This is the child
1654 : */
1655 :
1656 52 : initialize_modules ();
1657 :
1658 : /* Detach from tty and put process into a new session */
1659 52 : if (!nodetach )
1660 : {
1661 : int i;
1662 : unsigned int oldflags;
1663 :
1664 : /* Close stdin, stdout and stderr unless it is the log stream */
1665 208 : for (i=0; i <= 2; i++)
1666 : {
1667 156 : if (!log_test_fd (i) && i != fd )
1668 : {
1669 104 : if ( ! close (i)
1670 104 : && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1671 : {
1672 0 : log_error ("failed to open '%s': %s\n",
1673 0 : "/dev/null", strerror (errno));
1674 0 : cleanup ();
1675 0 : exit (1);
1676 : }
1677 : }
1678 : }
1679 52 : if (setsid() == -1)
1680 : {
1681 0 : log_error ("setsid() failed: %s\n", strerror(errno) );
1682 0 : cleanup ();
1683 0 : exit (1);
1684 : }
1685 :
1686 52 : log_get_prefix (&oldflags);
1687 52 : log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1688 52 : opt.running_detached = 1;
1689 : }
1690 :
1691 52 : if (chdir("/"))
1692 : {
1693 0 : log_error ("chdir to / failed: %s\n", strerror (errno));
1694 0 : exit (1);
1695 : }
1696 :
1697 : {
1698 : struct sigaction sa;
1699 :
1700 52 : sa.sa_handler = SIG_IGN;
1701 52 : sigemptyset (&sa.sa_mask);
1702 52 : sa.sa_flags = 0;
1703 52 : sigaction (SIGPIPE, &sa, NULL);
1704 : }
1705 : #endif /*!HAVE_W32_SYSTEM*/
1706 :
1707 52 : log_info ("%s %s started\n", strusage(11), strusage(13) );
1708 52 : handle_connections (fd, fd_extra, fd_browser, fd_ssh);
1709 4 : assuan_sock_close (fd);
1710 : }
1711 :
1712 4 : return 0;
1713 : }
1714 :
1715 :
1716 : /* Exit entry point. This function should be called instead of a
1717 : plain exit. */
1718 : void
1719 48 : agent_exit (int rc)
1720 : {
1721 : /*FIXME: update_random_seed_file();*/
1722 :
1723 : /* We run our cleanup handler because that may close cipher contexts
1724 : stored in secure memory and thus this needs to be done before we
1725 : explicitly terminate secure memory. */
1726 48 : cleanup ();
1727 :
1728 : #if 1
1729 : /* at this time a bit annoying */
1730 48 : if (opt.debug & DBG_MEMSTAT_VALUE)
1731 : {
1732 0 : gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1733 0 : gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1734 : }
1735 48 : if (opt.debug)
1736 0 : gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1737 : #endif
1738 48 : gcry_control (GCRYCTL_TERM_SECMEM );
1739 48 : rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1740 48 : exit (rc);
1741 : }
1742 :
1743 :
1744 : /* This is our callback function for gcrypt progress messages. It is
1745 : set once at startup and dispatches progress messages to the
1746 : corresponding threads of the agent. */
1747 : static void
1748 449 : agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
1749 : int current, int total)
1750 : {
1751 : struct progress_dispatch_s *dispatch;
1752 449 : npth_t mytid = npth_self ();
1753 :
1754 : (void)data;
1755 :
1756 449 : for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1757 449 : if (dispatch->ctrl && dispatch->tid == mytid)
1758 449 : break;
1759 449 : if (dispatch && dispatch->cb)
1760 449 : dispatch->cb (dispatch->ctrl, what, printchar, current, total);
1761 :
1762 : /* Libgcrypt < 1.8 does not know about nPth and thus when it reads
1763 : * from /dev/random this will block the process. To mitigate this
1764 : * problem we take a short nap when Libgcrypt tells us that it needs
1765 : * more entropy. This way other threads have chance to run. */
1766 : #if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */
1767 449 : if (what && !strcmp (what, "need_entropy"))
1768 0 : npth_usleep (100000); /* 100ms */
1769 : #endif
1770 449 : }
1771 :
1772 :
1773 : /* If a progress dispatcher callback has been associated with the
1774 : * current connection unregister it. */
1775 : static void
1776 740 : unregister_progress_cb (void)
1777 : {
1778 : struct progress_dispatch_s *dispatch;
1779 740 : npth_t mytid = npth_self ();
1780 :
1781 754 : for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1782 744 : if (dispatch->ctrl && dispatch->tid == mytid)
1783 730 : break;
1784 740 : if (dispatch)
1785 : {
1786 730 : dispatch->ctrl = NULL;
1787 730 : dispatch->cb = NULL;
1788 : }
1789 740 : }
1790 :
1791 :
1792 : /* Setup a progress callback CB for the current connection. Using a
1793 : * CB of NULL disables the callback. */
1794 : void
1795 778 : agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
1796 : int printchar, int current, int total),
1797 : ctrl_t ctrl)
1798 : {
1799 : struct progress_dispatch_s *dispatch, *firstfree;
1800 778 : npth_t mytid = npth_self ();
1801 :
1802 778 : firstfree = NULL;
1803 1511 : for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
1804 : {
1805 733 : if (dispatch->ctrl && dispatch->tid == mytid)
1806 0 : break;
1807 733 : if (!dispatch->ctrl && !firstfree)
1808 725 : firstfree = dispatch;
1809 : }
1810 778 : if (!dispatch) /* None allocated: Reuse or allocate a new one. */
1811 : {
1812 778 : if (firstfree)
1813 : {
1814 725 : dispatch = firstfree;
1815 : }
1816 53 : else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
1817 : {
1818 53 : dispatch->next = progress_dispatch_list;
1819 53 : progress_dispatch_list = dispatch;
1820 : }
1821 : else
1822 : {
1823 0 : log_error ("error allocating new progress dispatcher slot: %s\n",
1824 : gpg_strerror (gpg_error_from_syserror ()));
1825 778 : return;
1826 : }
1827 778 : dispatch->ctrl = ctrl;
1828 778 : dispatch->tid = mytid;
1829 : }
1830 :
1831 778 : dispatch->cb = cb;
1832 : }
1833 :
1834 :
1835 : /* Each thread has its own local variables conveyed by a control
1836 : structure usually identified by an argument named CTRL. This
1837 : function is called immediately after allocating the control
1838 : structure. Its purpose is to setup the default values for that
1839 : structure. Note that some values may have already been set. */
1840 : static void
1841 788 : agent_init_default_ctrl (ctrl_t ctrl)
1842 : {
1843 788 : assert (ctrl->session_env);
1844 :
1845 : /* Note we ignore malloc errors because we can't do much about it
1846 : and the request will fail anyway shortly after this
1847 : initialization. */
1848 788 : session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
1849 788 : session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
1850 788 : session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
1851 788 : session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
1852 788 : session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
1853 :
1854 788 : if (ctrl->lc_ctype)
1855 0 : xfree (ctrl->lc_ctype);
1856 788 : ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
1857 :
1858 788 : if (ctrl->lc_messages)
1859 0 : xfree (ctrl->lc_messages);
1860 1576 : ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
1861 788 : /**/ : NULL;
1862 788 : ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
1863 788 : }
1864 :
1865 :
1866 : /* Release all resources allocated by default in the control
1867 : structure. This is the counterpart to agent_init_default_ctrl. */
1868 : static void
1869 740 : agent_deinit_default_ctrl (ctrl_t ctrl)
1870 : {
1871 740 : unregister_progress_cb ();
1872 740 : session_env_release (ctrl->session_env);
1873 :
1874 740 : if (ctrl->lc_ctype)
1875 10 : xfree (ctrl->lc_ctype);
1876 740 : if (ctrl->lc_messages)
1877 0 : xfree (ctrl->lc_messages);
1878 740 : }
1879 :
1880 :
1881 : /* Because the ssh protocol does not send us information about the
1882 : current TTY setting, we use this function to use those from startup
1883 : or those explicitly set. This is also used for the restricted mode
1884 : where we ignore requests to change the environment. */
1885 : gpg_error_t
1886 10 : agent_copy_startup_env (ctrl_t ctrl)
1887 : {
1888 : static const char *names[] =
1889 : {"GPG_TTY", "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL};
1890 10 : gpg_error_t err = 0;
1891 : int idx;
1892 : const char *value;
1893 :
1894 60 : for (idx=0; !err && names[idx]; idx++)
1895 50 : if ((value = session_env_getenv (opt.startup_env, names[idx])))
1896 20 : err = session_env_setenv (ctrl->session_env, names[idx], value);
1897 :
1898 10 : if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
1899 10 : if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
1900 0 : err = gpg_error_from_syserror ();
1901 :
1902 10 : if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
1903 0 : if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
1904 0 : err = gpg_error_from_syserror ();
1905 :
1906 10 : if (err)
1907 0 : log_error ("error setting default session environment: %s\n",
1908 : gpg_strerror (err));
1909 :
1910 10 : return err;
1911 : }
1912 :
1913 :
1914 : /* Reread parts of the configuration. Note, that this function is
1915 : obviously not thread-safe and should only be called from the PTH
1916 : signal handler.
1917 :
1918 : Fixme: Due to the way the argument parsing works, we create a
1919 : memory leak here for all string type arguments. There is currently
1920 : no clean way to tell whether the memory for the argument has been
1921 : allocated or points into the process' original arguments. Unless
1922 : we have a mechanism to tell this, we need to live on with this. */
1923 : static void
1924 0 : reread_configuration (void)
1925 : {
1926 : ARGPARSE_ARGS pargs;
1927 : FILE *fp;
1928 0 : unsigned int configlineno = 0;
1929 : int dummy;
1930 :
1931 0 : if (!config_filename)
1932 0 : return; /* No config file. */
1933 :
1934 0 : fp = fopen (config_filename, "r");
1935 0 : if (!fp)
1936 : {
1937 0 : log_info (_("option file '%s': %s\n"),
1938 0 : config_filename, strerror(errno) );
1939 0 : return;
1940 : }
1941 :
1942 0 : parse_rereadable_options (NULL, 1); /* Start from the default values. */
1943 :
1944 0 : memset (&pargs, 0, sizeof pargs);
1945 0 : dummy = 0;
1946 0 : pargs.argc = &dummy;
1947 0 : pargs.flags = 1; /* do not remove the args */
1948 0 : while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
1949 : {
1950 0 : if (pargs.r_opt < -1)
1951 0 : pargs.err = 1; /* Print a warning. */
1952 : else /* Try to parse this option - ignore unchangeable ones. */
1953 0 : parse_rereadable_options (&pargs, 1);
1954 : }
1955 0 : fclose (fp);
1956 0 : finalize_rereadable_options ();
1957 0 : set_debug ();
1958 : }
1959 :
1960 :
1961 : /* Return the file name of the socket we are using for native
1962 : requests. */
1963 : const char *
1964 13 : get_agent_socket_name (void)
1965 : {
1966 13 : const char *s = socket_name;
1967 :
1968 13 : return (s && *s)? s : NULL;
1969 : }
1970 :
1971 : /* Return the file name of the socket we are using for SSH
1972 : requests. */
1973 : const char *
1974 0 : get_agent_ssh_socket_name (void)
1975 : {
1976 0 : const char *s = socket_name_ssh;
1977 :
1978 0 : return (s && *s)? s : NULL;
1979 : }
1980 :
1981 :
1982 : /* Return the number of active connections. */
1983 : int
1984 0 : get_agent_active_connection_count (void)
1985 : {
1986 0 : return active_connections;
1987 : }
1988 :
1989 :
1990 : /* Under W32, this function returns the handle of the scdaemon
1991 : notification event. Calling it the first time creates that
1992 : event. */
1993 : #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
1994 : void *
1995 : get_agent_scd_notify_event (void)
1996 : {
1997 : static HANDLE the_event = INVALID_HANDLE_VALUE;
1998 :
1999 : if (the_event == INVALID_HANDLE_VALUE)
2000 : {
2001 : HANDLE h, h2;
2002 : SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
2003 :
2004 : /* We need to use a manual reset event object due to the way our
2005 : w32-pth wait function works: If we would use an automatic
2006 : reset event we are not able to figure out which handle has
2007 : been signaled because at the time we single out the signaled
2008 : handles using WFSO the event has already been reset due to
2009 : the WFMO. */
2010 : h = CreateEvent (&sa, TRUE, FALSE, NULL);
2011 : if (!h)
2012 : log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
2013 : else if (!DuplicateHandle (GetCurrentProcess(), h,
2014 : GetCurrentProcess(), &h2,
2015 : EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
2016 : {
2017 : log_error ("setting syncronize for scd notify event failed: %s\n",
2018 : w32_strerror (-1) );
2019 : CloseHandle (h);
2020 : }
2021 : else
2022 : {
2023 : CloseHandle (h);
2024 : the_event = h2;
2025 : }
2026 : }
2027 :
2028 : return the_event;
2029 : }
2030 : #endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
2031 :
2032 :
2033 :
2034 : /* Create a name for the socket in the home directory as using
2035 : STANDARD_NAME. We also check for valid characters as well as
2036 : against a maximum allowed length for a unix domain socket is done.
2037 : The function terminates the process in case of an error. Returns:
2038 : Pointer to an allocated string with the absolute name of the socket
2039 : used. */
2040 : static char *
2041 208 : create_socket_name (char *standard_name, int with_homedir)
2042 : {
2043 : char *name;
2044 :
2045 208 : if (with_homedir)
2046 208 : name = make_filename (gnupg_socketdir (), standard_name, NULL);
2047 : else
2048 0 : name = make_filename (standard_name, NULL);
2049 208 : if (strchr (name, PATHSEP_C))
2050 : {
2051 0 : log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
2052 0 : agent_exit (2);
2053 : }
2054 208 : return name;
2055 : }
2056 :
2057 :
2058 :
2059 : /* Create a Unix domain socket with NAME. Returns the file descriptor
2060 : or terminates the process in case of an error. Note that this
2061 : function needs to be used for the regular socket first (indicated
2062 : by PRIMARY) and only then for the extra and the ssh sockets. If
2063 : the socket has been redirected the name of the real socket is
2064 : stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
2065 : Cygwin compatible socket is created (Windows only). */
2066 : static gnupg_fd_t
2067 208 : create_server_socket (char *name, int primary, int cygwin,
2068 : char **r_redir_name, assuan_sock_nonce_t *nonce)
2069 : {
2070 : struct sockaddr *addr;
2071 : struct sockaddr_un *unaddr;
2072 : socklen_t len;
2073 : gnupg_fd_t fd;
2074 : int rc;
2075 :
2076 208 : xfree (*r_redir_name);
2077 208 : *r_redir_name = NULL;
2078 :
2079 208 : fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
2080 208 : if (fd == ASSUAN_INVALID_FD)
2081 : {
2082 0 : log_error (_("can't create socket: %s\n"), strerror (errno));
2083 0 : *name = 0; /* Inhibit removal of the socket by cleanup(). */
2084 0 : agent_exit (2);
2085 : }
2086 :
2087 208 : if (cygwin)
2088 52 : assuan_sock_set_flag (fd, "cygwin", 1);
2089 :
2090 208 : unaddr = xmalloc (sizeof *unaddr);
2091 208 : addr = (struct sockaddr*)unaddr;
2092 :
2093 : {
2094 : int redirected;
2095 :
2096 208 : if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
2097 : {
2098 0 : if (errno == ENAMETOOLONG)
2099 0 : log_error (_("socket name '%s' is too long\n"), name);
2100 : else
2101 0 : log_error ("error preparing socket '%s': %s\n",
2102 : name, gpg_strerror (gpg_error_from_syserror ()));
2103 0 : *name = 0; /* Inhibit removal of the socket by cleanup(). */
2104 0 : agent_exit (2);
2105 : }
2106 208 : if (redirected)
2107 : {
2108 0 : *r_redir_name = xstrdup (unaddr->sun_path);
2109 0 : if (opt.verbose)
2110 0 : log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
2111 : }
2112 : }
2113 :
2114 208 : len = SUN_LEN (unaddr);
2115 208 : rc = assuan_sock_bind (fd, addr, len);
2116 :
2117 : /* Our error code mapping on W32CE returns EEXIST thus we also test
2118 : for this. */
2119 208 : if (rc == -1
2120 0 : && (errno == EADDRINUSE
2121 : #ifdef HAVE_W32_SYSTEM
2122 : || errno == EEXIST
2123 : #endif
2124 : ))
2125 : {
2126 : /* Check whether a gpg-agent is already running. We do this
2127 : test only if this is the primary socket. For secondary
2128 : sockets we assume that a test for gpg-agent has already been
2129 : done and reuse the requested socket. Testing the ssh-socket
2130 : is not possible because at this point, though we know the new
2131 : Assuan socket, the Assuan server and thus the ssh-agent
2132 : server is not yet operational; this would lead to a hang. */
2133 0 : if (primary && !check_for_running_agent (1))
2134 : {
2135 0 : log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
2136 0 : log_set_file (NULL);
2137 0 : log_error (_("a gpg-agent is already running - "
2138 : "not starting a new one\n"));
2139 0 : *name = 0; /* Inhibit removal of the socket by cleanup(). */
2140 0 : assuan_sock_close (fd);
2141 0 : agent_exit (2);
2142 : }
2143 0 : gnupg_remove (unaddr->sun_path);
2144 0 : rc = assuan_sock_bind (fd, addr, len);
2145 : }
2146 208 : if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
2147 0 : log_error (_("error getting nonce for the socket\n"));
2148 208 : if (rc == -1)
2149 : {
2150 : /* We use gpg_strerror here because it allows us to get strings
2151 : for some W32 socket error codes. */
2152 0 : log_error (_("error binding socket to '%s': %s\n"),
2153 0 : unaddr->sun_path,
2154 : gpg_strerror (gpg_error_from_syserror ()));
2155 :
2156 0 : assuan_sock_close (fd);
2157 0 : *name = 0; /* Inhibit removal of the socket by cleanup(). */
2158 0 : agent_exit (2);
2159 : }
2160 :
2161 208 : if (gnupg_chmod (unaddr->sun_path, "-rwx"))
2162 0 : log_error (_("can't set permissions of '%s': %s\n"),
2163 0 : unaddr->sun_path, strerror (errno));
2164 :
2165 208 : if (listen (FD2INT(fd), 5 ) == -1)
2166 : {
2167 0 : log_error (_("listen() failed: %s\n"), strerror (errno));
2168 0 : *name = 0; /* Inhibit removal of the socket by cleanup(). */
2169 0 : assuan_sock_close (fd);
2170 0 : agent_exit (2);
2171 : }
2172 :
2173 208 : if (opt.verbose)
2174 0 : log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
2175 :
2176 208 : return fd;
2177 : }
2178 :
2179 :
2180 : /* Check that the directory for storing the private keys exists and
2181 : create it if not. This function won't fail as it is only a
2182 : convenience function and not strictly necessary. */
2183 : static void
2184 52 : create_private_keys_directory (const char *home)
2185 : {
2186 : char *fname;
2187 : struct stat statbuf;
2188 :
2189 52 : fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
2190 52 : if (stat (fname, &statbuf) && errno == ENOENT)
2191 : {
2192 14 : if (gnupg_mkdir (fname, "-rwx"))
2193 0 : log_error (_("can't create directory '%s': %s\n"),
2194 0 : fname, strerror (errno) );
2195 14 : else if (!opt.quiet)
2196 14 : log_info (_("directory '%s' created\n"), fname);
2197 : }
2198 52 : if (gnupg_chmod (fname, "-rwx"))
2199 0 : log_error (_("can't set permissions of '%s': %s\n"),
2200 0 : fname, strerror (errno));
2201 52 : xfree (fname);
2202 52 : }
2203 :
2204 :
2205 : /* Create the directory only if the supplied directory name is the
2206 : same as the default one. This way we avoid to create arbitrary
2207 : directories when a non-default home directory is used. To cope
2208 : with HOME, we compare only the suffix if we see that the default
2209 : homedir does start with a tilde. We don't stop here in case of
2210 : problems because other functions will throw an error anyway.*/
2211 : static void
2212 52 : create_directories (void)
2213 : {
2214 : struct stat statbuf;
2215 52 : const char *defhome = standard_homedir ();
2216 : char *home;
2217 :
2218 52 : home = make_filename (gnupg_homedir (), NULL);
2219 52 : if ( stat (home, &statbuf) )
2220 : {
2221 0 : if (errno == ENOENT)
2222 : {
2223 0 : if (
2224 : #ifdef HAVE_W32_SYSTEM
2225 : ( !compare_filenames (home, defhome) )
2226 : #else
2227 0 : (*defhome == '~'
2228 0 : && (strlen (home) >= strlen (defhome+1)
2229 0 : && !strcmp (home + strlen(home)
2230 0 : - strlen (defhome+1), defhome+1)))
2231 0 : || (*defhome != '~' && !strcmp (home, defhome) )
2232 : #endif
2233 : )
2234 : {
2235 0 : if (gnupg_mkdir (home, "-rwx"))
2236 0 : log_error (_("can't create directory '%s': %s\n"),
2237 0 : home, strerror (errno) );
2238 : else
2239 : {
2240 0 : if (!opt.quiet)
2241 0 : log_info (_("directory '%s' created\n"), home);
2242 0 : create_private_keys_directory (home);
2243 : }
2244 : }
2245 : }
2246 : else
2247 0 : log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
2248 : }
2249 52 : else if ( !S_ISDIR(statbuf.st_mode))
2250 : {
2251 0 : log_error (_("can't use '%s' as home directory\n"), home);
2252 : }
2253 : else /* exists and is a directory. */
2254 : {
2255 52 : create_private_keys_directory (home);
2256 : }
2257 52 : xfree (home);
2258 52 : }
2259 :
2260 :
2261 :
2262 : /* This is the worker for the ticker. It is called every few seconds
2263 : and may only do fast operations. */
2264 : static void
2265 20 : handle_tick (void)
2266 : {
2267 : static time_t last_minute;
2268 :
2269 20 : if (!last_minute)
2270 10 : last_minute = time (NULL);
2271 :
2272 : /* Check whether the scdaemon has died and cleanup in this case. */
2273 20 : agent_scd_check_aliveness ();
2274 :
2275 : /* If we are running as a child of another process, check whether
2276 : the parent is still alive and shutdown if not. */
2277 : #ifndef HAVE_W32_SYSTEM
2278 20 : if (parent_pid != (pid_t)(-1))
2279 : {
2280 0 : if (kill (parent_pid, 0))
2281 : {
2282 0 : shutdown_pending = 2;
2283 0 : log_info ("parent process died - shutting down\n");
2284 0 : log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2285 0 : cleanup ();
2286 0 : agent_exit (0);
2287 : }
2288 : }
2289 : #endif /*HAVE_W32_SYSTEM*/
2290 :
2291 : /* Code to be run from time to time. */
2292 : #if CHECK_OWN_SOCKET_INTERVAL > 0
2293 20 : if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
2294 : {
2295 0 : check_own_socket ();
2296 0 : last_minute = time (NULL);
2297 : }
2298 : #endif
2299 :
2300 20 : }
2301 :
2302 :
2303 : /* A global function which allows us to call the reload stuff from
2304 : other places too. This is only used when build for W32. */
2305 : void
2306 0 : agent_sighup_action (void)
2307 : {
2308 0 : log_info ("SIGHUP received - "
2309 : "re-reading configuration and flushing cache\n");
2310 :
2311 0 : agent_flush_cache ();
2312 0 : reread_configuration ();
2313 0 : agent_reload_trustlist ();
2314 : /* We flush the module name cache so that after installing a
2315 : "pinentry" binary that one can be used in case the
2316 : "pinentry-basic" fallback was in use. */
2317 0 : gnupg_module_name_flush_some ();
2318 0 : }
2319 :
2320 :
2321 : /* A helper function to handle SIGUSR2. */
2322 : static void
2323 0 : agent_sigusr2_action (void)
2324 : {
2325 0 : if (opt.verbose)
2326 0 : log_info ("SIGUSR2 received - updating card event counter\n");
2327 : /* Nothing to check right now. We only increment a counter. */
2328 0 : bump_card_eventcounter ();
2329 0 : }
2330 :
2331 :
2332 : #ifndef HAVE_W32_SYSTEM
2333 : /* The signal handler for this program. It is expected to be run in
2334 : its own trhead and not in the context of a signal handler. */
2335 : static void
2336 0 : handle_signal (int signo)
2337 : {
2338 0 : switch (signo)
2339 : {
2340 : #ifndef HAVE_W32_SYSTEM
2341 : case SIGHUP:
2342 0 : agent_sighup_action ();
2343 0 : break;
2344 :
2345 : case SIGUSR1:
2346 0 : log_info ("SIGUSR1 received - printing internal information:\n");
2347 : /* Fixme: We need to see how to integrate pth dumping into our
2348 : logging system. */
2349 : /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
2350 0 : agent_query_dump_state ();
2351 0 : agent_scd_dump_state ();
2352 0 : break;
2353 :
2354 : case SIGUSR2:
2355 0 : agent_sigusr2_action ();
2356 0 : break;
2357 :
2358 : case SIGTERM:
2359 0 : if (!shutdown_pending)
2360 0 : log_info ("SIGTERM received - shutting down ...\n");
2361 : else
2362 0 : log_info ("SIGTERM received - still %i open connections\n",
2363 : active_connections);
2364 0 : shutdown_pending++;
2365 0 : if (shutdown_pending > 2)
2366 : {
2367 0 : log_info ("shutdown forced\n");
2368 0 : log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2369 0 : cleanup ();
2370 0 : agent_exit (0);
2371 : }
2372 0 : break;
2373 :
2374 : case SIGINT:
2375 0 : log_info ("SIGINT received - immediate shutdown\n");
2376 0 : log_info( "%s %s stopped\n", strusage(11), strusage(13));
2377 0 : cleanup ();
2378 0 : agent_exit (0);
2379 : break;
2380 : #endif
2381 : default:
2382 0 : log_info ("signal %d received - no action defined\n", signo);
2383 : }
2384 0 : }
2385 : #endif
2386 :
2387 : /* Check the nonce on a new connection. This is a NOP unless we we
2388 : are using our Unix domain socket emulation under Windows. */
2389 : static int
2390 788 : check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
2391 : {
2392 788 : if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
2393 : {
2394 0 : log_info (_("error reading nonce on fd %d: %s\n"),
2395 0 : FD2INT(ctrl->thread_startup.fd), strerror (errno));
2396 0 : assuan_sock_close (ctrl->thread_startup.fd);
2397 0 : xfree (ctrl);
2398 0 : return -1;
2399 : }
2400 : else
2401 788 : return 0;
2402 : }
2403 :
2404 :
2405 : #ifdef HAVE_W32_SYSTEM
2406 : /* The window message processing function for Putty. Warning: This
2407 : code runs as a native Windows thread. Use of our own functions
2408 : needs to be bracket with pth_leave/pth_enter. */
2409 : static LRESULT CALLBACK
2410 : putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
2411 : {
2412 : int ret = 0;
2413 : int w32rc;
2414 : COPYDATASTRUCT *cds;
2415 : const char *mapfile;
2416 : HANDLE maphd;
2417 : PSID mysid = NULL;
2418 : PSID mapsid = NULL;
2419 : void *data = NULL;
2420 : PSECURITY_DESCRIPTOR psd = NULL;
2421 : ctrl_t ctrl = NULL;
2422 :
2423 : if (msg != WM_COPYDATA)
2424 : {
2425 : return DefWindowProc (hwnd, msg, wparam, lparam);
2426 : }
2427 :
2428 : cds = (COPYDATASTRUCT*)lparam;
2429 : if (cds->dwData != PUTTY_IPC_MAGIC)
2430 : return 0; /* Ignore data with the wrong magic. */
2431 : mapfile = cds->lpData;
2432 : if (!cds->cbData || mapfile[cds->cbData - 1])
2433 : return 0; /* Ignore empty and non-properly terminated strings. */
2434 :
2435 : if (DBG_IPC)
2436 : {
2437 : npth_protect ();
2438 : log_debug ("ssh map file '%s'", mapfile);
2439 : npth_unprotect ();
2440 : }
2441 :
2442 : maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
2443 : if (DBG_IPC)
2444 : {
2445 : npth_protect ();
2446 : log_debug ("ssh map handle %p\n", maphd);
2447 : npth_unprotect ();
2448 : }
2449 :
2450 : if (!maphd || maphd == INVALID_HANDLE_VALUE)
2451 : return 0;
2452 :
2453 : npth_protect ();
2454 :
2455 : mysid = w32_get_user_sid ();
2456 : if (!mysid)
2457 : {
2458 : log_error ("error getting my sid\n");
2459 : goto leave;
2460 : }
2461 :
2462 : w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
2463 : OWNER_SECURITY_INFORMATION,
2464 : &mapsid, NULL, NULL, NULL,
2465 : &psd);
2466 : if (w32rc)
2467 : {
2468 : log_error ("error getting sid of ssh map file: rc=%d", w32rc);
2469 : goto leave;
2470 : }
2471 :
2472 : if (DBG_IPC)
2473 : {
2474 : char *sidstr;
2475 :
2476 : if (!ConvertSidToStringSid (mysid, &sidstr))
2477 : sidstr = NULL;
2478 : log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
2479 : LocalFree (sidstr);
2480 : if (!ConvertSidToStringSid (mapsid, &sidstr))
2481 : sidstr = NULL;
2482 : log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
2483 : LocalFree (sidstr);
2484 : }
2485 :
2486 : if (!EqualSid (mysid, mapsid))
2487 : {
2488 : log_error ("ssh map file has a non-matching sid\n");
2489 : goto leave;
2490 : }
2491 :
2492 : data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
2493 : if (DBG_IPC)
2494 : log_debug ("ssh IPC buffer at %p\n", data);
2495 : if (!data)
2496 : goto leave;
2497 :
2498 : /* log_printhex ("request:", data, 20); */
2499 :
2500 : ctrl = xtrycalloc (1, sizeof *ctrl);
2501 : if (!ctrl)
2502 : {
2503 : log_error ("error allocating connection control data: %s\n",
2504 : strerror (errno) );
2505 : goto leave;
2506 : }
2507 : ctrl->session_env = session_env_new ();
2508 : if (!ctrl->session_env)
2509 : {
2510 : log_error ("error allocating session environment block: %s\n",
2511 : strerror (errno) );
2512 : goto leave;
2513 : }
2514 :
2515 : agent_init_default_ctrl (ctrl);
2516 : if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
2517 : ret = 1; /* Valid ssh message has been constructed. */
2518 : agent_deinit_default_ctrl (ctrl);
2519 : /* log_printhex (" reply:", data, 20); */
2520 :
2521 : leave:
2522 : xfree (ctrl);
2523 : if (data)
2524 : UnmapViewOfFile (data);
2525 : xfree (mapsid);
2526 : if (psd)
2527 : LocalFree (psd);
2528 : xfree (mysid);
2529 : CloseHandle (maphd);
2530 :
2531 : npth_unprotect ();
2532 :
2533 : return ret;
2534 : }
2535 : #endif /*HAVE_W32_SYSTEM*/
2536 :
2537 :
2538 : #ifdef HAVE_W32_SYSTEM
2539 : /* The thread handling Putty's IPC requests. */
2540 : static void *
2541 : putty_message_thread (void *arg)
2542 : {
2543 : WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
2544 : NULL, NULL, NULL, NULL, NULL, "Pageant"};
2545 : HWND hwnd;
2546 : MSG msg;
2547 :
2548 : (void)arg;
2549 :
2550 : if (opt.verbose)
2551 : log_info ("putty message loop thread started\n");
2552 :
2553 : /* The message loop runs as thread independent from our nPth system.
2554 : This also means that we need to make sure that we switch back to
2555 : our system before calling any no-windows function. */
2556 : npth_unprotect ();
2557 :
2558 : /* First create a window to make sure that a message queue exists
2559 : for this thread. */
2560 : if (!RegisterClass (&wndwclass))
2561 : {
2562 : npth_protect ();
2563 : log_error ("error registering Pageant window class");
2564 : return NULL;
2565 : }
2566 : hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
2567 : 0, 0, 0, 0,
2568 : HWND_MESSAGE, /* hWndParent */
2569 : NULL, /* hWndMenu */
2570 : NULL, /* hInstance */
2571 : NULL); /* lpParm */
2572 : if (!hwnd)
2573 : {
2574 : npth_protect ();
2575 : log_error ("error creating Pageant window");
2576 : return NULL;
2577 : }
2578 :
2579 : while (GetMessage(&msg, NULL, 0, 0))
2580 : {
2581 : TranslateMessage(&msg);
2582 : DispatchMessage(&msg);
2583 : }
2584 :
2585 : /* Back to nPth. */
2586 : npth_protect ();
2587 :
2588 : if (opt.verbose)
2589 : log_info ("putty message loop thread stopped\n");
2590 : return NULL;
2591 : }
2592 : #endif /*HAVE_W32_SYSTEM*/
2593 :
2594 :
2595 : static void *
2596 778 : do_start_connection_thread (ctrl_t ctrl)
2597 : {
2598 778 : active_connections++;
2599 778 : agent_init_default_ctrl (ctrl);
2600 778 : if (opt.verbose && !DBG_IPC)
2601 0 : log_info (_("handler 0x%lx for fd %d started\n"),
2602 : (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2603 :
2604 778 : start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
2605 730 : if (opt.verbose && !DBG_IPC)
2606 0 : log_info (_("handler 0x%lx for fd %d terminated\n"),
2607 : (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2608 :
2609 730 : agent_deinit_default_ctrl (ctrl);
2610 730 : xfree (ctrl);
2611 730 : active_connections--;
2612 730 : return NULL;
2613 : }
2614 :
2615 :
2616 : /* This is the standard connection thread's main function. */
2617 : static void *
2618 778 : start_connection_thread_std (void *arg)
2619 : {
2620 778 : ctrl_t ctrl = arg;
2621 :
2622 778 : if (check_nonce (ctrl, &socket_nonce))
2623 : {
2624 0 : log_error ("handler 0x%lx nonce check FAILED\n",
2625 : (unsigned long) npth_self());
2626 0 : return NULL;
2627 : }
2628 :
2629 778 : return do_start_connection_thread (ctrl);
2630 : }
2631 :
2632 :
2633 : /* This is the extra socket connection thread's main function. */
2634 : static void *
2635 0 : start_connection_thread_extra (void *arg)
2636 : {
2637 0 : ctrl_t ctrl = arg;
2638 :
2639 0 : if (check_nonce (ctrl, &socket_nonce_extra))
2640 : {
2641 0 : log_error ("handler 0x%lx nonce check FAILED\n",
2642 : (unsigned long) npth_self());
2643 0 : return NULL;
2644 : }
2645 :
2646 0 : ctrl->restricted = 1;
2647 0 : return do_start_connection_thread (ctrl);
2648 : }
2649 :
2650 :
2651 : /* This is the browser socket connection thread's main function. */
2652 : static void *
2653 0 : start_connection_thread_browser (void *arg)
2654 : {
2655 0 : ctrl_t ctrl = arg;
2656 :
2657 0 : if (check_nonce (ctrl, &socket_nonce_browser))
2658 : {
2659 0 : log_error ("handler 0x%lx nonce check FAILED\n",
2660 : (unsigned long) npth_self());
2661 0 : return NULL;
2662 : }
2663 :
2664 0 : ctrl->restricted = 2;
2665 0 : return do_start_connection_thread (ctrl);
2666 : }
2667 :
2668 :
2669 : /* This is the ssh connection thread's main function. */
2670 : static void *
2671 10 : start_connection_thread_ssh (void *arg)
2672 : {
2673 10 : ctrl_t ctrl = arg;
2674 :
2675 10 : if (check_nonce (ctrl, &socket_nonce_ssh))
2676 0 : return NULL;
2677 :
2678 10 : active_connections++;
2679 10 : agent_init_default_ctrl (ctrl);
2680 10 : if (opt.verbose)
2681 0 : log_info (_("ssh handler 0x%lx for fd %d started\n"),
2682 : (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2683 :
2684 10 : start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
2685 10 : if (opt.verbose)
2686 0 : log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
2687 : (unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
2688 :
2689 10 : agent_deinit_default_ctrl (ctrl);
2690 10 : xfree (ctrl);
2691 10 : active_connections--;
2692 10 : return NULL;
2693 : }
2694 :
2695 :
2696 : /* Connection handler loop. Wait for connection requests and spawn a
2697 : thread after accepting a connection. */
2698 : static void
2699 52 : handle_connections (gnupg_fd_t listen_fd,
2700 : gnupg_fd_t listen_fd_extra,
2701 : gnupg_fd_t listen_fd_browser,
2702 : gnupg_fd_t listen_fd_ssh)
2703 : {
2704 : gpg_error_t err;
2705 : npth_attr_t tattr;
2706 : struct sockaddr_un paddr;
2707 : socklen_t plen;
2708 : fd_set fdset, read_fdset;
2709 : int ret;
2710 : gnupg_fd_t fd;
2711 : int nfd;
2712 : int saved_errno;
2713 : struct timespec abstime;
2714 : struct timespec curtime;
2715 : struct timespec timeout;
2716 : #ifdef HAVE_W32_SYSTEM
2717 : HANDLE events[2];
2718 : unsigned int events_set;
2719 : #endif
2720 52 : int my_inotify_fd = -1;
2721 : struct {
2722 : const char *name;
2723 : void *(*func) (void *arg);
2724 : gnupg_fd_t l_fd;
2725 52 : } listentbl[] = {
2726 : { "std", start_connection_thread_std },
2727 : { "extra", start_connection_thread_extra },
2728 : { "browser", start_connection_thread_browser },
2729 : { "ssh", start_connection_thread_ssh }
2730 : };
2731 :
2732 :
2733 52 : ret = npth_attr_init(&tattr);
2734 52 : if (ret)
2735 0 : log_fatal ("error allocating thread attributes: %s\n",
2736 : strerror (ret));
2737 52 : npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2738 :
2739 : #ifndef HAVE_W32_SYSTEM
2740 52 : npth_sigev_init ();
2741 52 : npth_sigev_add (SIGHUP);
2742 52 : npth_sigev_add (SIGUSR1);
2743 52 : npth_sigev_add (SIGUSR2);
2744 52 : npth_sigev_add (SIGINT);
2745 52 : npth_sigev_add (SIGTERM);
2746 52 : npth_sigev_fini ();
2747 : #else
2748 : # ifdef HAVE_W32CE_SYSTEM
2749 : /* Use a dummy event. */
2750 : sigs = 0;
2751 : ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
2752 : # else
2753 : events[0] = get_agent_scd_notify_event ();
2754 : events[1] = INVALID_HANDLE_VALUE;
2755 : # endif
2756 : #endif
2757 :
2758 52 : if (disable_check_own_socket)
2759 0 : my_inotify_fd = -1;
2760 52 : else if ((err = gnupg_inotify_watch_socket (&my_inotify_fd, socket_name)))
2761 : {
2762 0 : if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
2763 0 : log_info ("error enabling fast daemon termination: %s\n",
2764 : gpg_strerror (err));
2765 : }
2766 :
2767 : /* On Windows we need to fire up a separate thread to listen for
2768 : requests from Putty (an SSH client), so we can replace Putty's
2769 : Pageant (its ssh-agent implementation). */
2770 : #ifdef HAVE_W32_SYSTEM
2771 : if (putty_support)
2772 : {
2773 : npth_t thread;
2774 :
2775 : ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
2776 : if (ret)
2777 : {
2778 : log_error ("error spawning putty message loop: %s\n", strerror (ret));
2779 : }
2780 : }
2781 : #endif /*HAVE_W32_SYSTEM*/
2782 :
2783 : /* Set a flag to tell call-scd.c that it may enable event
2784 : notifications. */
2785 52 : opt.sigusr2_enabled = 1;
2786 :
2787 52 : FD_ZERO (&fdset);
2788 52 : FD_SET (FD2INT (listen_fd), &fdset);
2789 52 : nfd = FD2INT (listen_fd);
2790 52 : if (listen_fd_extra != GNUPG_INVALID_FD)
2791 : {
2792 52 : FD_SET ( FD2INT(listen_fd_extra), &fdset);
2793 52 : if (FD2INT (listen_fd_extra) > nfd)
2794 52 : nfd = FD2INT (listen_fd_extra);
2795 : }
2796 52 : if (listen_fd_browser != GNUPG_INVALID_FD)
2797 : {
2798 52 : FD_SET ( FD2INT(listen_fd_browser), &fdset);
2799 52 : if (FD2INT (listen_fd_browser) > nfd)
2800 52 : nfd = FD2INT (listen_fd_browser);
2801 : }
2802 52 : if (listen_fd_ssh != GNUPG_INVALID_FD)
2803 : {
2804 52 : FD_SET ( FD2INT(listen_fd_ssh), &fdset);
2805 52 : if (FD2INT (listen_fd_ssh) > nfd)
2806 52 : nfd = FD2INT (listen_fd_ssh);
2807 : }
2808 52 : if (my_inotify_fd != -1)
2809 : {
2810 52 : FD_SET (my_inotify_fd, &fdset);
2811 52 : if (my_inotify_fd > nfd)
2812 52 : nfd = my_inotify_fd;
2813 : }
2814 :
2815 52 : listentbl[0].l_fd = listen_fd;
2816 52 : listentbl[1].l_fd = listen_fd_extra;
2817 52 : listentbl[2].l_fd = listen_fd_browser;
2818 52 : listentbl[3].l_fd = listen_fd_ssh;
2819 :
2820 52 : npth_clock_gettime (&abstime);
2821 52 : abstime.tv_sec += TIMERTICK_INTERVAL;
2822 :
2823 : for (;;)
2824 : {
2825 : /* Shutdown test. */
2826 938 : if (shutdown_pending)
2827 : {
2828 4 : if (active_connections == 0)
2829 4 : break; /* ready */
2830 :
2831 : /* Do not accept new connections but keep on running the
2832 : * loop to cope with the timer events.
2833 : *
2834 : * Note that we do not close the listening socket because a
2835 : * client trying to connect to that socket would instead
2836 : * restart a new dirmngr instance - which is unlikely the
2837 : * intention of a shutdown. */
2838 0 : FD_ZERO (&fdset);
2839 0 : nfd = -1;
2840 0 : if (my_inotify_fd != -1)
2841 : {
2842 0 : FD_SET (my_inotify_fd, &fdset);
2843 0 : nfd = my_inotify_fd;
2844 : }
2845 : }
2846 :
2847 : /* POSIX says that fd_set should be implemented as a structure,
2848 : thus a simple assignment is fine to copy the entire set. */
2849 934 : read_fdset = fdset;
2850 :
2851 934 : npth_clock_gettime (&curtime);
2852 934 : if (!(npth_timercmp (&curtime, &abstime, <)))
2853 : {
2854 : /* Timeout. */
2855 20 : handle_tick ();
2856 20 : npth_clock_gettime (&abstime);
2857 20 : abstime.tv_sec += TIMERTICK_INTERVAL;
2858 : }
2859 934 : npth_timersub (&abstime, &curtime, &timeout);
2860 :
2861 : #ifndef HAVE_W32_SYSTEM
2862 934 : ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2863 934 : npth_sigev_sigmask ());
2864 886 : saved_errno = errno;
2865 :
2866 : {
2867 : int signo;
2868 1772 : while (npth_sigev_get_pending (&signo))
2869 0 : handle_signal (signo);
2870 : }
2871 : #else
2872 : ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2873 : events, &events_set);
2874 : saved_errno = errno;
2875 :
2876 : /* This is valid even if npth_eselect returns an error. */
2877 : if (events_set & 1)
2878 : agent_sigusr2_action ();
2879 : #endif
2880 :
2881 886 : if (ret == -1 && saved_errno != EINTR)
2882 : {
2883 0 : log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2884 : strerror (saved_errno));
2885 0 : npth_sleep (1);
2886 0 : continue;
2887 : }
2888 886 : if (ret <= 0)
2889 : /* Interrupt or timeout. Will be handled when calculating the
2890 : next timeout. */
2891 20 : continue;
2892 :
2893 866 : if (!shutdown_pending)
2894 : {
2895 : int idx;
2896 : ctrl_t ctrl;
2897 : npth_t thread;
2898 :
2899 866 : if (my_inotify_fd != -1
2900 866 : && FD_ISSET (my_inotify_fd, &read_fdset)
2901 78 : && gnupg_inotify_has_name (my_inotify_fd, GPG_AGENT_SOCK_NAME))
2902 : {
2903 4 : shutdown_pending = 1;
2904 4 : log_info ("socket file has been removed - shutting down\n");
2905 : }
2906 :
2907 4330 : for (idx=0; idx < DIM(listentbl); idx++)
2908 : {
2909 3464 : if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
2910 0 : continue;
2911 3464 : if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
2912 2676 : continue;
2913 :
2914 788 : plen = sizeof paddr;
2915 788 : fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
2916 : (struct sockaddr *)&paddr, &plen));
2917 788 : if (fd == GNUPG_INVALID_FD)
2918 : {
2919 0 : log_error ("accept failed for %s: %s\n",
2920 0 : listentbl[idx].name, strerror (errno));
2921 : }
2922 788 : else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
2923 : {
2924 0 : log_error ("error allocating connection data for %s: %s\n",
2925 0 : listentbl[idx].name, strerror (errno) );
2926 0 : assuan_sock_close (fd);
2927 : }
2928 788 : else if ( !(ctrl->session_env = session_env_new ()))
2929 : {
2930 0 : log_error ("error allocating session env block for %s: %s\n",
2931 0 : listentbl[idx].name, strerror (errno) );
2932 0 : xfree (ctrl);
2933 0 : assuan_sock_close (fd);
2934 : }
2935 : else
2936 : {
2937 788 : ctrl->thread_startup.fd = fd;
2938 788 : ret = npth_create (&thread, &tattr,
2939 : listentbl[idx].func, ctrl);
2940 788 : if (ret)
2941 : {
2942 0 : log_error ("error spawning connection handler for %s:"
2943 : " %s\n", listentbl[idx].name, strerror (ret));
2944 0 : assuan_sock_close (fd);
2945 0 : xfree (ctrl);
2946 : }
2947 : }
2948 788 : fd = GNUPG_INVALID_FD;
2949 : }
2950 : }
2951 886 : }
2952 :
2953 4 : if (my_inotify_fd != -1)
2954 4 : close (my_inotify_fd);
2955 4 : cleanup ();
2956 4 : log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
2957 4 : npth_attr_destroy (&tattr);
2958 4 : }
2959 :
2960 :
2961 :
2962 : /* Helper for check_own_socket. */
2963 : static gpg_error_t
2964 0 : check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
2965 : {
2966 0 : membuf_t *mb = opaque;
2967 0 : put_membuf (mb, buffer, length);
2968 0 : return 0;
2969 : }
2970 :
2971 :
2972 : /* The thread running the actual check. We need to run this in a
2973 : separate thread so that check_own_thread can be called from the
2974 : timer tick. */
2975 : static void *
2976 0 : check_own_socket_thread (void *arg)
2977 : {
2978 : int rc;
2979 0 : char *sockname = arg;
2980 0 : assuan_context_t ctx = NULL;
2981 : membuf_t mb;
2982 : char *buffer;
2983 :
2984 0 : check_own_socket_running++;
2985 :
2986 0 : rc = assuan_new (&ctx);
2987 0 : if (rc)
2988 : {
2989 0 : log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
2990 0 : goto leave;
2991 : }
2992 0 : assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
2993 :
2994 0 : rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
2995 0 : if (rc)
2996 : {
2997 0 : log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
2998 0 : goto leave;
2999 : }
3000 :
3001 0 : init_membuf (&mb, 100);
3002 0 : rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
3003 : NULL, NULL, NULL, NULL);
3004 0 : put_membuf (&mb, "", 1);
3005 0 : buffer = get_membuf (&mb, NULL);
3006 0 : if (rc || !buffer)
3007 : {
3008 0 : log_error ("sending command \"%s\" to my own socket failed: %s\n",
3009 : "GETINFO pid", gpg_strerror (rc));
3010 0 : rc = 1;
3011 : }
3012 0 : else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
3013 : {
3014 0 : log_error ("socket is now serviced by another server\n");
3015 0 : rc = 1;
3016 : }
3017 0 : else if (opt.verbose > 1)
3018 0 : log_error ("socket is still served by this server\n");
3019 :
3020 0 : xfree (buffer);
3021 :
3022 : leave:
3023 0 : xfree (sockname);
3024 0 : if (ctx)
3025 0 : assuan_release (ctx);
3026 0 : if (rc)
3027 : {
3028 : /* We may not remove the socket as it is now in use by another
3029 : server. */
3030 0 : inhibit_socket_removal = 1;
3031 0 : shutdown_pending = 2;
3032 0 : log_info ("this process is useless - shutting down\n");
3033 : }
3034 0 : check_own_socket_running--;
3035 0 : return NULL;
3036 : }
3037 :
3038 :
3039 : /* Check whether we are still listening on our own socket. In case
3040 : another gpg-agent process started after us has taken ownership of
3041 : our socket, we would linger around without any real task. Thus we
3042 : better check once in a while whether we are really needed. */
3043 : static void
3044 0 : check_own_socket (void)
3045 : {
3046 : char *sockname;
3047 : npth_t thread;
3048 : npth_attr_t tattr;
3049 : int err;
3050 :
3051 0 : if (disable_check_own_socket)
3052 0 : return;
3053 :
3054 0 : if (check_own_socket_running || shutdown_pending)
3055 0 : return; /* Still running or already shutting down. */
3056 :
3057 0 : sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3058 0 : if (!sockname)
3059 0 : return; /* Out of memory. */
3060 :
3061 0 : err = npth_attr_init (&tattr);
3062 0 : if (err)
3063 0 : return;
3064 0 : npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
3065 0 : err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
3066 0 : if (err)
3067 0 : log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
3068 0 : npth_attr_destroy (&tattr);
3069 : }
3070 :
3071 :
3072 :
3073 : /* Figure out whether an agent is available and running. Prints an
3074 : error if not. If SILENT is true, no messages are printed.
3075 : Returns 0 if the agent is running. */
3076 : static int
3077 0 : check_for_running_agent (int silent)
3078 : {
3079 : gpg_error_t err;
3080 : char *sockname;
3081 0 : assuan_context_t ctx = NULL;
3082 :
3083 0 : sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
3084 0 : if (!sockname)
3085 0 : return gpg_error_from_syserror ();
3086 :
3087 0 : err = assuan_new (&ctx);
3088 0 : if (!err)
3089 0 : err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
3090 0 : xfree (sockname);
3091 0 : if (err)
3092 : {
3093 0 : if (!silent)
3094 0 : log_error (_("no gpg-agent running in this session\n"));
3095 :
3096 0 : if (ctx)
3097 0 : assuan_release (ctx);
3098 0 : return -1;
3099 : }
3100 :
3101 0 : if (!opt.quiet && !silent)
3102 0 : log_info ("gpg-agent running and available\n");
3103 :
3104 0 : assuan_release (ctx);
3105 0 : return 0;
3106 : }
|