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