Imported Upstream version 2.1.3
[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 "call-dirmngr.h"
42
43
44 /* Parameter structure used to gather status info.  */
45 struct ks_status_parm_s
46 {
47   char *source;
48 };
49
50
51 /* Parameter structure used with the KS_SEARCH command.  */
52 struct ks_search_parm_s
53 {
54   gpg_error_t lasterr;  /* Last error code.  */
55   membuf_t saveddata;   /* Buffer to build complete lines.  */
56   char *helpbuf;        /* NULL or malloced buffer.  */
57   size_t helpbufsize;   /* Allocated size of HELPBUF.  */
58   gpg_error_t (*data_cb)(void*, int, char*);  /* Callback.  */
59   void *data_cb_value;  /* First argument for DATA_CB.  */
60   struct ks_status_parm_s *stparm; /* Link to the status parameter.  */
61 };
62
63
64 /* Parameter structure used with the KS_GET command.  */
65 struct ks_get_parm_s
66 {
67   estream_t memfp;
68 };
69
70
71 /* Parameter structure used with the KS_PUT command.  */
72 struct ks_put_parm_s
73 {
74   assuan_context_t ctx;
75   kbnode_t keyblock;  /* The optional keyblock.  */
76   const void *data;   /* The key in OpenPGP binary format.  */
77   size_t datalen;     /* The length of DATA.  */
78 };
79
80
81 /* Data used to associate an session with dirmngr contexts.  We can't
82    use a simple one to one mapping because we sometimes need two
83    connections to the dirmngr; for example while doing a listing and
84    being in a data callback we may want to retrieve a key.  The local
85    dirmngr data takes care of this.  At the end of the session the
86    function dirmngr_deinit_session_data is called by gpg.c to cleanup
87    these resources.  Note that gpg.h defines a typedef dirmngr_local_t
88    for this structure. */
89 struct dirmngr_local_s
90 {
91   /* Link to other contexts which are used simultaneously.  */
92   struct dirmngr_local_s *next;
93
94   /* The active Assuan context. */
95   assuan_context_t ctx;
96
97   /* Flag set to true while an operation is running on CTX.  */
98   int is_active;
99 };
100
101
102 \f
103 /* Deinitialize all session data of dirmngr pertaining to CTRL.  */
104 void
105 gpg_dirmngr_deinit_session_data (ctrl_t ctrl)
106 {
107   dirmngr_local_t dml;
108
109   while ((dml = ctrl->dirmngr_local))
110     {
111       ctrl->dirmngr_local = dml->next;
112       if (dml->is_active)
113         log_error ("oops: trying to cleanup an active dirmngr context\n");
114       else
115         assuan_release (dml->ctx);
116       xfree (dml);
117     }
118 }
119
120
121 /* Try to connect to the Dirmngr via a socket or spawn it if possible.
122    Handle the server's initial greeting and set global options.  */
123 static gpg_error_t
124 create_context (ctrl_t ctrl, assuan_context_t *r_ctx)
125 {
126   gpg_error_t err;
127   assuan_context_t ctx;
128
129   *r_ctx = NULL;
130   err = start_new_dirmngr (&ctx,
131                            GPG_ERR_SOURCE_DEFAULT,
132                            opt.homedir,
133                            opt.dirmngr_program,
134                            opt.autostart, opt.verbose, DBG_IPC,
135                            NULL /*gpg_status2*/, ctrl);
136   if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR)
137     {
138       static int shown;
139
140       if (!shown)
141         {
142           shown = 1;
143           log_info (_("no dirmngr running in this session\n"));
144         }
145     }
146   else if (!err)
147     {
148       keyserver_spec_t ksi;
149
150       /* Tell the dirmngr that we want to collect audit event. */
151       /* err = assuan_transact (agent_ctx, "OPTION audit-events=1", */
152       /*                        NULL, NULL, NULL, NULL, NULL, NULL); */
153
154       /* Set all configured keyservers.  We clear existing keyservers
155          so that any keyserver configured in GPG overrides keyservers
156          possibly still configured in Dirmngr for the session (Note
157          that the keyserver list of a session in Dirmngr survives a
158          RESET. */
159       for (ksi = opt.keyserver; !err && ksi; ksi = ksi->next)
160         {
161           char *line;
162
163           line = xtryasprintf ("KEYSERVER%s %s",
164                                ksi == opt.keyserver? " --clear":"", ksi->uri);
165           if (!line)
166             err = gpg_error_from_syserror ();
167           else
168             {
169               err = assuan_transact (ctx, line,
170                                      NULL, NULL, NULL, NULL, NULL, NULL);
171               xfree (line);
172             }
173         }
174     }
175
176   if (err)
177     assuan_release (ctx);
178   else
179     {
180       /* audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); */
181       *r_ctx = ctx;
182     }
183
184   return err;
185 }
186
187
188 /* Get a context for accessing dirmngr.  If no context is available a
189    new one is created and - if required - dirmngr started.  On success
190    an assuan context is stored at R_CTX.  This context may only be
191    released by means of close_context.  Note that NULL is stored at
192    R_CTX on error.  */
193 static gpg_error_t
194 open_context (ctrl_t ctrl, assuan_context_t *r_ctx)
195 {
196   gpg_error_t err;
197   dirmngr_local_t dml;
198
199   *r_ctx = NULL;
200   for (;;)
201     {
202       for (dml = ctrl->dirmngr_local; dml && dml->is_active; dml = dml->next)
203         ;
204       if (dml)
205         {
206           /* Found an inactive local session - return that.  */
207           assert (!dml->is_active);
208           dml->is_active = 1;
209           *r_ctx = dml->ctx;
210           return 0;
211         }
212
213       dml = xtrycalloc (1, sizeof *dml);
214       if (!dml)
215         return gpg_error_from_syserror ();
216       err = create_context (ctrl, &dml->ctx);
217       if (err)
218         {
219           xfree (dml);
220           return err;
221         }
222       /* To be on the nPth thread safe site we need to add it to a
223          list; this is far easier than to have a lock for this
224          function.  It should not happen anyway but the code is free
225          because we need it for the is_active check above.  */
226       dml->next = ctrl->dirmngr_local;
227       ctrl->dirmngr_local = dml;
228     }
229 }
230
231
232 /* Close the assuan context CTX or return it to a pool of unused
233    contexts.  If CTX is NULL, the function does nothing.  */
234 static void
235 close_context (ctrl_t ctrl, assuan_context_t ctx)
236 {
237   dirmngr_local_t dml;
238
239   if (!ctx)
240     return;
241
242   for (dml = ctrl->dirmngr_local; dml; dml = dml->next)
243     {
244       if (dml->ctx == ctx)
245         {
246           if (!dml->is_active)
247             log_fatal ("closing inactive dirmngr context %p\n", ctx);
248           dml->is_active = 0;
249           return;
250         }
251     }
252   log_fatal ("closing unknown dirmngr ctx %p\n", ctx);
253 }
254
255
256 \f
257 /* Status callback for ks_get and ks_search.  */
258 static gpg_error_t
259 ks_status_cb (void *opaque, const char *line)
260 {
261   struct ks_status_parm_s *parm = opaque;
262   gpg_error_t err = 0;
263   const char *s;
264
265   if ((s = has_leading_keyword (line, "SOURCE")))
266     {
267       if (!parm->source)
268         {
269           parm->source = xtrystrdup (s);
270           if (!parm->source)
271             err = gpg_error_from_syserror ();
272         }
273     }
274
275   return err;
276 }
277
278
279 \f
280 /* Data callback for the KS_SEARCH command. */
281 static gpg_error_t
282 ks_search_data_cb (void *opaque, const void *data, size_t datalen)
283 {
284   gpg_error_t err = 0;
285   struct ks_search_parm_s *parm = opaque;
286   const char *line, *s;
287   size_t rawlen, linelen;
288   char fixedbuf[256];
289
290   if (parm->lasterr)
291     return 0;
292
293   if (parm->stparm->source)
294     {
295       err = parm->data_cb (parm->data_cb_value, 1, parm->stparm->source);
296       if (err)
297         {
298           parm->lasterr = err;
299           return err;
300         }
301       /* Clear it so that we won't get back here unless the server
302          accidentally sends a second source status line.  Note that
303          will not see all accidentally sent source lines because it
304          depends on whether data lines have been send in between.  */
305       xfree (parm->stparm->source);
306       parm->stparm->source = NULL;
307     }
308
309   if (!data)
310     return 0;  /* Ignore END commands.  */
311
312   put_membuf (&parm->saveddata, data, datalen);
313
314  again:
315   line = peek_membuf (&parm->saveddata, &rawlen);
316   if (!line)
317     {
318       parm->lasterr = gpg_error_from_syserror ();
319       return parm->lasterr; /* Tell the server about our problem.  */
320     }
321   if ((s = memchr (line, '\n', rawlen)))
322     {
323       linelen = s - line;  /* That is the length excluding the LF.  */
324       if (linelen + 1 < sizeof fixedbuf)
325         {
326           /* We can use the static buffer.  */
327           memcpy (fixedbuf, line, linelen);
328           fixedbuf[linelen] = 0;
329           if (linelen && fixedbuf[linelen-1] == '\r')
330             fixedbuf[linelen-1] = 0;
331           err = parm->data_cb (parm->data_cb_value, 0, fixedbuf);
332         }
333       else
334         {
335           if (linelen + 1 >= parm->helpbufsize)
336             {
337               xfree (parm->helpbuf);
338               parm->helpbufsize = linelen + 1 + 1024;
339               parm->helpbuf = xtrymalloc (parm->helpbufsize);
340               if (!parm->helpbuf)
341                 {
342                   parm->lasterr = gpg_error_from_syserror ();
343                   return parm->lasterr;
344                 }
345             }
346           memcpy (parm->helpbuf, line, linelen);
347           parm->helpbuf[linelen] = 0;
348           if (linelen && parm->helpbuf[linelen-1] == '\r')
349             parm->helpbuf[linelen-1] = 0;
350           err = parm->data_cb (parm->data_cb_value, 0, parm->helpbuf);
351         }
352       if (err)
353         parm->lasterr = err;
354       else
355         {
356           clear_membuf (&parm->saveddata, linelen+1);
357           goto again;  /* There might be another complete line.  */
358         }
359     }
360
361   return err;
362 }
363
364
365 /* Run the KS_SEARCH command using the search string SEARCHSTR.  All
366    data lines are passed to the CB function.  That function is called
367    with CB_VALUE as its first argument, a 0 as second argument, and
368    the decoded data line as third argument.  The callback function may
369    modify the data line and it is guaranteed that this data line is a
370    complete line with a terminating 0 character but without the
371    linefeed.  NULL is passed to the callback to indicate EOF.  */
372 gpg_error_t
373 gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr,
374                        gpg_error_t (*cb)(void*, int, char *), void *cb_value)
375 {
376   gpg_error_t err;
377   assuan_context_t ctx;
378   struct ks_status_parm_s stparm;
379   struct ks_search_parm_s parm;
380   char line[ASSUAN_LINELENGTH];
381
382   err = open_context (ctrl, &ctx);
383   if (err)
384     return err;
385
386   {
387     char *escsearchstr = percent_plus_escape (searchstr);
388     if (!escsearchstr)
389       {
390         err = gpg_error_from_syserror ();
391         close_context (ctrl, ctx);
392         return err;
393       }
394     snprintf (line, sizeof line, "KS_SEARCH -- %s", escsearchstr);
395     xfree (escsearchstr);
396   }
397
398   memset (&stparm, 0, sizeof stparm);
399   memset (&parm, 0, sizeof parm);
400   init_membuf (&parm.saveddata, 1024);
401   parm.data_cb = cb;
402   parm.data_cb_value = cb_value;
403   parm.stparm = &stparm;
404
405   err = assuan_transact (ctx, line, ks_search_data_cb, &parm,
406                         NULL, NULL, ks_status_cb, &stparm);
407   if (!err)
408     err = cb (cb_value, 0, NULL);  /* Send EOF.  */
409
410   xfree (get_membuf (&parm.saveddata, NULL));
411   xfree (parm.helpbuf);
412   xfree (stparm.source);
413
414   close_context (ctrl, ctx);
415   return err;
416 }
417
418
419 \f
420 /* Data callback for the KS_GET and KS_FETCH commands. */
421 static gpg_error_t
422 ks_get_data_cb (void *opaque, const void *data, size_t datalen)
423 {
424   gpg_error_t err = 0;
425   struct ks_get_parm_s *parm = opaque;
426   size_t nwritten;
427
428   if (!data)
429     return 0;  /* Ignore END commands.  */
430
431   if (es_write (parm->memfp, data, datalen, &nwritten))
432     err = gpg_error_from_syserror ();
433
434   return err;
435 }
436
437
438 /* Run the KS_GET command using the patterns in the array PATTERN.  On
439    success an estream object is returned to retrieve the keys.  On
440    error an error code is returned and NULL stored at R_FP.
441
442    The pattern may only use search specification which a keyserver can
443    use to retrieve keys.  Because we know the format of the pattern we
444    don't need to escape the patterns before sending them to the
445    server.
446
447    If R_SOURCE is not NULL the source of the data is stored as a
448    malloced string there.  If a source is not known NULL is stored.
449
450    If there are too many patterns the function returns an error.  That
451    could be fixed by issuing several search commands or by
452    implementing a different interface.  However with long keyids we
453    are able to ask for (1000-10-1)/(2+8+1) = 90 keys at once.  */
454 gpg_error_t
455 gpg_dirmngr_ks_get (ctrl_t ctrl, char **pattern,
456                     estream_t *r_fp, char **r_source)
457 {
458   gpg_error_t err;
459   assuan_context_t ctx;
460   struct ks_status_parm_s stparm;
461   struct ks_get_parm_s parm;
462   char *line = NULL;
463   size_t linelen;
464   membuf_t mb;
465   int idx;
466
467   memset (&stparm, 0, sizeof stparm);
468   memset (&parm, 0, sizeof parm);
469
470   *r_fp = NULL;
471   if (r_source)
472     *r_source = NULL;
473
474   err = open_context (ctrl, &ctx);
475   if (err)
476     return err;
477
478   /* Lump all patterns into one string.  */
479   init_membuf (&mb, 1024);
480   put_membuf_str (&mb, "KS_GET --");
481   for (idx=0; pattern[idx]; idx++)
482     {
483       put_membuf (&mb, " ", 1); /* Append Delimiter.  */
484       put_membuf_str (&mb, pattern[idx]);
485     }
486   put_membuf (&mb, "", 1); /* Append Nul.  */
487   line = get_membuf (&mb, &linelen);
488   if (!line)
489     {
490       err = gpg_error_from_syserror ();
491       goto leave;
492     }
493   if (linelen + 2 >= ASSUAN_LINELENGTH)
494     {
495       err = gpg_error (GPG_ERR_TOO_MANY);
496       goto leave;
497     }
498
499   parm.memfp = es_fopenmem (0, "rwb");
500   if (!parm.memfp)
501     {
502       err = gpg_error_from_syserror ();
503       goto leave;
504     }
505   err = assuan_transact (ctx, line, ks_get_data_cb, &parm,
506                          NULL, NULL, ks_status_cb, &stparm);
507   if (err)
508     goto leave;
509
510   es_rewind (parm.memfp);
511   *r_fp = parm.memfp;
512   parm.memfp = NULL;
513
514   if (r_source)
515     {
516       *r_source = stparm.source;
517       stparm.source = NULL;
518     }
519
520  leave:
521   es_fclose (parm.memfp);
522   xfree (stparm.source);
523   xfree (line);
524   close_context (ctrl, ctx);
525   return err;
526 }
527
528
529 /* Run the KS_FETCH and pass URL as argument.  On success an estream
530    object is returned to retrieve the keys.  On error an error code is
531    returned and NULL stored at R_FP.
532
533    The url is expected to point to a small set of keys; in many cases
534    only to one key.  However, schemes like finger may return several
535    keys.  Note that the configured keyservers are ignored by the
536    KS_FETCH command.  */
537 gpg_error_t
538 gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp)
539 {
540   gpg_error_t err;
541   assuan_context_t ctx;
542   struct ks_get_parm_s parm;
543   char *line = NULL;
544
545   memset (&parm, 0, sizeof parm);
546
547   *r_fp = NULL;
548
549   err = open_context (ctrl, &ctx);
550   if (err)
551     return err;
552
553   line = strconcat ("KS_FETCH -- ", url, NULL);
554   if (!line)
555     {
556       err = gpg_error_from_syserror ();
557       goto leave;
558     }
559   if (strlen (line) + 2 >= ASSUAN_LINELENGTH)
560     {
561       err = gpg_error (GPG_ERR_TOO_LARGE);
562       goto leave;
563     }
564
565   parm.memfp = es_fopenmem (0, "rwb");
566   if (!parm.memfp)
567     {
568       err = gpg_error_from_syserror ();
569       goto leave;
570     }
571   err = assuan_transact (ctx, line, ks_get_data_cb, &parm,
572                          NULL, NULL, NULL, NULL);
573   if (err)
574     goto leave;
575
576   es_rewind (parm.memfp);
577   *r_fp = parm.memfp;
578   parm.memfp = NULL;
579
580  leave:
581   es_fclose (parm.memfp);
582   xfree (line);
583   close_context (ctrl, ctx);
584   return err;
585 }
586
587
588 \f
589 static void
590 record_output (estream_t output,
591                pkttype_t type,
592                const char *validity,
593                /* The public key length or -1.  */
594                int pub_key_length,
595                /* The public key algo or -1.  */
596                int pub_key_algo,
597                /* 2 ulongs or NULL.  */
598                const u32 *keyid,
599                /* The creation / expiration date or 0.  */
600                u32 creation_date,
601                u32 expiration_date,
602                const char *userid)
603 {
604   const char *type_str = NULL;
605   char *pub_key_length_str = NULL;
606   char *pub_key_algo_str = NULL;
607   char *keyid_str = NULL;
608   char *creation_date_str = NULL;
609   char *expiration_date_str = NULL;
610   char *userid_escaped = NULL;
611
612   switch (type)
613     {
614     case PKT_PUBLIC_KEY:
615       type_str = "pub";
616       break;
617     case PKT_PUBLIC_SUBKEY:
618       type_str = "sub";
619       break;
620     case PKT_USER_ID:
621       type_str = "uid";
622       break;
623     case PKT_SIGNATURE:
624       type_str = "sig";
625       break;
626     default:
627       assert (! "Unhandled type.");
628     }
629
630   if (pub_key_length > 0)
631     pub_key_length_str = xasprintf ("%d", pub_key_length);
632
633   if (pub_key_algo != -1)
634     pub_key_algo_str = xasprintf ("%d", pub_key_algo);
635
636   if (keyid)
637     keyid_str = xasprintf ("%08lX%08lX", (ulong) keyid[0], (ulong) keyid[1]);
638
639   if (creation_date)
640     creation_date_str = xstrdup (colon_strtime (creation_date));
641
642   if (expiration_date)
643     expiration_date_str = xstrdup (colon_strtime (expiration_date));
644
645   /* Quote ':', '%', and any 8-bit characters.  */
646   if (userid)
647     {
648       int r;
649       int w = 0;
650
651       int len = strlen (userid);
652       /* A 100k character limit on the uid should be way more than
653          enough.  */
654       if (len > 100 * 1024)
655         len = 100 * 1024;
656
657       /* The minimum amount of space that we need.  */
658       userid_escaped = xmalloc (len * 3 + 1);
659
660       for (r = 0; r < len; r++)
661         {
662           if (userid[r] == ':' || userid[r]== '%' || (userid[r] & 0x80))
663             {
664               sprintf (&userid_escaped[w], "%%%02X", (byte) userid[r]);
665               w += 3;
666             }
667           else
668             userid_escaped[w ++] = userid[r];
669         }
670       userid_escaped[w] = '\0';
671     }
672
673   es_fprintf (output, "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n",
674               type_str,
675               validity ?: "",
676               pub_key_length_str ?: "",
677               pub_key_algo_str ?: "",
678               keyid_str ?: "",
679               creation_date_str ?: "",
680               expiration_date_str ?: "",
681               "" /* Certificate S/N */,
682               "" /* Ownertrust.  */,
683               userid_escaped ?: "",
684               "" /* Signature class.  */,
685               "" /* Key capabilities.  */,
686               "" /* Issuer certificate fingerprint.  */,
687               "" /* Flag field.  */,
688               "" /* S/N of a token.  */,
689               "" /* Hash algo.  */,
690               "" /* Curve name.  */);
691
692   xfree (userid_escaped);
693   xfree (expiration_date_str);
694   xfree (creation_date_str);
695   xfree (keyid_str);
696   xfree (pub_key_algo_str);
697   xfree (pub_key_length_str);
698 }
699
700 /* Handle the KS_PUT inquiries. */
701 static gpg_error_t
702 ks_put_inq_cb (void *opaque, const char *line)
703 {
704   struct ks_put_parm_s *parm = opaque;
705   gpg_error_t err = 0;
706
707   if (has_leading_keyword (line, "KEYBLOCK"))
708     {
709       if (parm->data)
710         err = assuan_send_data (parm->ctx, parm->data, parm->datalen);
711     }
712   else if (has_leading_keyword (line, "KEYBLOCK_INFO"))
713     {
714       kbnode_t node;
715       estream_t fp;
716
717       /* Parse the keyblock and send info lines back to the server.  */
718       fp = es_fopenmem (0, "rw,samethread");
719       if (!fp)
720         err = gpg_error_from_syserror ();
721
722       /* Note: the output format for the INFO block follows the colon
723          format as described in doc/DETAILS.  We don't actually reuse
724          the functionality from g10/keylist.c to produce the output,
725          because we don't need all of it and some of it is quite
726          expensive to generate.
727
728          The fields are (the starred fields are the ones we need):
729
730            * Field 1 - Type of record
731            * Field 2 - Validity
732            * Field 3 - Key length
733            * Field 4 - Public key algorithm
734            * Field 5 - KeyID
735            * Field 6 - Creation date
736            * Field 7 - Expiration date
737              Field 8 - Certificate S/N, UID hash, trust signature info
738              Field 9 -  Ownertrust
739            * Field 10 - User-ID
740              Field 11 - Signature class
741              Field 12 - Key capabilities
742              Field 13 - Issuer certificate fingerprint or other info
743              Field 14 - Flag field
744              Field 15 - S/N of a token
745              Field 16 - Hash algorithm
746              Field 17 - Curve name
747        */
748       for (node = parm->keyblock; !err && node; node=node->next)
749         {
750           switch (node->pkt->pkttype)
751             {
752             case PKT_PUBLIC_KEY:
753             case PKT_PUBLIC_SUBKEY:
754               {
755                 PKT_public_key *pk = node->pkt->pkt.public_key;
756
757                 char validity[3];
758                 int i;
759
760                 i = 0;
761                 if (pk->flags.revoked)
762                   validity[i ++] = 'r';
763                 if (pk->has_expired)
764                   validity[i ++] = 'e';
765                 validity[i] = '\0';
766
767                 keyid_from_pk (pk, NULL);
768
769                 record_output (fp, node->pkt->pkttype, validity,
770                                nbits_from_pk (pk), pk->pubkey_algo,
771                                pk->keyid, pk->timestamp, pk->expiredate,
772                                NULL);
773               }
774               break;
775
776             case PKT_USER_ID:
777               {
778                 PKT_user_id *uid = node->pkt->pkt.user_id;
779
780                 if (!uid->attrib_data)
781                   {
782                     char validity[3];
783                     int i;
784
785                     i = 0;
786                     if (uid->is_revoked)
787                       validity[i ++] = 'r';
788                     if (uid->is_expired)
789                       validity[i ++] = 'e';
790                     validity[i] = '\0';
791
792                     record_output (fp, node->pkt->pkttype, validity,
793                                    -1, -1, NULL,
794                                    uid->created, uid->expiredate,
795                                    uid->name);
796                   }
797               }
798               break;
799
800               /* This bit is really for the benefit of people who
801                  store their keys in LDAP servers.  It makes it easy
802                  to do queries for things like "all keys signed by
803                  Isabella".  */
804             case PKT_SIGNATURE:
805               {
806                 PKT_signature *sig = node->pkt->pkt.signature;
807
808                 if (IS_UID_SIG (sig))
809                   record_output (fp, node->pkt->pkttype, NULL,
810                                  -1, -1, sig->keyid,
811                                  sig->timestamp, sig->expiredate, NULL);
812               }
813               break;
814
815             default:
816               continue;
817             }
818           /* Given that the last operation was an es_fprintf we should
819              get the correct ERRNO if ferror indicates an error.  */
820           if (es_ferror (fp))
821             err = gpg_error_from_syserror ();
822         }
823
824       /* Without an error and if we have an keyblock at all, send the
825          data back.  */
826       if (!err && parm->keyblock)
827         {
828           int rc;
829           char buffer[512];
830           size_t nread;
831
832           es_rewind (fp);
833           while (!(rc=es_read (fp, buffer, sizeof buffer, &nread)) && nread)
834             {
835               err = assuan_send_data (parm->ctx, buffer, nread);
836               if (err)
837                 break;
838             }
839           if (!err && rc)
840             err = gpg_error_from_syserror ();
841         }
842       es_fclose (fp);
843     }
844   else
845     return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
846
847   return err;
848 }
849
850
851 /* Send a key to the configured server.  {DATA,DATLEN} contains the
852    key in OpenPGP binary transport format.  If KEYBLOCK is not NULL it
853    has the internal representaion of that key; this is for example
854    used to convey meta data to LDAP keyservers.  */
855 gpg_error_t
856 gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock)
857 {
858   gpg_error_t err;
859   assuan_context_t ctx;
860   struct ks_put_parm_s parm;
861
862   memset (&parm, 0, sizeof parm);
863
864   /* We are going to parse the keyblock, thus we better make sure the
865      all information is readily available.  */
866   if (keyblock)
867     merge_keys_and_selfsig (keyblock);
868
869   err = open_context (ctrl, &ctx);
870   if (err)
871     return err;
872
873   parm.ctx = ctx;
874   parm.keyblock = keyblock;
875   parm.data = data;
876   parm.datalen = datalen;
877
878   err = assuan_transact (ctx, "KS_PUT", NULL, NULL,
879                          ks_put_inq_cb, &parm, NULL, NULL);
880
881   close_context (ctrl, ctx);
882   return err;
883 }