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