chiark / gitweb /
341dfe3270baf0db0cc29026f3f62840c594554c
[gnupg2.git] / common / asshelp.c
1 /* asshelp.c - Helper functions for Assuan
2  * Copyright (C) 2002, 2004, 2007, 2009, 2010 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * This file is free software; you can redistribute it and/or modify
7  * it under the terms of either
8  *
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.
12  *
13  * or
14  *
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.
18  *
19  * or both in parallel, as here.
20  *
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.
25  *
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/>.
28  */
29
30 #include <config.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #ifdef HAVE_LOCALE_H
37 #include <locale.h>
38 #endif
39
40 #include "i18n.h"
41 #include "util.h"
42 #include "exechelp.h"
43 #include "sysutils.h"
44 #include "status.h"
45 #include "membuf.h"
46 #include "asshelp.h"
47
48 /* The type we use for lock_agent_spawning.  */
49 #ifdef HAVE_W32_SYSTEM
50 # define lock_spawn_t HANDLE
51 #else
52 # define lock_spawn_t dotlock_t
53 #endif
54
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
60 #else
61 # define SECS_TO_WAIT_FOR_AGENT 5
62 # define SECS_TO_WAIT_FOR_DIRMNGR 5
63 #endif
64
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. */
69 static int log_cats;
70 #define TEST_LOG_CAT(x) (!! (log_cats & (1 << (x - 1))))
71
72 /* The assuan log monitor used to temporary inhibit log messages from
73  * assuan.  */
74 static int (*my_log_monitor) (assuan_context_t ctx,
75                               unsigned int cat,
76                               const char *msg);
77
78
79 #define DLOG(m, ...) do{                        \
80     int DLOG_se = errno;                        \
81     if (/*DBG_IPC*/ 0)                          \
82       log_debug("asshelp " m,                   \
83                 ##__VA_ARGS__);                 \
84     errno = DLOG_se;                            \
85   }while(0)
86
87
88 static int
89 my_libassuan_log_handler (assuan_context_t ctx, void *hook,
90                           unsigned int cat, const char *msg)
91 {
92   unsigned int dbgval;
93
94   if (! TEST_LOG_CAT (cat))
95     return 0;
96
97   dbgval = hook? *(unsigned int*)hook : 0;
98   if (!(dbgval & 1024))
99     return 0; /* Assuan debugging is not enabled.  */
100
101   if (ctx && my_log_monitor && !my_log_monitor (ctx, cat, msg))
102     return 0; /* Temporary disabled.  */
103
104   if (msg)
105     log_string (GPGRT_LOG_DEBUG, msg);
106
107   return 1;
108 }
109
110
111 /* Setup libassuan to use our own logging functions.  Should be used
112    early at startup.  */
113 void
114 setup_libassuan_logging (unsigned int *debug_var_address,
115                          int (*log_monitor)(assuan_context_t ctx,
116                                             unsigned int cat,
117                                             const char *msg))
118 {
119   char *flagstr;
120
121   flagstr = getenv ("ASSUAN_DEBUG");
122   if (flagstr)
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);
128 }
129
130
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
134    given here.  */
135 void
136 set_libassuan_log_cats (unsigned int newcats)
137 {
138   if (newcats)
139     log_cats = newcats;
140   else /* Default to log the control channel.  */
141     log_cats = (1 << (ASSUAN_LOG_CONTROL - 1));
142 }
143
144
145
146 static gpg_error_t
147 send_one_option (assuan_context_t ctx, gpg_err_source_t errsource,
148                  const char *name, const char *value, int use_putenv)
149 {
150   gpg_error_t err;
151   char *optstr;
152
153   (void)errsource;
154
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 ();
160   else
161     {
162       err = assuan_transact (ctx, optstr, NULL, NULL, NULL, NULL, NULL, NULL);
163       xfree (optstr);
164     }
165
166   return err;
167 }
168
169
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. */
173 gpg_error_t
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)
179
180 {
181   gpg_error_t err = 0;
182 #if defined(HAVE_SETLOCALE)
183   char *old_lc = NULL;
184 #endif
185   char *dft_lc = NULL;
186   const char *dft_ttyname;
187   int iterator;
188   const char *name, *assname, *value;
189   int is_default;
190
191   iterator = 0;
192   while ((name = session_env_list_stdenvnames (&iterator, &assname)))
193     {
194       value = session_env_getenv_or_default (session_env, name, NULL);
195       if (!value)
196         continue;
197
198       if (assname)
199         err = send_one_option (ctx, errsource, assname, value, 0);
200       else
201         {
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.  */
205         }
206       if (err)
207         return err;
208     }
209
210
211   dft_ttyname = session_env_getenv_or_default (session_env, "GPG_TTY",
212                                                &is_default);
213   if (dft_ttyname && !is_default)
214     dft_ttyname = NULL;  /* We need the default value.  */
215
216   /* Send the value for LC_CTYPE.  */
217 #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
218   old_lc = setlocale (LC_CTYPE, NULL);
219   if (old_lc)
220     {
221       old_lc = xtrystrdup (old_lc);
222       if (!old_lc)
223         return gpg_error_from_syserror ();
224     }
225   dft_lc = setlocale (LC_CTYPE, "");
226 #endif
227   if (opt_lc_ctype || (dft_ttyname && dft_lc))
228     {
229       err = send_one_option (ctx, errsource, "lc-ctype",
230                              opt_lc_ctype ? opt_lc_ctype : dft_lc, 0);
231     }
232 #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE)
233   if (old_lc)
234     {
235       setlocale (LC_CTYPE, old_lc);
236       xfree (old_lc);
237     }
238 #endif
239   if (err)
240     return err;
241
242   /* Send the value for LC_MESSAGES.  */
243 #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
244   old_lc = setlocale (LC_MESSAGES, NULL);
245   if (old_lc)
246     {
247       old_lc = xtrystrdup (old_lc);
248       if (!old_lc)
249         return gpg_error_from_syserror ();
250     }
251   dft_lc = setlocale (LC_MESSAGES, "");
252 #endif
253   if (opt_lc_messages || (dft_ttyname && dft_lc))
254     {
255       err = send_one_option (ctx, errsource, "lc-messages",
256                              opt_lc_messages ? opt_lc_messages : dft_lc, 0);
257     }
258 #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES)
259   if (old_lc)
260     {
261       setlocale (LC_MESSAGES, old_lc);
262       xfree (old_lc);
263     }
264 #endif
265   if (err)
266     return err;
267
268   return 0;
269 }
270
271
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
274    process.  */
275 static gpg_error_t
276 lock_spawning (lock_spawn_t *lock, const char *homedir, const char *name,
277                int verbose)
278 {
279   char *fname;
280   (void)verbose;
281
282   DLOG("lock_spawning(,%s,%s)\n", homedir, name);
283
284   *lock = NULL;
285
286   fname = make_absfilename_try
287     (homedir,
288      !strcmp (name, "agent")?   "gnupg_spawn_agent_sentinel":
289      !strcmp (name, "dirmngr")? "gnupg_spawn_dirmngr_sentinel":
290      /*                    */   "gnupg_spawn_unknown_sentinel",
291      NULL);
292   if (!fname)
293     return gpg_error_from_syserror ();
294
295   *lock = dotlock_create (fname, 0);
296   xfree (fname);
297   if (!*lock)
298     return gpg_error_from_syserror ();
299
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 ();
304
305   return 0;
306 }
307
308
309 /* Unlock the spawning process.  */
310 static void
311 unlock_spawning (lock_spawn_t *lock, const char *name)
312 {
313   DLOG("unlock_spawning(%p, %s)\n", lock, name);
314
315   if (*lock)
316     {
317       (void)name;
318       dotlock_destroy (*lock);
319       *lock = NULL;
320     }
321 }
322
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
326    code. */
327 gpg_error_t
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)
337 {
338   gpg_error_t err;
339   assuan_context_t ctx;
340   int did_success_msg = 0;
341   char *sockname;
342   const char *argv[6];
343
344   *r_ctx = NULL;
345
346   DLOG("start_new_gpg_agent(autostart=%d)...\n",autostart);
347
348   err = assuan_new (&ctx);
349   if (err)
350     {
351       log_error ("error allocating assuan context: %s\n", gpg_strerror (err));
352       return err;
353     }
354
355   sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
356   if (!sockname)
357     {
358       err = gpg_err_make (errsource, gpg_err_code_from_syserror ());
359       assuan_release (ctx);
360       return err;
361     }
362
363   DLOG("start_new_gpg_agent sockname=%s...\n",sockname);
364
365   err = assuan_socket_connect (ctx, sockname, 0, 0);
366   if (err && autostart)
367     {
368       char *abs_homedir;
369       lock_spawn_t lock;
370       char *program = NULL;
371       const char *program_arg = NULL;
372       char *p;
373       const char *s;
374       int i;
375
376       DLOG("start_new_gpg_agent err=%d, spawning...\n",err);
377
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]=='-')
382         {
383           /* Hack to insert an additional option on the command line.  */
384           program = xtrystrdup (agent_program);
385           if (!program)
386             {
387               gpg_error_t tmperr = gpg_err_make (errsource,
388                                                  gpg_err_code_from_syserror ());
389               xfree (sockname);
390               assuan_release (ctx);
391               DLOG("start_new_gpg_agent ERROR %ld (xstrdup)\n", (long)tmperr);
392               return tmperr;
393             }
394           p = strchr (program, '|');
395           *p++ = 0;
396           program_arg = p;
397         }
398
399       if (verbose)
400         log_info (_("no running gpg-agent - starting '%s'\n"),
401                   agent_program);
402
403       if (status_cb)
404         status_cb (status_cb_arg, STATUS_PROGRESS,
405                    "starting_agent ? 0 0", NULL);
406
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);
411       if (!abs_homedir)
412         {
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));
416           xfree (sockname);
417           assuan_release (ctx);
418           xfree (program);
419           DLOG("start_new_gpg_agent ERROR %ld (abs_homedir)\n", (long)tmperr);
420           return tmperr;
421         }
422
423       if (fflush (NULL))
424         {
425           gpg_error_t tmperr = gpg_err_make (errsource,
426                                              gpg_err_code_from_syserror ());
427           log_error ("error flushing pending output: %s\n",
428                      strerror (errno));
429           xfree (sockname);
430           assuan_release (ctx);
431           xfree (abs_homedir);
432           xfree (program);
433           DLOG("start_new_gpg_agent ERROR %ld (fflush)\n", (long)tmperr);
434           return tmperr;
435         }
436
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.  */
440       i = 0;
441       argv[i++] = "--homedir";
442       argv[i++] = abs_homedir;
443       argv[i++] = "--use-standard-socket";
444       if (program_arg)
445         argv[i++] = program_arg;
446       argv[i++] = "--daemon";
447       argv[i++] = NULL;
448
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))
452         {
453           DLOG("start_new_gpg_agent locked spawning, no connect...\n");
454           err = gnupg_spawn_process_detached (program? program : agent_program,
455                                               argv, NULL);
456           if (err)
457             log_error ("failed to start agent '%s': %s\n",
458                        agent_program, gpg_strerror (err));
459           else
460             {
461               for (i=0; i < SECS_TO_WAIT_FOR_AGENT; i++)
462                 {
463                   DLOG("start_new_gpg_agent waiting %d...\n", i);
464                   if (verbose)
465                     log_info (_("waiting for the agent to come up ... (%ds)\n"),
466                               SECS_TO_WAIT_FOR_AGENT - i);
467                   gnupg_sleep (1);
468                   err = assuan_socket_connect (ctx, sockname, 0, 0);
469                   if (!err)
470                     {
471                       if (verbose)
472                         {
473                           log_info (_("connection to agent established\n"));
474                           did_success_msg = 1;
475                         }
476                       break;
477                     }
478                 }
479             }
480         }
481       DLOG("start_new_gpg_agent lock failed or connect failed...\n");
482
483       unlock_spawning (&lock, "agent");
484       xfree (abs_homedir);
485       xfree (program);
486     }
487   xfree (sockname);
488   if (err)
489     {
490       DLOG("start_new_gpg_agent ERROR (connect)\n");
491
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);
496     }
497
498   if (debug && !did_success_msg)
499     log_debug ("connection to agent established\n");
500
501   err = assuan_transact (ctx, "RESET",
502                          NULL, NULL, NULL, NULL, NULL, NULL);
503   if (!err)
504     {
505       err = send_pinentry_environment (ctx, errsource,
506                                        opt_lc_ctype, opt_lc_messages,
507                                        session_env);
508       if (gpg_err_code (err) == GPG_ERR_FORBIDDEN
509           && gpg_err_source (err) == GPG_ERR_SOURCE_GPGAGENT)
510         {
511           /* Check whether we are in restricted mode.  */
512           if (!assuan_transact (ctx, "GETINFO restricted",
513                                 NULL, NULL, NULL, NULL, NULL, NULL))
514             {
515               if (verbose)
516                 log_info (_("connection to agent is in restricted mode\n"));
517               err = 0;
518             }
519         }
520     }
521   if (err)
522     {
523       assuan_release (ctx);
524       DLOG("start_new_gpg_agent ERROR %ld (final)\n", (long)err);
525       return err;
526     }
527
528   *r_ctx = ctx;
529   DLOG("start_new_gpg_agent=%p OK\n", ctx);
530   return 0;
531 }
532
533
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. */
537 gpg_error_t
538 start_new_dirmngr (assuan_context_t *r_ctx,
539                    gpg_err_source_t errsource,
540                    const char *dirmngr_program,
541                    int autostart,
542                    int verbose, int debug,
543                    gpg_error_t (*status_cb)(ctrl_t, int, ...),
544                    ctrl_t status_cb_arg)
545 {
546   gpg_error_t err;
547   assuan_context_t ctx;
548   const char *sockname;
549   int did_success_msg = 0;
550
551   *r_ctx = NULL;
552
553   err = assuan_new (&ctx);
554   if (err)
555     {
556       log_error ("error allocating assuan context: %s\n", gpg_strerror (err));
557       return err;
558     }
559
560   sockname = dirmngr_socket_name ();
561   err = assuan_socket_connect (ctx, sockname, 0, 0);
562
563 #ifdef USE_DIRMNGR_AUTO_START
564   if (err && autostart)
565     {
566       lock_spawn_t lock;
567       const char *argv[4];
568       char *abs_homedir;
569
570       /* No connection: Try start a new Dirmngr.  */
571       if (!dirmngr_program || !*dirmngr_program)
572         dirmngr_program = gnupg_module_name (GNUPG_MODULE_NAME_DIRMNGR);
573
574       if (verbose)
575         log_info (_("no running Dirmngr - starting '%s'\n"),
576                   dirmngr_program);
577
578       if (status_cb)
579         status_cb (status_cb_arg, STATUS_PROGRESS,
580                    "starting_dirmngr ? 0 0", NULL);
581
582       abs_homedir = make_absfilename (gnupg_homedir (), NULL);
583       if (!abs_homedir)
584         {
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);
589           return tmperr;
590         }
591
592       if (fflush (NULL))
593         {
594           gpg_error_t tmperr = gpg_err_make (errsource,
595                                              gpg_err_code_from_syserror ());
596           log_error ("error flushing pending output: %s\n",
597                      strerror (errno));
598           assuan_release (ctx);
599           return tmperr;
600         }
601
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;
607       argv[3] = NULL;
608
609       if (!(err = lock_spawning (&lock, gnupg_homedir (), "dirmngr", verbose))
610           && assuan_socket_connect (ctx, sockname, 0, 0))
611         {
612           err = gnupg_spawn_process_detached (dirmngr_program, argv, NULL);
613           if (err)
614             log_error ("failed to start the dirmngr '%s': %s\n",
615                        dirmngr_program, gpg_strerror (err));
616           else
617             {
618               int i;
619
620               for (i=0; i < SECS_TO_WAIT_FOR_DIRMNGR; i++)
621                 {
622                   if (verbose)
623                     log_info (_("waiting for the dirmngr "
624                                 "to come up ... (%ds)\n"),
625                               SECS_TO_WAIT_FOR_DIRMNGR - i);
626                   gnupg_sleep (1);
627                   err = assuan_socket_connect (ctx, sockname, 0, 0);
628                   if (!err)
629                     {
630                       if (verbose)
631                         {
632                           log_info (_("connection to the dirmngr"
633                                       " established\n"));
634                           did_success_msg = 1;
635                         }
636                       break;
637                     }
638                 }
639             }
640         }
641
642       unlock_spawning (&lock, "dirmngr");
643       xfree (abs_homedir);
644     }
645 #else
646   (void)dirmngr_program;
647   (void)verbose;
648   (void)status_cb;
649   (void)status_cb_arg;
650 #endif /*USE_DIRMNGR_AUTO_START*/
651
652   if (err)
653     {
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);
659     }
660
661   if (debug && !did_success_msg)
662     log_debug ("connection to the dirmngr established\n");
663
664   *r_ctx = ctx;
665   return 0;
666 }
667
668
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:
674
675       MODE == 0 = Use "GETINFO version"
676       MODE == 2 - Use "SCD GETINFO version"
677  */
678 gpg_error_t
679 get_assuan_server_version (assuan_context_t ctx, int mode, char **r_version)
680 {
681   gpg_error_t err;
682   membuf_t data;
683
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);
690   if (err)
691     {
692       xfree (get_membuf (&data, NULL));
693       *r_version = NULL;
694     }
695   else
696     {
697       put_membuf (&data, "", 1);
698       *r_version = get_membuf (&data, NULL);
699       if (!*r_version)
700         err = gpg_error_from_syserror ();
701     }
702   return err;
703 }