chiark / gitweb /
gpg: Fix searching for mail addresses in keyrings.
[gnupg2.git] / g10 / call-dirmngr.c
1 /* call-dirmngr.c - GPG operations to the Dirmngr.
2  * Copyright (C) 2011 Free Software Foundation, Inc.
3  * Copyright (C) 2015  g10 Code GmbH
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 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <time.h>
28 #ifdef HAVE_LOCALE_H
29 # include <locale.h>
30 #endif
31
32 #include "gpg.h"
33 #include <assuan.h>
34 #include "util.h"
35 #include "membuf.h"
36 #include "options.h"
37 #include "i18n.h"
38 #include "asshelp.h"
39 #include "keyserver.h"
40 #include "status.h"
41 #include "call-dirmngr.h"
42
43
44 /* Parameter structure used to gather status info.  */
45 struct ks_status_parm_s
46 {
47   const char *keyword; /* Look for this keyword or NULL for "SOURCE". */
48   char *source;
49 };
50
51
52 /* Parameter structure used with the KS_SEARCH command.  */
53 struct ks_search_parm_s
54 {
55   gpg_error_t lasterr;  /* Last error code.  */
56   membuf_t saveddata;   /* Buffer to build complete lines.  */
57   char *helpbuf;        /* NULL or malloced buffer.  */
58   size_t helpbufsize;   /* Allocated size of HELPBUF.  */
59   gpg_error_t (*data_cb)(void*, int, char*);  /* Callback.  */
60   void *data_cb_value;  /* First argument for DATA_CB.  */
61   struct ks_status_parm_s *stparm; /* Link to the status parameter.  */
62 };
63
64
65 /* Parameter structure used with the KS_GET command.  */
66 struct ks_get_parm_s
67 {
68   estream_t memfp;
69 };
70
71
72 /* Parameter structure used with the KS_PUT command.  */
73 struct ks_put_parm_s
74 {
75   assuan_context_t ctx;
76   kbnode_t keyblock;  /* The optional keyblock.  */
77   const void *data;   /* The key in OpenPGP binary format.  */
78   size_t datalen;     /* The length of DATA.  */
79 };
80
81
82 /* Parameter structure used with the DNS_CERT command.  */
83 struct dns_cert_parm_s
84 {
85   estream_t memfp;
86   unsigned char *fpr;
87   size_t fprlen;
88   char *url;
89 };
90
91
92 /* Data used to associate an session with dirmngr contexts.  We can't
93    use a simple one to one mapping because we sometimes need two
94    connections to the dirmngr; for example while doing a listing and
95    being in a data callback we may want to retrieve a key.  The local
96    dirmngr data takes care of this.  At the end of the session the
97    function dirmngr_deinit_session_data is called by gpg.c to cleanup
98    these resources.  Note that gpg.h defines a typedef dirmngr_local_t
99    for this structure. */
100 struct dirmngr_local_s
101 {
102   /* Link to other contexts which are used simultaneously.  */
103   struct dirmngr_local_s *next;
104
105   /* The active Assuan context. */
106   assuan_context_t ctx;
107
108   /* Flag set when the keyserver names have been send.  */
109   int set_keyservers_done;
110
111   /* Flag set to true while an operation is running on CTX.  */
112   int is_active;
113 };
114
115
116 \f
117 /* Deinitialize all session data of dirmngr pertaining to CTRL.  */
118 void
119 gpg_dirmngr_deinit_session_data (ctrl_t ctrl)
120 {
121   dirmngr_local_t dml;
122
123   while ((dml = ctrl->dirmngr_local))
124     {
125       ctrl->dirmngr_local = dml->next;
126       if (dml->is_active)
127         log_error ("oops: trying to cleanup an active dirmngr context\n");
128       else
129         assuan_release (dml->ctx);
130       xfree (dml);
131     }
132 }
133
134
135 /* Print a warning if the server's version number is less than our
136    version number.  Returns an error code on a connection problem.  */
137 static gpg_error_t
138 warn_version_mismatch (assuan_context_t ctx, const char *servername)
139 {
140   gpg_error_t err;
141   char *serverversion;
142   const char *myversion = strusage (13);
143
144   err = get_assuan_server_version (ctx, 0, &serverversion);
145   if (err)
146     log_error (_("error getting version from '%s': %s\n"),
147                servername, gpg_strerror (err));
148   else if (compare_version_strings (serverversion, myversion) < 0)
149     {
150       char *warn;
151
152       warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"),
153                            servername, serverversion, myversion);
154       if (!warn)
155         err = gpg_error_from_syserror ();
156       else
157         {
158           log_info (_("WARNING: %s\n"), warn);
159           write_status_strings (STATUS_WARNING, "server_version_mismatch 0",
160                                 " ", warn, NULL);
161           xfree (warn);
162         }
163     }
164   xfree (serverversion);
165   return err;
166 }
167
168
169 /* Try to connect to the Dirmngr via a socket or spawn it if possible.
170    Handle the server's initial greeting and set global options.  */
171 static gpg_error_t
172 create_context (ctrl_t ctrl, assuan_context_t *r_ctx)
173 {
174   gpg_error_t err;
175   assuan_context_t ctx;
176
177   *r_ctx = NULL;
178   err = start_new_dirmngr (&ctx,
179                            GPG_ERR_SOURCE_DEFAULT,
180                            opt.dirmngr_program,
181                            opt.autostart, opt.verbose, DBG_IPC,
182                            NULL /*gpg_status2*/, ctrl);
183   if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR)
184     {
185       static int shown;
186
187       if (!shown)
188         {
189           shown = 1;
190           log_info (_("no dirmngr running in this session\n"));
191         }
192     }
193   else if (!err && !(err = warn_version_mismatch (ctx, DIRMNGR_NAME)))
194     {
195       char *line;
196
197       /* Tell the dirmngr that we want to collect audit event. */
198       /* err = assuan_transact (agent_ctx, "OPTION audit-events=1", */
199       /*                        NULL, NULL, NULL, NULL, NULL, NULL); */
200       if (opt.keyserver_options.http_proxy)
201         {
202           line = xtryasprintf ("OPTION http-proxy=%s",
203                                opt.keyserver_options.http_proxy);
204           if (!line)
205             err = gpg_error_from_syserror ();
206           else
207             {
208               err = assuan_transact (ctx, line, NULL, NULL, NULL,
209                                      NULL, NULL, NULL);
210               xfree (line);
211             }
212         }
213
214       if (err)
215         ;
216       else if ((opt.keyserver_options.options & KEYSERVER_HONOR_KEYSERVER_URL))
217         {
218           /* Tell the dirmngr that this possibly privacy invading
219              option is in use.  If Dirmngr is running in Tor mode, it
220              will return an error.  */
221           err = assuan_transact (ctx, "OPTION honor-keyserver-url-used",
222                                  NULL, NULL, NULL, NULL, NULL, NULL);
223           if (gpg_err_code (err) == GPG_ERR_FORBIDDEN)
224             log_error (_("keyserver option \"honor-keyserver-url\""
225                          " may not be used in Tor mode\n"));
226           else if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION)
227             err = 0; /* Old dirmngr versions do not support this option.  */
228         }
229     }
230
231   if (err)
232     assuan_release (ctx);
233   else
234     {
235       /* audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); */
236       *r_ctx = ctx;
237     }
238
239   return err;
240 }
241
242
243 /* Get a context for accessing dirmngr.  If no context is available a
244    new one is created and - if required - dirmngr started.  On success
245    an assuan context is stored at R_CTX.  This context may only be
246    released by means of close_context.  Note that NULL is stored at
247    R_CTX on error.  */
248 static gpg_error_t
249 open_context (ctrl_t ctrl, assuan_context_t *r_ctx)
250 {
251   gpg_error_t err;
252   dirmngr_local_t dml;
253
254   *r_ctx = NULL;
255   for (;;)
256     {
257       for (dml = ctrl->dirmngr_local; dml && dml->is_active; dml = dml->next)
258         ;
259       if (dml)
260         {
261           /* Found an inactive local session - return that.  */
262           log_assert (!dml->is_active);
263
264           /* But first do the per session init if not yet done.  */
265           if (!dml->set_keyservers_done)
266             {
267               keyserver_spec_t ksi;
268
269               /* Set all configured keyservers.  We clear existing
270                  keyservers so that any keyserver configured in GPG
271                  overrides keyservers possibly still configured in Dirmngr
272                  for the session (Note that the keyserver list of a
273                  session in Dirmngr survives a RESET. */
274               for (ksi = opt.keyserver; ksi; ksi = ksi->next)
275                 {
276                   char *line;
277
278                   line = xtryasprintf
279                     ("KEYSERVER%s %s",
280                      ksi == opt.keyserver? " --clear":"", ksi->uri);
281                   if (!line)
282                     err = gpg_error_from_syserror ();
283                   else
284                     {
285                       err = assuan_transact (dml->ctx, line, NULL, NULL, NULL,
286                                              NULL, NULL, NULL);
287                       xfree (line);
288                     }
289
290                   if (err)
291                     return err;
292                 }
293
294               dml->set_keyservers_done = 1;
295             }
296
297           dml->is_active = 1;
298
299           *r_ctx = dml->ctx;
300           return 0;
301         }
302
303       dml = xtrycalloc (1, sizeof *dml);
304       if (!dml)
305         return gpg_error_from_syserror ();
306       err = create_context (ctrl, &dml->ctx);
307       if (err)
308         {
309           xfree (dml);
310           return err;
311         }
312
313       /* To be on the nPth thread safe site we need to add it to a
314          list; this is far easier than to have a lock for this
315          function.  It should not happen anyway but the code is free
316          because we need it for the is_active check above.  */
317       dml->next = ctrl->dirmngr_local;
318       ctrl->dirmngr_local = dml;
319     }
320 }
321
322
323 /* Close the assuan context CTX or return it to a pool of unused
324    contexts.  If CTX is NULL, the function does nothing.  */
325 static void
326 close_context (ctrl_t ctrl, assuan_context_t ctx)
327 {
328   dirmngr_local_t dml;
329
330   if (!ctx)
331     return;
332
333   for (dml = ctrl->dirmngr_local; dml; dml = dml->next)
334     {
335       if (dml->ctx == ctx)
336         {
337           if (!dml->is_active)
338             log_fatal ("closing inactive dirmngr context %p\n", ctx);
339           dml->is_active = 0;
340           return;
341         }
342     }
343   log_fatal ("closing unknown dirmngr ctx %p\n", ctx);
344 }
345
346
347 /* Clear the set_keyservers_done flag on context CTX.  */
348 static void
349 clear_context_flags (ctrl_t ctrl, assuan_context_t ctx)
350 {
351   dirmngr_local_t dml;
352
353   if (!ctx)
354     return;
355
356   for (dml = ctrl->dirmngr_local; dml; dml = dml->next)
357     {
358       if (dml->ctx == ctx)
359         {
360           if (!dml->is_active)
361             log_fatal ("clear_context_flags on inactive dirmngr ctx %p\n", ctx);
362           dml->set_keyservers_done = 0;
363           return;
364         }
365     }
366   log_fatal ("clear_context_flags on unknown dirmngr ctx %p\n", ctx);
367 }
368
369
370 \f
371 /* Status callback for ks_list, ks_get and ks_search.  */
372 static gpg_error_t
373 ks_status_cb (void *opaque, const char *line)
374 {
375   struct ks_status_parm_s *parm = opaque;
376   gpg_error_t err = 0;
377   const char *s, *s2;
378   const char *warn;
379
380   if ((s = has_leading_keyword (line, parm->keyword? parm->keyword : "SOURCE")))
381     {
382       if (!parm->source)
383         {
384           parm->source = xtrystrdup (s);
385           if (!parm->source)
386             err = gpg_error_from_syserror ();
387         }
388     }
389   else if ((s = has_leading_keyword (line, "WARNING")))
390     {
391       if ((s2 = has_leading_keyword (s, "tor_not_running")))
392         warn = _("Tor is not running");
393       else if ((s2 = has_leading_keyword (s, "tor_config_problem")))
394         warn = _("Tor is not properly configured");
395       else
396         warn = NULL;
397
398       if (warn)
399         {
400           log_info (_("WARNING: %s\n"), warn);
401           if (s2)
402             {
403               while (*s2 && !spacep (s2))
404                 s2++;
405               while (*s2 && spacep (s2))
406                 s2++;
407               if (*s2)
408                 print_further_info ("%s", s2);
409             }
410         }
411     }
412
413   return err;
414 }
415
416
417 \f
418 /* Run the "KEYSERVER" command to return the name of the used
419    keyserver at R_KEYSERVER.  */
420 gpg_error_t
421 gpg_dirmngr_ks_list (ctrl_t ctrl, char **r_keyserver)
422 {
423   gpg_error_t err;
424   assuan_context_t ctx;
425   struct ks_status_parm_s stparm;
426
427   memset (&stparm, 0, sizeof stparm);
428   stparm.keyword = "KEYSERVER";
429   if (r_keyserver)
430     *r_keyserver = NULL;
431
432   err = open_context (ctrl, &ctx);
433   if (err)
434     return err;
435
436   err = assuan_transact (ctx, "KEYSERVER", NULL, NULL,
437                          NULL, NULL, ks_status_cb, &stparm);
438   if (err)
439     goto leave;
440   if (!stparm.source)
441     {
442       err = gpg_error (GPG_ERR_NO_KEYSERVER);
443       goto leave;
444     }
445
446   if (r_keyserver)
447     *r_keyserver = stparm.source;
448   else
449     xfree (stparm.source);
450   stparm.source = NULL;
451
452  leave:
453   xfree (stparm.source);
454   close_context (ctrl, ctx);
455   return err;
456 }
457
458
459 \f
460 /* Data callback for the KS_SEARCH command. */
461 static gpg_error_t
462 ks_search_data_cb (void *opaque, const void *data, size_t datalen)
463 {
464   gpg_error_t err = 0;
465   struct ks_search_parm_s *parm = opaque;
466   const char *line, *s;
467   size_t rawlen, linelen;
468   char fixedbuf[256];
469
470   if (parm->lasterr)
471     return 0;
472
473   if (parm->stparm->source)
474     {
475       err = parm->data_cb (parm->data_cb_value, 1, parm->stparm->source);
476       if (err)
477         {
478           parm->lasterr = err;
479           return err;
480         }
481       /* Clear it so that we won't get back here unless the server
482          accidentally sends a second source status line.  Note that
483          will not see all accidentally sent source lines because it
484          depends on whether data lines have been send in between.  */
485       xfree (parm->stparm->source);
486       parm->stparm->source = NULL;
487     }
488
489   if (!data)
490     return 0;  /* Ignore END commands.  */
491
492   put_membuf (&parm->saveddata, data, datalen);
493
494  again:
495   line = peek_membuf (&parm->saveddata, &rawlen);
496   if (!line)
497     {
498       parm->lasterr = gpg_error_from_syserror ();
499       return parm->lasterr; /* Tell the server about our problem.  */
500     }
501   if ((s = memchr (line, '\n', rawlen)))
502     {
503       linelen = s - line;  /* That is the length excluding the LF.  */
504       if (linelen + 1 < sizeof fixedbuf)
505         {
506           /* We can use the static buffer.  */
507           memcpy (fixedbuf, line, linelen);
508           fixedbuf[linelen] = 0;
509           if (linelen && fixedbuf[linelen-1] == '\r')
510             fixedbuf[linelen-1] = 0;
511           err = parm->data_cb (parm->data_cb_value, 0, fixedbuf);
512         }
513       else
514         {
515           if (linelen + 1 >= parm->helpbufsize)
516             {
517               xfree (parm->helpbuf);
518               parm->helpbufsize = linelen + 1 + 1024;
519               parm->helpbuf = xtrymalloc (parm->helpbufsize);
520               if (!parm->helpbuf)
521                 {
522                   parm->lasterr = gpg_error_from_syserror ();
523                   return parm->lasterr;
524                 }
525             }
526           memcpy (parm->helpbuf, line, linelen);
527           parm->helpbuf[linelen] = 0;
528           if (linelen && parm->helpbuf[linelen-1] == '\r')
529             parm->helpbuf[linelen-1] = 0;
530           err = parm->data_cb (parm->data_cb_value, 0, parm->helpbuf);
531         }
532       if (err)
533         parm->lasterr = err;
534       else
535         {
536           clear_membuf (&parm->saveddata, linelen+1);
537           goto again;  /* There might be another complete line.  */
538         }
539     }
540
541   return err;
542 }
543
544
545 /* Run the KS_SEARCH command using the search string SEARCHSTR.  All
546    data lines are passed to the CB function.  That function is called
547    with CB_VALUE as its first argument, a 0 as second argument, and
548    the decoded data line as third argument.  The callback function may
549    modify the data line and it is guaranteed that this data line is a
550    complete line with a terminating 0 character but without the
551    linefeed.  NULL is passed to the callback to indicate EOF.  */
552 gpg_error_t
553 gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr,
554                        gpg_error_t (*cb)(void*, int, char *), void *cb_value)
555 {
556   gpg_error_t err;
557   assuan_context_t ctx;
558   struct ks_status_parm_s stparm;
559   struct ks_search_parm_s parm;
560   char line[ASSUAN_LINELENGTH];
561
562   err = open_context (ctrl, &ctx);
563   if (err)
564     return err;
565
566   {
567     char *escsearchstr = percent_plus_escape (searchstr);
568     if (!escsearchstr)
569       {
570         err = gpg_error_from_syserror ();
571         close_context (ctrl, ctx);
572         return err;
573       }
574     snprintf (line, sizeof line, "KS_SEARCH -- %s", escsearchstr);
575     xfree (escsearchstr);
576   }
577
578   memset (&stparm, 0, sizeof stparm);
579   memset (&parm, 0, sizeof parm);
580   init_membuf (&parm.saveddata, 1024);
581   parm.data_cb = cb;
582   parm.data_cb_value = cb_value;
583   parm.stparm = &stparm;
584
585   err = assuan_transact (ctx, line, ks_search_data_cb, &parm,
586                         NULL, NULL, ks_status_cb, &stparm);
587   if (!err)
588     err = cb (cb_value, 0, NULL);  /* Send EOF.  */
589
590   xfree (get_membuf (&parm.saveddata, NULL));
591   xfree (parm.helpbuf);
592   xfree (stparm.source);
593
594   close_context (ctrl, ctx);
595   return err;
596 }
597
598
599 \f
600 /* Data callback for the KS_GET and KS_FETCH commands. */
601 static gpg_error_t
602 ks_get_data_cb (void *opaque, const void *data, size_t datalen)
603 {
604   gpg_error_t err = 0;
605   struct ks_get_parm_s *parm = opaque;
606   size_t nwritten;
607
608   if (!data)
609     return 0;  /* Ignore END commands.  */
610
611   if (es_write (parm->memfp, data, datalen, &nwritten))
612     err = gpg_error_from_syserror ();
613
614   return err;
615 }
616
617
618 /* Run the KS_GET command using the patterns in the array PATTERN.  On
619    success an estream object is returned to retrieve the keys.  On
620    error an error code is returned and NULL stored at R_FP.
621
622    The pattern may only use search specification which a keyserver can
623    use to retrieve keys.  Because we know the format of the pattern we
624    don't need to escape the patterns before sending them to the
625    server.
626
627    If QUICK is set the dirmngr is advised to use a shorter timeout.
628
629    If R_SOURCE is not NULL the source of the data is stored as a
630    malloced string there.  If a source is not known NULL is stored.
631
632    If there are too many patterns the function returns an error.  That
633    could be fixed by issuing several search commands or by
634    implementing a different interface.  However with long keyids we
635    are able to ask for (1000-10-1)/(2+8+1) = 90 keys at once.  */
636 gpg_error_t
637 gpg_dirmngr_ks_get (ctrl_t ctrl, char **pattern,
638                     keyserver_spec_t override_keyserver, int quick,
639                     estream_t *r_fp, char **r_source)
640 {
641   gpg_error_t err;
642   assuan_context_t ctx;
643   struct ks_status_parm_s stparm;
644   struct ks_get_parm_s parm;
645   char *line = NULL;
646   size_t linelen;
647   membuf_t mb;
648   int idx;
649
650   memset (&stparm, 0, sizeof stparm);
651   memset (&parm, 0, sizeof parm);
652
653   *r_fp = NULL;
654   if (r_source)
655     *r_source = NULL;
656
657   err = open_context (ctrl, &ctx);
658   if (err)
659     return err;
660
661   /* If we have an override keyserver we first indicate that the next
662      user of the context needs to again setup the global keyservers and
663      them we send the override keyserver.  */
664   if (override_keyserver)
665     {
666       clear_context_flags (ctrl, ctx);
667       line = xtryasprintf ("KEYSERVER --clear %s", override_keyserver->uri);
668       if (!line)
669         {
670           err = gpg_error_from_syserror ();
671           goto leave;
672         }
673       err = assuan_transact (ctx, line, NULL, NULL, NULL,
674                              NULL, NULL, NULL);
675       if (err)
676         goto leave;
677
678       xfree (line);
679       line = NULL;
680     }
681
682   /* Lump all patterns into one string.  */
683   init_membuf (&mb, 1024);
684   put_membuf_str (&mb, quick? "KS_GET --quick --" : "KS_GET --");
685   for (idx=0; pattern[idx]; idx++)
686     {
687       put_membuf (&mb, " ", 1); /* Append Delimiter.  */
688       put_membuf_str (&mb, pattern[idx]);
689     }
690   put_membuf (&mb, "", 1); /* Append Nul.  */
691   line = get_membuf (&mb, &linelen);
692   if (!line)
693     {
694       err = gpg_error_from_syserror ();
695       goto leave;
696     }
697   if (linelen + 2 >= ASSUAN_LINELENGTH)
698     {
699       err = gpg_error (GPG_ERR_TOO_MANY);
700       goto leave;
701     }
702
703   parm.memfp = es_fopenmem (0, "rwb");
704   if (!parm.memfp)
705     {
706       err = gpg_error_from_syserror ();
707       goto leave;
708     }
709   err = assuan_transact (ctx, line, ks_get_data_cb, &parm,
710                          NULL, NULL, ks_status_cb, &stparm);
711   if (err)
712     goto leave;
713
714   es_rewind (parm.memfp);
715   *r_fp = parm.memfp;
716   parm.memfp = NULL;
717
718   if (r_source)
719     {
720       *r_source = stparm.source;
721       stparm.source = NULL;
722     }
723
724  leave:
725   es_fclose (parm.memfp);
726   xfree (stparm.source);
727   xfree (line);
728   close_context (ctrl, ctx);
729   return err;
730 }
731
732
733 /* Run the KS_FETCH and pass URL as argument.  On success an estream
734    object is returned to retrieve the keys.  On error an error code is
735    returned and NULL stored at R_FP.
736
737    The url is expected to point to a small set of keys; in many cases
738    only to one key.  However, schemes like finger may return several
739    keys.  Note that the configured keyservers are ignored by the
740    KS_FETCH command.  */
741 gpg_error_t
742 gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp)
743 {
744   gpg_error_t err;
745   assuan_context_t ctx;
746   struct ks_get_parm_s parm;
747   char *line = NULL;
748
749   memset (&parm, 0, sizeof parm);
750
751   *r_fp = NULL;
752
753   err = open_context (ctrl, &ctx);
754   if (err)
755     return err;
756
757   line = strconcat ("KS_FETCH -- ", url, NULL);
758   if (!line)
759     {
760       err = gpg_error_from_syserror ();
761       goto leave;
762     }
763   if (strlen (line) + 2 >= ASSUAN_LINELENGTH)
764     {
765       err = gpg_error (GPG_ERR_TOO_LARGE);
766       goto leave;
767     }
768
769   parm.memfp = es_fopenmem (0, "rwb");
770   if (!parm.memfp)
771     {
772       err = gpg_error_from_syserror ();
773       goto leave;
774     }
775   err = assuan_transact (ctx, line, ks_get_data_cb, &parm,
776                          NULL, NULL, NULL, NULL);
777   if (err)
778     goto leave;
779
780   es_rewind (parm.memfp);
781   *r_fp = parm.memfp;
782   parm.memfp = NULL;
783
784  leave:
785   es_fclose (parm.memfp);
786   xfree (line);
787   close_context (ctrl, ctx);
788   return err;
789 }
790
791
792 \f
793 static void
794 record_output (estream_t output,
795                pkttype_t type,
796                const char *validity,
797                /* The public key length or -1.  */
798                int pub_key_length,
799                /* The public key algo or -1.  */
800                int pub_key_algo,
801                /* 2 ulongs or NULL.  */
802                const u32 *keyid,
803                /* The creation / expiration date or 0.  */
804                u32 creation_date,
805                u32 expiration_date,
806                const char *userid)
807 {
808   const char *type_str = NULL;
809   char *pub_key_length_str = NULL;
810   char *pub_key_algo_str = NULL;
811   char *keyid_str = NULL;
812   char *creation_date_str = NULL;
813   char *expiration_date_str = NULL;
814   char *userid_escaped = NULL;
815
816   switch (type)
817     {
818     case PKT_PUBLIC_KEY:
819       type_str = "pub";
820       break;
821     case PKT_PUBLIC_SUBKEY:
822       type_str = "sub";
823       break;
824     case PKT_USER_ID:
825       type_str = "uid";
826       break;
827     case PKT_SIGNATURE:
828       type_str = "sig";
829       break;
830     default:
831       log_assert (! "Unhandled type.");
832     }
833
834   if (pub_key_length > 0)
835     pub_key_length_str = xasprintf ("%d", pub_key_length);
836
837   if (pub_key_algo != -1)
838     pub_key_algo_str = xasprintf ("%d", pub_key_algo);
839
840   if (keyid)
841     keyid_str = xasprintf ("%08lX%08lX", (ulong) keyid[0], (ulong) keyid[1]);
842
843   if (creation_date)
844     creation_date_str = xstrdup (colon_strtime (creation_date));
845
846   if (expiration_date)
847     expiration_date_str = xstrdup (colon_strtime (expiration_date));
848
849   /* Quote ':', '%', and any 8-bit characters.  */
850   if (userid)
851     {
852       int r;
853       int w = 0;
854
855       int len = strlen (userid);
856       /* A 100k character limit on the uid should be way more than
857          enough.  */
858       if (len > 100 * 1024)
859         len = 100 * 1024;
860
861       /* The minimum amount of space that we need.  */
862       userid_escaped = xmalloc (len * 3 + 1);
863
864       for (r = 0; r < len; r++)
865         {
866           if (userid[r] == ':' || userid[r]== '%' || (userid[r] & 0x80))
867             {
868               sprintf (&userid_escaped[w], "%%%02X", (byte) userid[r]);
869               w += 3;
870             }
871           else
872             userid_escaped[w ++] = userid[r];
873         }
874       userid_escaped[w] = '\0';
875     }
876
877   es_fprintf (output, "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n",
878               type_str,
879               validity ?: "",
880               pub_key_length_str ?: "",
881               pub_key_algo_str ?: "",
882               keyid_str ?: "",
883               creation_date_str ?: "",
884               expiration_date_str ?: "",
885               "" /* Certificate S/N */,
886               "" /* Ownertrust.  */,
887               userid_escaped ?: "",
888               "" /* Signature class.  */,
889               "" /* Key capabilities.  */,
890               "" /* Issuer certificate fingerprint.  */,
891               "" /* Flag field.  */,
892               "" /* S/N of a token.  */,
893               "" /* Hash algo.  */,
894               "" /* Curve name.  */);
895
896   xfree (userid_escaped);
897   xfree (expiration_date_str);
898   xfree (creation_date_str);
899   xfree (keyid_str);
900   xfree (pub_key_algo_str);
901   xfree (pub_key_length_str);
902 }
903
904 /* Handle the KS_PUT inquiries. */
905 static gpg_error_t
906 ks_put_inq_cb (void *opaque, const char *line)
907 {
908   struct ks_put_parm_s *parm = opaque;
909   gpg_error_t err = 0;
910
911   if (has_leading_keyword (line, "KEYBLOCK"))
912     {
913       if (parm->data)
914         err = assuan_send_data (parm->ctx, parm->data, parm->datalen);
915     }
916   else if (has_leading_keyword (line, "KEYBLOCK_INFO"))
917     {
918       kbnode_t node;
919       estream_t fp;
920
921       /* Parse the keyblock and send info lines back to the server.  */
922       fp = es_fopenmem (0, "rw,samethread");
923       if (!fp)
924         err = gpg_error_from_syserror ();
925
926       /* Note: the output format for the INFO block follows the colon
927          format as described in doc/DETAILS.  We don't actually reuse
928          the functionality from g10/keylist.c to produce the output,
929          because we don't need all of it and some of it is quite
930          expensive to generate.
931
932          The fields are (the starred fields are the ones we need):
933
934            * Field 1 - Type of record
935            * Field 2 - Validity
936            * Field 3 - Key length
937            * Field 4 - Public key algorithm
938            * Field 5 - KeyID
939            * Field 6 - Creation date
940            * Field 7 - Expiration date
941              Field 8 - Certificate S/N, UID hash, trust signature info
942              Field 9 -  Ownertrust
943            * Field 10 - User-ID
944              Field 11 - Signature class
945              Field 12 - Key capabilities
946              Field 13 - Issuer certificate fingerprint or other info
947              Field 14 - Flag field
948              Field 15 - S/N of a token
949              Field 16 - Hash algorithm
950              Field 17 - Curve name
951        */
952       for (node = parm->keyblock; !err && node; node=node->next)
953         {
954           switch (node->pkt->pkttype)
955             {
956             case PKT_PUBLIC_KEY:
957             case PKT_PUBLIC_SUBKEY:
958               {
959                 PKT_public_key *pk = node->pkt->pkt.public_key;
960
961                 char validity[3];
962                 int i;
963
964                 i = 0;
965                 if (pk->flags.revoked)
966                   validity[i ++] = 'r';
967                 if (pk->has_expired)
968                   validity[i ++] = 'e';
969                 validity[i] = '\0';
970
971                 keyid_from_pk (pk, NULL);
972
973                 record_output (fp, node->pkt->pkttype, validity,
974                                nbits_from_pk (pk), pk->pubkey_algo,
975                                pk->keyid, pk->timestamp, pk->expiredate,
976                                NULL);
977               }
978               break;
979
980             case PKT_USER_ID:
981               {
982                 PKT_user_id *uid = node->pkt->pkt.user_id;
983
984                 if (!uid->attrib_data)
985                   {
986                     char validity[3];
987                     int i;
988
989                     i = 0;
990                     if (uid->is_revoked)
991                       validity[i ++] = 'r';
992                     if (uid->is_expired)
993                       validity[i ++] = 'e';
994                     validity[i] = '\0';
995
996                     record_output (fp, node->pkt->pkttype, validity,
997                                    -1, -1, NULL,
998                                    uid->created, uid->expiredate,
999                                    uid->name);
1000                   }
1001               }
1002               break;
1003
1004               /* This bit is really for the benefit of people who
1005                  store their keys in LDAP servers.  It makes it easy
1006                  to do queries for things like "all keys signed by
1007                  Isabella".  */
1008             case PKT_SIGNATURE:
1009               {
1010                 PKT_signature *sig = node->pkt->pkt.signature;
1011
1012                 if (IS_UID_SIG (sig))
1013                   record_output (fp, node->pkt->pkttype, NULL,
1014                                  -1, -1, sig->keyid,
1015                                  sig->timestamp, sig->expiredate, NULL);
1016               }
1017               break;
1018
1019             default:
1020               continue;
1021             }
1022           /* Given that the last operation was an es_fprintf we should
1023              get the correct ERRNO if ferror indicates an error.  */
1024           if (es_ferror (fp))
1025             err = gpg_error_from_syserror ();
1026         }
1027
1028       /* Without an error and if we have an keyblock at all, send the
1029          data back.  */
1030       if (!err && parm->keyblock)
1031         {
1032           int rc;
1033           char buffer[512];
1034           size_t nread;
1035
1036           es_rewind (fp);
1037           while (!(rc=es_read (fp, buffer, sizeof buffer, &nread)) && nread)
1038             {
1039               err = assuan_send_data (parm->ctx, buffer, nread);
1040               if (err)
1041                 break;
1042             }
1043           if (!err && rc)
1044             err = gpg_error_from_syserror ();
1045         }
1046       es_fclose (fp);
1047     }
1048   else
1049     return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
1050
1051   return err;
1052 }
1053
1054
1055 /* Send a key to the configured server.  {DATA,DATLEN} contains the
1056    key in OpenPGP binary transport format.  If KEYBLOCK is not NULL it
1057    has the internal representaion of that key; this is for example
1058    used to convey meta data to LDAP keyservers.  */
1059 gpg_error_t
1060 gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock)
1061 {
1062   gpg_error_t err;
1063   assuan_context_t ctx;
1064   struct ks_put_parm_s parm;
1065
1066   memset (&parm, 0, sizeof parm);
1067
1068   /* We are going to parse the keyblock, thus we better make sure the
1069      all information is readily available.  */
1070   if (keyblock)
1071     merge_keys_and_selfsig (keyblock);
1072
1073   err = open_context (ctrl, &ctx);
1074   if (err)
1075     return err;
1076
1077   parm.ctx = ctx;
1078   parm.keyblock = keyblock;
1079   parm.data = data;
1080   parm.datalen = datalen;
1081
1082   err = assuan_transact (ctx, "KS_PUT", NULL, NULL,
1083                          ks_put_inq_cb, &parm, NULL, NULL);
1084
1085   close_context (ctrl, ctx);
1086   return err;
1087 }
1088
1089
1090 \f
1091 /* Data callback for the DNS_CERT and WKD_GET commands. */
1092 static gpg_error_t
1093 dns_cert_data_cb (void *opaque, const void *data, size_t datalen)
1094 {
1095   struct dns_cert_parm_s *parm = opaque;
1096   gpg_error_t err = 0;
1097   size_t nwritten;
1098
1099   if (!data)
1100     return 0;  /* Ignore END commands.  */
1101   if (!parm->memfp)
1102     return 0;  /* Data is not required.  */
1103
1104   if (es_write (parm->memfp, data, datalen, &nwritten))
1105     err = gpg_error_from_syserror ();
1106
1107   return err;
1108 }
1109
1110
1111 /* Status callback for the DNS_CERT command.  */
1112 static gpg_error_t
1113 dns_cert_status_cb (void *opaque, const char *line)
1114 {
1115   struct dns_cert_parm_s *parm = opaque;
1116   gpg_error_t err = 0;
1117   const char *s;
1118   size_t nbytes;
1119
1120   if ((s = has_leading_keyword (line, "FPR")))
1121     {
1122       char *buf;
1123
1124       if (!(buf = xtrystrdup (s)))
1125         err = gpg_error_from_syserror ();
1126       else if (parm->fpr)
1127         err = gpg_error (GPG_ERR_DUP_KEY);
1128       else if (!hex2str (buf, buf, strlen (buf)+1, &nbytes))
1129         err = gpg_error_from_syserror ();
1130       else if (nbytes < 20)
1131         err = gpg_error (GPG_ERR_TOO_SHORT);
1132       else
1133         {
1134           parm->fpr = xtrymalloc (nbytes);
1135           if (!parm->fpr)
1136             err = gpg_error_from_syserror ();
1137           else
1138             memcpy (parm->fpr, buf, (parm->fprlen = nbytes));
1139         }
1140       xfree (buf);
1141     }
1142   else if ((s = has_leading_keyword (line, "URL")) && *s)
1143     {
1144       if (parm->url)
1145         err = gpg_error (GPG_ERR_DUP_KEY);
1146       else if (!(parm->url = xtrystrdup (s)))
1147         err = gpg_error_from_syserror ();
1148     }
1149
1150   return err;
1151 }
1152
1153 /* Ask the dirmngr for a DNS CERT record.  Depending on the found
1154    subtypes different return values are set:
1155
1156    - For a PGP subtype a new estream with that key will be returned at
1157      R_KEY and the other return parameters are set to NULL/0.
1158
1159    - For an IPGP subtype the fingerprint is stored as a malloced block
1160      at (R_FPR,R_FPRLEN).  If an URL is available it is stored as a
1161      malloced string at R_URL; NULL is stored if there is no URL.
1162
1163    If CERTTYPE is DNS_CERTTYPE_ANY this function returns the first
1164    CERT record found with a supported type; it is expected that only
1165    one CERT record is used.  If CERTTYPE is one of the supported
1166    certtypes, only records with this certtype are considered and the
1167    first one found is returned.  All R_* args are optional.
1168
1169    If CERTTYPE is NULL the DANE method is used to fetch the key.
1170  */
1171 gpg_error_t
1172 gpg_dirmngr_dns_cert (ctrl_t ctrl, const char *name, const char *certtype,
1173                       estream_t *r_key,
1174                       unsigned char **r_fpr, size_t *r_fprlen,
1175                       char **r_url)
1176 {
1177   gpg_error_t err;
1178   assuan_context_t ctx;
1179   struct dns_cert_parm_s parm;
1180   char *line = NULL;
1181
1182   memset (&parm, 0, sizeof parm);
1183   if (r_key)
1184     *r_key = NULL;
1185   if (r_fpr)
1186     *r_fpr = NULL;
1187   if (r_fprlen)
1188     *r_fprlen = 0;
1189   if (r_url)
1190     *r_url = NULL;
1191
1192   err = open_context (ctrl, &ctx);
1193   if (err)
1194     return err;
1195
1196   line = es_bsprintf ("DNS_CERT %s %s", certtype? certtype : "--dane", name);
1197   if (!line)
1198     {
1199       err = gpg_error_from_syserror ();
1200       goto leave;
1201     }
1202   if (strlen (line) + 2 >= ASSUAN_LINELENGTH)
1203     {
1204       err = gpg_error (GPG_ERR_TOO_LARGE);
1205       goto leave;
1206     }
1207
1208   parm.memfp = es_fopenmem (0, "rwb");
1209   if (!parm.memfp)
1210     {
1211       err = gpg_error_from_syserror ();
1212       goto leave;
1213     }
1214   err = assuan_transact (ctx, line, dns_cert_data_cb, &parm,
1215                          NULL, NULL, dns_cert_status_cb, &parm);
1216   if (err)
1217     goto leave;
1218
1219   if (r_key)
1220     {
1221       es_rewind (parm.memfp);
1222       *r_key = parm.memfp;
1223       parm.memfp = NULL;
1224     }
1225
1226   if (r_fpr && parm.fpr)
1227     {
1228       *r_fpr = parm.fpr;
1229       parm.fpr = NULL;
1230     }
1231   if (r_fprlen)
1232     *r_fprlen = parm.fprlen;
1233
1234   if (r_url && parm.url)
1235     {
1236       *r_url = parm.url;
1237       parm.url = NULL;
1238     }
1239
1240  leave:
1241   xfree (parm.fpr);
1242   xfree (parm.url);
1243   es_fclose (parm.memfp);
1244   xfree (line);
1245   close_context (ctrl, ctx);
1246   return err;
1247 }
1248
1249
1250 /* Ask the dirmngr for PKA info.  On success the retrieved fingerprint
1251    is returned in a malloced buffer at R_FPR and its length is stored
1252    at R_FPRLEN.  If an URL is available it is stored as a malloced
1253    string at R_URL.  On error all return values are set to NULL/0.  */
1254 gpg_error_t
1255 gpg_dirmngr_get_pka (ctrl_t ctrl, const char *userid,
1256                      unsigned char **r_fpr, size_t *r_fprlen,
1257                      char **r_url)
1258 {
1259   gpg_error_t err;
1260   assuan_context_t ctx;
1261   struct dns_cert_parm_s parm;
1262   char *line = NULL;
1263
1264   memset (&parm, 0, sizeof parm);
1265   if (r_fpr)
1266     *r_fpr = NULL;
1267   if (r_fprlen)
1268     *r_fprlen = 0;
1269   if (r_url)
1270     *r_url = NULL;
1271
1272   err = open_context (ctrl, &ctx);
1273   if (err)
1274     return err;
1275
1276   line = es_bsprintf ("DNS_CERT --pka -- %s", userid);
1277   if (!line)
1278     {
1279       err = gpg_error_from_syserror ();
1280       goto leave;
1281     }
1282   if (strlen (line) + 2 >= ASSUAN_LINELENGTH)
1283     {
1284       err = gpg_error (GPG_ERR_TOO_LARGE);
1285       goto leave;
1286     }
1287
1288   err = assuan_transact (ctx, line, dns_cert_data_cb, &parm,
1289                          NULL, NULL, dns_cert_status_cb, &parm);
1290   if (err)
1291     goto leave;
1292
1293   if (r_fpr && parm.fpr)
1294     {
1295       *r_fpr = parm.fpr;
1296       parm.fpr = NULL;
1297     }
1298   if (r_fprlen)
1299     *r_fprlen = parm.fprlen;
1300
1301   if (r_url && parm.url)
1302     {
1303       *r_url = parm.url;
1304       parm.url = NULL;
1305     }
1306
1307  leave:
1308   xfree (parm.fpr);
1309   xfree (parm.url);
1310   xfree (line);
1311   close_context (ctrl, ctx);
1312   return err;
1313 }
1314
1315
1316 \f
1317 /* Ask the dirmngr to retrieve a key via the Web Key Directory
1318  * protocol.  If QUICK is set the dirmngr is advised to use a shorter
1319  * timeout.  On success a new estream with the key is stored at R_KEY.
1320  */
1321 gpg_error_t
1322 gpg_dirmngr_wkd_get (ctrl_t ctrl, const char *name, int quick, estream_t *r_key)
1323 {
1324   gpg_error_t err;
1325   assuan_context_t ctx;
1326   struct dns_cert_parm_s parm;
1327   char *line = NULL;
1328
1329   memset (&parm, 0, sizeof parm);
1330
1331   err = open_context (ctrl, &ctx);
1332   if (err)
1333     return err;
1334
1335   line = es_bsprintf ("WKD_GET%s -- %s", quick?" --quick":"", name);
1336   if (!line)
1337     {
1338       err = gpg_error_from_syserror ();
1339       goto leave;
1340     }
1341   if (strlen (line) + 2 >= ASSUAN_LINELENGTH)
1342     {
1343       err = gpg_error (GPG_ERR_TOO_LARGE);
1344       goto leave;
1345     }
1346
1347   parm.memfp = es_fopenmem (0, "rwb");
1348   if (!parm.memfp)
1349     {
1350       err = gpg_error_from_syserror ();
1351       goto leave;
1352     }
1353   err = assuan_transact (ctx, line, dns_cert_data_cb, &parm,
1354                          NULL, NULL, NULL, &parm);
1355   if (err)
1356     goto leave;
1357
1358   if (r_key)
1359     {
1360       es_rewind (parm.memfp);
1361       *r_key = parm.memfp;
1362       parm.memfp = NULL;
1363     }
1364
1365  leave:
1366   xfree (parm.fpr);
1367   xfree (parm.url);
1368   es_fclose (parm.memfp);
1369   xfree (line);
1370   close_context (ctrl, ctx);
1371   return err;
1372 }