1 /* asshelp.c - Helper functions for Assuan
2 * Copyright (C) 2002, 2004, 2007, 2009, 2010 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * This file is free software; you can redistribute it and/or modify
7 * it under the terms of either
9 * - the GNU Lesser General Public License as published by the Free
10 * Software Foundation; either version 3 of the License, or (at
11 * your option) any later version.
15 * - the GNU General Public License as published by the Free
16 * Software Foundation; either version 2 of the License, or (at
17 * your option) any later version.
19 * or both in parallel, as here.
21 * This file is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, see <https://www.gnu.org/licenses/>.
48 /* The type we use for lock_agent_spawning. */
49 #ifdef HAVE_W32_SYSTEM
50 # define lock_spawn_t HANDLE
52 # define lock_spawn_t dotlock_t
55 /* The time we wait until the agent or the dirmngr are ready for
56 operation after we started them before giving up. */
57 #ifdef HAVE_W32CE_SYSTEM
58 # define SECS_TO_WAIT_FOR_AGENT 30
59 # define SECS_TO_WAIT_FOR_DIRMNGR 30
61 # define SECS_TO_WAIT_FOR_AGENT 5
62 # define SECS_TO_WAIT_FOR_DIRMNGR 5
65 /* A bitfield that specifies the assuan categories to log. This is
66 identical to the default log handler of libassuan. We need to do
67 it ourselves because we use a custom log handler and want to use
68 the same assuan variables to select the categories to log. */
70 #define TEST_LOG_CAT(x) (!! (log_cats & (1 << (x - 1))))
72 /* The assuan log monitor used to temporary inhibit log messages from
74 static int (*my_log_monitor) (assuan_context_t ctx,
79 #define DLOG(m, ...) do{ \
80 int DLOG_se = errno; \
82 log_debug("asshelp " m, \
89 my_libassuan_log_handler (assuan_context_t ctx, void *hook,
90 unsigned int cat, const char *msg)
94 if (! TEST_LOG_CAT (cat))
97 dbgval = hook? *(unsigned int*)hook : 0;
99 return 0; /* Assuan debugging is not enabled. */
101 if (ctx && my_log_monitor && !my_log_monitor (ctx, cat, msg))
102 return 0; /* Temporary disabled. */
105 log_string (GPGRT_LOG_DEBUG, msg);
111 /* Setup libassuan to use our own logging functions. Should be used
114 setup_libassuan_logging (unsigned int *debug_var_address,
115 int (*log_monitor)(assuan_context_t ctx,
121 flagstr = getenv ("ASSUAN_DEBUG");
123 log_cats = atoi (flagstr);
124 else /* Default to log the control channel. */
125 log_cats = (1 << (ASSUAN_LOG_CONTROL - 1));
126 my_log_monitor = log_monitor;
127 assuan_set_log_cb (my_libassuan_log_handler, debug_var_address);
131 /* Change the Libassuan log categories to those given by NEWCATS.
132 NEWCATS is 0 the default category of ASSUAN_LOG_CONTROL is
133 selected. Note, that setup_libassuan_logging overrides the values
136 set_libassuan_log_cats (unsigned int newcats)
140 else /* Default to log the control channel. */
141 log_cats = (1 << (ASSUAN_LOG_CONTROL - 1));
147 send_one_option (assuan_context_t ctx, gpg_err_source_t errsource,
148 const char *name, const char *value, int use_putenv)
155 if (!value || !*value)
156 err = 0; /* Avoid sending empty strings. */
157 else if (asprintf (&optstr, "OPTION %s%s=%s",
158 use_putenv? "putenv=":"", name, value) < 0)
159 err = gpg_error_from_syserror ();
162 err = assuan_transact (ctx, optstr, NULL, NULL, NULL, NULL, NULL, NULL);
170 /* Send the assuan commands pertaining to the pinentry environment. The
171 OPT_* arguments are optional and may be used to override the
172 defaults taken from the current locale. */
174 send_pinentry_environment (assuan_context_t ctx,
175 gpg_err_source_t errsource,
176 const char *opt_lc_ctype,
177 const char *opt_lc_messages,
178 session_env_t session_env)
182 #if defined(HAVE_SETLOCALE)
186 const char *dft_ttyname;
188 const char *name, *assname, *value;
192 while ((name = session_env_list_stdenvnames (&iterator, &assname)))
194 value = session_env_getenv_or_default (session_env, name, NULL);
199 err = send_one_option (ctx, errsource, assname, value, 0);
202 err = send_one_option (ctx, errsource, name, value, 1);
203 if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION)
204 err = 0; /* Server too old; can't pass the new envvars. */
211 dft_ttyname = session_env_getenv_or_default (session_env, "GPG_TTY",
213 if (dft_ttyname && !is_default)
214 dft_ttyname = NULL; /* We need the default value. */
216 /* Send the value for LC_CTYPE. */
217 #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
218 old_lc = setlocale (LC_CTYPE, NULL);
221 old_lc = xtrystrdup (old_lc);
223 return gpg_error_from_syserror ();
225 dft_lc = setlocale (LC_CTYPE, "");
227 if (opt_lc_ctype || (dft_ttyname && dft_lc))
229 err = send_one_option (ctx, errsource, "lc-ctype",
230 opt_lc_ctype ? opt_lc_ctype : dft_lc, 0);
232 #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
235 setlocale (LC_CTYPE, old_lc);
242 /* Send the value for LC_MESSAGES. */
243 #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
244 old_lc = setlocale (LC_MESSAGES, NULL);
247 old_lc = xtrystrdup (old_lc);
249 return gpg_error_from_syserror ();
251 dft_lc = setlocale (LC_MESSAGES, "");
253 if (opt_lc_messages || (dft_ttyname && dft_lc))
255 err = send_one_option (ctx, errsource, "lc-messages",
256 opt_lc_messages ? opt_lc_messages : dft_lc, 0);
258 #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
261 setlocale (LC_MESSAGES, old_lc);
272 /* Lock a spawning process. The caller needs to provide the address
273 of a variable to store the lock information and the name or the
276 lock_spawning (lock_spawn_t *lock, const char *homedir, const char *name,
282 DLOG("lock_spawning(,%s,%s)\n", homedir, name);
286 fname = make_absfilename_try
288 !strcmp (name, "agent")? "gnupg_spawn_agent_sentinel":
289 !strcmp (name, "dirmngr")? "gnupg_spawn_dirmngr_sentinel":
290 /* */ "gnupg_spawn_unknown_sentinel",
293 return gpg_error_from_syserror ();
295 *lock = dotlock_create (fname, 0);
298 return gpg_error_from_syserror ();
300 /* FIXME: We should use a timeout of 5000 here - however
301 make_dotlock does not yet support values other than -1 and 0. */
302 if (dotlock_take (*lock, -1))
303 return gpg_error_from_syserror ();
309 /* Unlock the spawning process. */
311 unlock_spawning (lock_spawn_t *lock, const char *name)
313 DLOG("unlock_spawning(%p, %s)\n", lock, name);
318 dotlock_destroy (*lock);
323 /* Try to connect to the agent via socket or start it if it is not
324 running and AUTOSTART is set. Handle the server's initial
325 greeting. Returns a new assuan context at R_CTX or an error
328 start_new_gpg_agent (assuan_context_t *r_ctx,
329 gpg_err_source_t errsource,
330 const char *agent_program,
331 const char *opt_lc_ctype,
332 const char *opt_lc_messages,
333 session_env_t session_env,
334 int autostart, int verbose, int debug,
335 gpg_error_t (*status_cb)(ctrl_t, int, ...),
336 ctrl_t status_cb_arg)
339 assuan_context_t ctx;
340 int did_success_msg = 0;
346 DLOG("start_new_gpg_agent(autostart=%d)...\n",autostart);
348 err = assuan_new (&ctx);
351 log_error ("error allocating assuan context: %s\n", gpg_strerror (err));
355 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
358 err = gpg_err_make (errsource, gpg_err_code_from_syserror ());
359 assuan_release (ctx);
363 DLOG("start_new_gpg_agent sockname=%s...\n",sockname);
365 err = assuan_socket_connect (ctx, sockname, 0, 0);
366 if (err && autostart)
370 char *program = NULL;
371 const char *program_arg = NULL;
376 DLOG("start_new_gpg_agent err=%d, spawning...\n",err);
378 /* With no success start a new server. */
379 if (!agent_program || !*agent_program)
380 agent_program = gnupg_module_name (GNUPG_MODULE_NAME_AGENT);
381 else if ((s=strchr (agent_program, '|')) && s[1] == '-' && s[2]=='-')
383 /* Hack to insert an additional option on the command line. */
384 program = xtrystrdup (agent_program);
387 gpg_error_t tmperr = gpg_err_make (errsource,
388 gpg_err_code_from_syserror ());
390 assuan_release (ctx);
391 DLOG("start_new_gpg_agent ERROR %ld (xstrdup)\n", (long)tmperr);
394 p = strchr (program, '|');
400 log_info (_("no running gpg-agent - starting '%s'\n"),
404 status_cb (status_cb_arg, STATUS_PROGRESS,
405 "starting_agent ? 0 0", NULL);
407 /* We better pass an absolute home directory to the agent just
408 in case gpg-agent does not convert the passed name to an
409 absolute one (which it should do). */
410 abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
413 gpg_error_t tmperr = gpg_err_make (errsource,
414 gpg_err_code_from_syserror ());
415 log_error ("error building filename: %s\n",gpg_strerror (tmperr));
417 assuan_release (ctx);
419 DLOG("start_new_gpg_agent ERROR %ld (abs_homedir)\n", (long)tmperr);
425 gpg_error_t tmperr = gpg_err_make (errsource,
426 gpg_err_code_from_syserror ());
427 log_error ("error flushing pending output: %s\n",
430 assuan_release (ctx);
433 DLOG("start_new_gpg_agent ERROR %ld (fflush)\n", (long)tmperr);
437 /* If the agent has been configured for use with a standard
438 socket, an environment variable is not required and thus
439 we we can savely start the agent here. */
441 argv[i++] = "--homedir";
442 argv[i++] = abs_homedir;
443 argv[i++] = "--use-standard-socket";
445 argv[i++] = program_arg;
446 argv[i++] = "--daemon";
449 DLOG("start_new_gpg_agent locking spawning...\n");
450 if (!(err = lock_spawning (&lock, gnupg_homedir (), "agent", verbose))
451 && assuan_socket_connect (ctx, sockname, 0, 0))
453 DLOG("start_new_gpg_agent locked spawning, no connect...\n");
454 err = gnupg_spawn_process_detached (program? program : agent_program,
457 log_error ("failed to start agent '%s': %s\n",
458 agent_program, gpg_strerror (err));
461 for (i=0; i < SECS_TO_WAIT_FOR_AGENT; i++)
463 DLOG("start_new_gpg_agent waiting %d...\n", i);
465 log_info (_("waiting for the agent to come up ... (%ds)\n"),
466 SECS_TO_WAIT_FOR_AGENT - i);
468 err = assuan_socket_connect (ctx, sockname, 0, 0);
473 log_info (_("connection to agent established\n"));
481 DLOG("start_new_gpg_agent lock failed or connect failed...\n");
483 unlock_spawning (&lock, "agent");
490 DLOG("start_new_gpg_agent ERROR (connect)\n");
492 if (autostart || gpg_err_code (err) != GPG_ERR_ASS_CONNECT_FAILED)
493 log_error ("can't connect to the agent: %s\n", gpg_strerror (err));
494 assuan_release (ctx);
495 return gpg_err_make (errsource, GPG_ERR_NO_AGENT);
498 if (debug && !did_success_msg)
499 log_debug ("connection to agent established\n");
501 err = assuan_transact (ctx, "RESET",
502 NULL, NULL, NULL, NULL, NULL, NULL);
505 err = send_pinentry_environment (ctx, errsource,
506 opt_lc_ctype, opt_lc_messages,
508 if (gpg_err_code (err) == GPG_ERR_FORBIDDEN
509 && gpg_err_source (err) == GPG_ERR_SOURCE_GPGAGENT)
511 /* Check whether we are in restricted mode. */
512 if (!assuan_transact (ctx, "GETINFO restricted",
513 NULL, NULL, NULL, NULL, NULL, NULL))
516 log_info (_("connection to agent is in restricted mode\n"));
523 assuan_release (ctx);
524 DLOG("start_new_gpg_agent ERROR %ld (final)\n", (long)err);
529 DLOG("start_new_gpg_agent=%p OK\n", ctx);
534 /* Try to connect to the dirmngr via a socket. On platforms
535 supporting it, start it up if needed and if AUTOSTART is true.
536 Returns a new assuan context at R_CTX or an error code. */
538 start_new_dirmngr (assuan_context_t *r_ctx,
539 gpg_err_source_t errsource,
540 const char *dirmngr_program,
542 int verbose, int debug,
543 gpg_error_t (*status_cb)(ctrl_t, int, ...),
544 ctrl_t status_cb_arg)
547 assuan_context_t ctx;
548 const char *sockname;
549 int did_success_msg = 0;
553 err = assuan_new (&ctx);
556 log_error ("error allocating assuan context: %s\n", gpg_strerror (err));
560 sockname = dirmngr_socket_name ();
561 err = assuan_socket_connect (ctx, sockname, 0, 0);
563 #ifdef USE_DIRMNGR_AUTO_START
564 if (err && autostart)
570 /* No connection: Try start a new Dirmngr. */
571 if (!dirmngr_program || !*dirmngr_program)
572 dirmngr_program = gnupg_module_name (GNUPG_MODULE_NAME_DIRMNGR);
575 log_info (_("no running Dirmngr - starting '%s'\n"),
579 status_cb (status_cb_arg, STATUS_PROGRESS,
580 "starting_dirmngr ? 0 0", NULL);
582 abs_homedir = make_absfilename (gnupg_homedir (), NULL);
585 gpg_error_t tmperr = gpg_err_make (errsource,
586 gpg_err_code_from_syserror ());
587 log_error ("error building filename: %s\n",gpg_strerror (tmperr));
588 assuan_release (ctx);
594 gpg_error_t tmperr = gpg_err_make (errsource,
595 gpg_err_code_from_syserror ());
596 log_error ("error flushing pending output: %s\n",
598 assuan_release (ctx);
602 argv[0] = "--daemon";
603 /* Try starting the daemon. Versions of dirmngr < 2.1.15 do
604 * this only if the home directory is given on the command line. */
605 argv[1] = "--homedir";
606 argv[2] = abs_homedir;
609 if (!(err = lock_spawning (&lock, gnupg_homedir (), "dirmngr", verbose))
610 && assuan_socket_connect (ctx, sockname, 0, 0))
612 err = gnupg_spawn_process_detached (dirmngr_program, argv, NULL);
614 log_error ("failed to start the dirmngr '%s': %s\n",
615 dirmngr_program, gpg_strerror (err));
620 for (i=0; i < SECS_TO_WAIT_FOR_DIRMNGR; i++)
623 log_info (_("waiting for the dirmngr "
624 "to come up ... (%ds)\n"),
625 SECS_TO_WAIT_FOR_DIRMNGR - i);
627 err = assuan_socket_connect (ctx, sockname, 0, 0);
632 log_info (_("connection to the dirmngr"
642 unlock_spawning (&lock, "dirmngr");
646 (void)dirmngr_program;
650 #endif /*USE_DIRMNGR_AUTO_START*/
654 if (autostart || gpg_err_code (err) != GPG_ERR_ASS_CONNECT_FAILED)
655 log_error ("connecting dirmngr at '%s' failed: %s\n",
656 sockname, gpg_strerror (err));
657 assuan_release (ctx);
658 return gpg_err_make (errsource, GPG_ERR_NO_DIRMNGR);
661 if (debug && !did_success_msg)
662 log_debug ("connection to the dirmngr established\n");
669 /* Return the version of a server using "GETINFO version". On success
670 0 is returned and R_VERSION receives a malloced string with the
671 version which must be freed by the caller. On error NULL is stored
672 at R_VERSION and an error code returned. Mode is in general 0 but
673 certain values may be used to modify the used version command:
675 MODE == 0 = Use "GETINFO version"
676 MODE == 2 - Use "SCD GETINFO version"
679 get_assuan_server_version (assuan_context_t ctx, int mode, char **r_version)
684 init_membuf (&data, 64);
685 err = assuan_transact (ctx,
686 mode == 2? "SCD GETINFO version"
687 /**/ : "GETINFO version",
688 put_membuf_cb, &data,
689 NULL, NULL, NULL, NULL);
692 xfree (get_membuf (&data, NULL));
697 put_membuf (&data, "", 1);
698 *r_version = get_membuf (&data, NULL);
700 err = gpg_error_from_syserror ();