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,
80 my_libassuan_log_handler (assuan_context_t ctx, void *hook,
81 unsigned int cat, const char *msg)
85 if (! TEST_LOG_CAT (cat))
88 dbgval = hook? *(unsigned int*)hook : 0;
90 return 0; /* Assuan debugging is not enabled. */
92 if (ctx && my_log_monitor && !my_log_monitor (ctx, cat, msg))
93 return 0; /* Temporary disabled. */
96 log_string (GPGRT_LOG_DEBUG, msg);
102 /* Setup libassuan to use our own logging functions. Should be used
105 setup_libassuan_logging (unsigned int *debug_var_address,
106 int (*log_monitor)(assuan_context_t ctx,
112 flagstr = getenv ("ASSUAN_DEBUG");
114 log_cats = atoi (flagstr);
115 else /* Default to log the control channel. */
116 log_cats = (1 << (ASSUAN_LOG_CONTROL - 1));
117 my_log_monitor = log_monitor;
118 assuan_set_log_cb (my_libassuan_log_handler, debug_var_address);
122 /* Change the Libassuan log categories to those given by NEWCATS.
123 NEWCATS is 0 the default category of ASSUAN_LOG_CONTROL is
124 selected. Note, that setup_libassuan_logging overrides the values
127 set_libassuan_log_cats (unsigned int newcats)
131 else /* Default to log the control channel. */
132 log_cats = (1 << (ASSUAN_LOG_CONTROL - 1));
138 send_one_option (assuan_context_t ctx, gpg_err_source_t errsource,
139 const char *name, const char *value, int use_putenv)
146 if (!value || !*value)
147 err = 0; /* Avoid sending empty strings. */
148 else if (asprintf (&optstr, "OPTION %s%s=%s",
149 use_putenv? "putenv=":"", name, value) < 0)
150 err = gpg_error_from_syserror ();
153 err = assuan_transact (ctx, optstr, NULL, NULL, NULL, NULL, NULL, NULL);
161 /* Send the assuan commands pertaining to the pinentry environment. The
162 OPT_* arguments are optional and may be used to override the
163 defaults taken from the current locale. */
165 send_pinentry_environment (assuan_context_t ctx,
166 gpg_err_source_t errsource,
167 const char *opt_lc_ctype,
168 const char *opt_lc_messages,
169 session_env_t session_env)
173 #if defined(HAVE_SETLOCALE)
177 const char *dft_ttyname;
179 const char *name, *assname, *value;
183 while ((name = session_env_list_stdenvnames (&iterator, &assname)))
185 value = session_env_getenv_or_default (session_env, name, NULL);
190 err = send_one_option (ctx, errsource, assname, value, 0);
193 err = send_one_option (ctx, errsource, name, value, 1);
194 if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION)
195 err = 0; /* Server too old; can't pass the new envvars. */
202 dft_ttyname = session_env_getenv_or_default (session_env, "GPG_TTY",
204 if (dft_ttyname && !is_default)
205 dft_ttyname = NULL; /* We need the default value. */
207 /* Send the value for LC_CTYPE. */
208 #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
209 old_lc = setlocale (LC_CTYPE, NULL);
212 old_lc = xtrystrdup (old_lc);
214 return gpg_error_from_syserror ();
216 dft_lc = setlocale (LC_CTYPE, "");
218 if (opt_lc_ctype || (dft_ttyname && dft_lc))
220 err = send_one_option (ctx, errsource, "lc-ctype",
221 opt_lc_ctype ? opt_lc_ctype : dft_lc, 0);
223 #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
226 setlocale (LC_CTYPE, old_lc);
233 /* Send the value for LC_MESSAGES. */
234 #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
235 old_lc = setlocale (LC_MESSAGES, NULL);
238 old_lc = xtrystrdup (old_lc);
240 return gpg_error_from_syserror ();
242 dft_lc = setlocale (LC_MESSAGES, "");
244 if (opt_lc_messages || (dft_ttyname && dft_lc))
246 err = send_one_option (ctx, errsource, "lc-messages",
247 opt_lc_messages ? opt_lc_messages : dft_lc, 0);
249 #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
252 setlocale (LC_MESSAGES, old_lc);
263 /* Lock a spawning process. The caller needs to provide the address
264 of a variable to store the lock information and the name or the
267 lock_spawning (lock_spawn_t *lock, const char *homedir, const char *name,
275 fname = make_absfilename_try
277 !strcmp (name, "agent")? "gnupg_spawn_agent_sentinel":
278 !strcmp (name, "dirmngr")? "gnupg_spawn_dirmngr_sentinel":
279 /* */ "gnupg_spawn_unknown_sentinel",
282 return gpg_error_from_syserror ();
284 *lock = dotlock_create (fname, 0);
287 return gpg_error_from_syserror ();
289 /* FIXME: We should use a timeout of 5000 here - however
290 make_dotlock does not yet support values other than -1 and 0. */
291 if (dotlock_take (*lock, -1))
292 return gpg_error_from_syserror ();
298 /* Unlock the spawning process. */
300 unlock_spawning (lock_spawn_t *lock, const char *name)
305 dotlock_destroy (*lock);
310 /* Try to connect to the agent via socket or start it if it is not
311 running and AUTOSTART is set. Handle the server's initial
312 greeting. Returns a new assuan context at R_CTX or an error
315 start_new_gpg_agent (assuan_context_t *r_ctx,
316 gpg_err_source_t errsource,
317 const char *agent_program,
318 const char *opt_lc_ctype,
319 const char *opt_lc_messages,
320 session_env_t session_env,
321 int autostart, int verbose, int debug,
322 gpg_error_t (*status_cb)(ctrl_t, int, ...),
323 ctrl_t status_cb_arg)
326 assuan_context_t ctx;
327 int did_success_msg = 0;
333 err = assuan_new (&ctx);
336 log_error ("error allocating assuan context: %s\n", gpg_strerror (err));
340 sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
343 err = gpg_err_make (errsource, gpg_err_code_from_syserror ());
344 assuan_release (ctx);
348 err = assuan_socket_connect (ctx, sockname, 0, 0);
349 if (err && autostart)
353 char *program = NULL;
354 const char *program_arg = NULL;
359 /* With no success start a new server. */
360 if (!agent_program || !*agent_program)
361 agent_program = gnupg_module_name (GNUPG_MODULE_NAME_AGENT);
362 else if ((s=strchr (agent_program, '|')) && s[1] == '-' && s[2]=='-')
364 /* Hack to insert an additional option on the command line. */
365 program = xtrystrdup (agent_program);
368 gpg_error_t tmperr = gpg_err_make (errsource,
369 gpg_err_code_from_syserror ());
371 assuan_release (ctx);
374 p = strchr (program, '|');
380 log_info (_("no running gpg-agent - starting '%s'\n"),
384 status_cb (status_cb_arg, STATUS_PROGRESS,
385 "starting_agent ? 0 0", NULL);
387 /* We better pass an absolute home directory to the agent just
388 in case gpg-agent does not convert the passed name to an
389 absolute one (which it should do). */
390 abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
393 gpg_error_t tmperr = gpg_err_make (errsource,
394 gpg_err_code_from_syserror ());
395 log_error ("error building filename: %s\n",gpg_strerror (tmperr));
397 assuan_release (ctx);
404 gpg_error_t tmperr = gpg_err_make (errsource,
405 gpg_err_code_from_syserror ());
406 log_error ("error flushing pending output: %s\n",
409 assuan_release (ctx);
415 /* If the agent has been configured for use with a standard
416 socket, an environment variable is not required and thus
417 we we can savely start the agent here. */
419 argv[i++] = "--homedir";
420 argv[i++] = abs_homedir;
421 argv[i++] = "--use-standard-socket";
423 argv[i++] = program_arg;
424 argv[i++] = "--daemon";
427 if (!(err = lock_spawning (&lock, gnupg_homedir (), "agent", verbose))
428 && assuan_socket_connect (ctx, sockname, 0, 0))
430 err = gnupg_spawn_process_detached (program? program : agent_program,
433 log_error ("failed to start agent '%s': %s\n",
434 agent_program, gpg_strerror (err));
437 for (i=0; i < SECS_TO_WAIT_FOR_AGENT; i++)
440 log_info (_("waiting for the agent to come up ... (%ds)\n"),
441 SECS_TO_WAIT_FOR_AGENT - i);
443 err = assuan_socket_connect (ctx, sockname, 0, 0);
448 log_info (_("connection to agent established\n"));
457 unlock_spawning (&lock, "agent");
464 if (autostart || gpg_err_code (err) != GPG_ERR_ASS_CONNECT_FAILED)
465 log_error ("can't connect to the agent: %s\n", gpg_strerror (err));
466 assuan_release (ctx);
467 return gpg_err_make (errsource, GPG_ERR_NO_AGENT);
470 if (debug && !did_success_msg)
471 log_debug ("connection to agent established\n");
473 err = assuan_transact (ctx, "RESET",
474 NULL, NULL, NULL, NULL, NULL, NULL);
477 err = send_pinentry_environment (ctx, errsource,
478 opt_lc_ctype, opt_lc_messages,
480 if (gpg_err_code (err) == GPG_ERR_FORBIDDEN
481 && gpg_err_source (err) == GPG_ERR_SOURCE_GPGAGENT)
483 /* Check whether we are in restricted mode. */
484 if (!assuan_transact (ctx, "GETINFO restricted",
485 NULL, NULL, NULL, NULL, NULL, NULL))
488 log_info (_("connection to agent is in restricted mode\n"));
495 assuan_release (ctx);
504 /* Try to connect to the dirmngr via a socket. On platforms
505 supporting it, start it up if needed and if AUTOSTART is true.
506 Returns a new assuan context at R_CTX or an error code. */
508 start_new_dirmngr (assuan_context_t *r_ctx,
509 gpg_err_source_t errsource,
510 const char *dirmngr_program,
512 int verbose, int debug,
513 gpg_error_t (*status_cb)(ctrl_t, int, ...),
514 ctrl_t status_cb_arg)
517 assuan_context_t ctx;
518 const char *sockname;
519 int did_success_msg = 0;
523 err = assuan_new (&ctx);
526 log_error ("error allocating assuan context: %s\n", gpg_strerror (err));
530 sockname = dirmngr_socket_name ();
531 err = assuan_socket_connect (ctx, sockname, 0, 0);
533 #ifdef USE_DIRMNGR_AUTO_START
534 if (err && autostart)
540 /* No connection: Try start a new Dirmngr. */
541 if (!dirmngr_program || !*dirmngr_program)
542 dirmngr_program = gnupg_module_name (GNUPG_MODULE_NAME_DIRMNGR);
545 log_info (_("no running Dirmngr - starting '%s'\n"),
549 status_cb (status_cb_arg, STATUS_PROGRESS,
550 "starting_dirmngr ? 0 0", NULL);
552 abs_homedir = make_absfilename (gnupg_homedir (), NULL);
555 gpg_error_t tmperr = gpg_err_make (errsource,
556 gpg_err_code_from_syserror ());
557 log_error ("error building filename: %s\n",gpg_strerror (tmperr));
558 assuan_release (ctx);
564 gpg_error_t tmperr = gpg_err_make (errsource,
565 gpg_err_code_from_syserror ());
566 log_error ("error flushing pending output: %s\n",
568 assuan_release (ctx);
572 argv[0] = "--daemon";
573 /* Try starting the daemon. Versions of dirmngr < 2.1.15 do
574 * this only if the home directory is given on the command line. */
575 argv[1] = "--homedir";
576 argv[2] = abs_homedir;
579 if (!(err = lock_spawning (&lock, gnupg_homedir (), "dirmngr", verbose))
580 && assuan_socket_connect (ctx, sockname, 0, 0))
582 err = gnupg_spawn_process_detached (dirmngr_program, argv, NULL);
584 log_error ("failed to start the dirmngr '%s': %s\n",
585 dirmngr_program, gpg_strerror (err));
590 for (i=0; i < SECS_TO_WAIT_FOR_DIRMNGR; i++)
593 log_info (_("waiting for the dirmngr "
594 "to come up ... (%ds)\n"),
595 SECS_TO_WAIT_FOR_DIRMNGR - i);
597 err = assuan_socket_connect (ctx, sockname, 0, 0);
602 log_info (_("connection to the dirmngr"
612 unlock_spawning (&lock, "dirmngr");
616 (void)dirmngr_program;
620 #endif /*USE_DIRMNGR_AUTO_START*/
624 if (autostart || gpg_err_code (err) != GPG_ERR_ASS_CONNECT_FAILED)
625 log_error ("connecting dirmngr at '%s' failed: %s\n",
626 sockname, gpg_strerror (err));
627 assuan_release (ctx);
628 return gpg_err_make (errsource, GPG_ERR_NO_DIRMNGR);
631 if (debug && !did_success_msg)
632 log_debug ("connection to the dirmngr established\n");
639 /* Return the version of a server using "GETINFO version". On success
640 0 is returned and R_VERSION receives a malloced string with the
641 version which must be freed by the caller. On error NULL is stored
642 at R_VERSION and an error code returned. Mode is in general 0 but
643 certain values may be used to modify the used version command:
645 MODE == 0 = Use "GETINFO version"
646 MODE == 2 - Use "SCD GETINFO version"
649 get_assuan_server_version (assuan_context_t ctx, int mode, char **r_version)
654 init_membuf (&data, 64);
655 err = assuan_transact (ctx,
656 mode == 2? "SCD GETINFO version"
657 /**/ : "GETINFO version",
658 put_membuf_cb, &data,
659 NULL, NULL, NULL, NULL);
662 xfree (get_membuf (&data, NULL));
667 put_membuf (&data, "", 1);
668 *r_version = get_membuf (&data, NULL);
670 err = gpg_error_from_syserror ();