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