chiark / gitweb /
gpg: Fix searching for mail addresses in keyrings.
[gnupg2.git] / tools / gpg-wks-client.c
1 /* gpg-wks-client.c - A client for the Web Key Service protocols.
2  * Copyright (C) 2016 Werner Koch
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 <https://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "util.h"
26 #include "status.h"
27 #include "i18n.h"
28 #include "sysutils.h"
29 #include "init.h"
30 #include "asshelp.h"
31 #include "userids.h"
32 #include "ccparray.h"
33 #include "exectool.h"
34 #include "mbox-util.h"
35 #include "name-value.h"
36 #include "call-dirmngr.h"
37 #include "mime-maker.h"
38 #include "send-mail.h"
39 #include "gpg-wks.h"
40
41
42 /* Constants to identify the commands and options. */
43 enum cmd_and_opt_values
44   {
45     aNull = 0,
46
47     oQuiet      = 'q',
48     oVerbose    = 'v',
49     oOutput     = 'o',
50
51     oDebug      = 500,
52
53     aSupported,
54     aCheck,
55     aCreate,
56     aReceive,
57     aRead,
58
59     oGpgProgram,
60     oSend,
61     oFakeSubmissionAddr,
62     oStatusFD,
63
64     oDummy
65   };
66
67
68 /* The list of commands and options. */
69 static ARGPARSE_OPTS opts[] = {
70   ARGPARSE_group (300, ("@Commands:\n ")),
71
72   ARGPARSE_c (aSupported, "supported",
73               ("check whether provider supports WKS")),
74   ARGPARSE_c (aCheck, "check",
75               ("check whether a key is available")),
76   ARGPARSE_c (aCreate,   "create",
77               ("create a publication request")),
78   ARGPARSE_c (aReceive,   "receive",
79               ("receive a MIME confirmation request")),
80   ARGPARSE_c (aRead,      "read",
81               ("receive a plain text confirmation request")),
82
83   ARGPARSE_group (301, ("@\nOptions:\n ")),
84
85   ARGPARSE_s_n (oVerbose, "verbose", ("verbose")),
86   ARGPARSE_s_n (oQuiet, "quiet",  ("be somewhat more quiet")),
87   ARGPARSE_s_s (oDebug, "debug", "@"),
88   ARGPARSE_s_s (oGpgProgram, "gpg", "@"),
89   ARGPARSE_s_n (oSend, "send", "send the mail using sendmail"),
90   ARGPARSE_s_s (oOutput, "output", "|FILE|write the mail to FILE"),
91   ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")),
92
93   ARGPARSE_s_s (oFakeSubmissionAddr, "fake-submission-addr", "@"),
94
95   ARGPARSE_end ()
96 };
97
98
99 /* The list of supported debug flags.  */
100 static struct debug_flags_s debug_flags [] =
101   {
102     { DBG_MIME_VALUE   , "mime"    },
103     { DBG_PARSER_VALUE , "parser"  },
104     { DBG_CRYPTO_VALUE , "crypto"  },
105     { DBG_MEMORY_VALUE , "memory"  },
106     { DBG_MEMSTAT_VALUE, "memstat" },
107     { DBG_IPC_VALUE    , "ipc"     },
108     { DBG_EXTPROG_VALUE, "extprog" },
109     { 0, NULL }
110   };
111
112
113
114 /* Value of the option --fake-submission-addr.  */
115 const char *fake_submission_addr;
116
117
118 static void wrong_args (const char *text) GPGRT_ATTR_NORETURN;
119 static gpg_error_t command_supported (char *userid);
120 static gpg_error_t command_check (char *userid);
121 static gpg_error_t command_send (const char *fingerprint, char *userid);
122 static gpg_error_t encrypt_response (estream_t *r_output, estream_t input,
123                                      const char *addrspec,
124                                      const char *fingerprint);
125 static gpg_error_t read_confirmation_request (estream_t msg);
126 static gpg_error_t command_receive_cb (void *opaque,
127                                        const char *mediatype, estream_t fp,
128                                        unsigned int flags);
129
130
131 \f
132 /* Print usage information and and provide strings for help. */
133 static const char *
134 my_strusage( int level )
135 {
136   const char *p;
137
138   switch (level)
139     {
140     case 11: p = "gpg-wks-client (@GNUPG@)";
141       break;
142     case 13: p = VERSION; break;
143     case 17: p = PRINTABLE_OS_NAME; break;
144     case 19: p = ("Please report bugs to <@EMAIL@>.\n"); break;
145
146     case 1:
147     case 40:
148       p = ("Usage: gpg-wks-client [command] [options] [args] (-h for help)");
149       break;
150     case 41:
151       p = ("Syntax: gpg-wks-client [command] [options] [args]\n"
152            "Client for the Web Key Service\n");
153       break;
154
155     default: p = NULL; break;
156     }
157   return p;
158 }
159
160
161 static void
162 wrong_args (const char *text)
163 {
164   es_fprintf (es_stderr, _("usage: %s [options] %s\n"), strusage (11), text);
165   exit (2);
166 }
167
168
169 \f
170 /* Command line parsing.  */
171 static enum cmd_and_opt_values
172 parse_arguments (ARGPARSE_ARGS *pargs, ARGPARSE_OPTS *popts)
173 {
174   enum cmd_and_opt_values cmd = 0;
175   int no_more_options = 0;
176
177   while (!no_more_options && optfile_parse (NULL, NULL, NULL, pargs, popts))
178     {
179       switch (pargs->r_opt)
180         {
181         case oQuiet:     opt.quiet = 1; break;
182         case oVerbose:   opt.verbose++; break;
183         case oDebug:
184           if (parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags))
185             {
186               pargs->r_opt = ARGPARSE_INVALID_ARG;
187               pargs->err = ARGPARSE_PRINT_ERROR;
188             }
189           break;
190
191         case oGpgProgram:
192           opt.gpg_program = pargs->r.ret_str;
193           break;
194         case oSend:
195           opt.use_sendmail = 1;
196           break;
197         case oOutput:
198           opt.output = pargs->r.ret_str;
199           break;
200         case oFakeSubmissionAddr:
201           fake_submission_addr = pargs->r.ret_str;
202           break;
203         case oStatusFD:
204           wks_set_status_fd (translate_sys2libc_fd_int (pargs->r.ret_int, 1));
205           break;
206
207         case aSupported:
208         case aCreate:
209         case aReceive:
210         case aRead:
211         case aCheck:
212           cmd = pargs->r_opt;
213           break;
214
215         default: pargs->err = 2; break;
216         }
217     }
218
219   return cmd;
220 }
221
222
223 \f
224 /* gpg-wks-client main. */
225 int
226 main (int argc, char **argv)
227 {
228   gpg_error_t err;
229   ARGPARSE_ARGS pargs;
230   enum cmd_and_opt_values cmd;
231
232   gnupg_reopen_std ("gpg-wks-client");
233   set_strusage (my_strusage);
234   log_set_prefix ("gpg-wks-client", GPGRT_LOG_WITH_PREFIX);
235
236   /* Make sure that our subsystems are ready.  */
237   i18n_init();
238   init_common_subsystems (&argc, &argv);
239
240   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
241   setup_libassuan_logging (&opt.debug, NULL);
242
243   /* Parse the command line. */
244   pargs.argc  = &argc;
245   pargs.argv  = &argv;
246   pargs.flags = ARGPARSE_FLAG_KEEP;
247   cmd = parse_arguments (&pargs, opts);
248
249   if (log_get_errorcount (0))
250     exit (2);
251
252   /* Print a warning if an argument looks like an option.  */
253   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
254     {
255       int i;
256
257       for (i=0; i < argc; i++)
258         if (argv[i][0] == '-' && argv[i][1] == '-')
259           log_info (("NOTE: '%s' is not considered an option\n"), argv[i]);
260     }
261
262   /* Set defaults for non given options.  */
263   if (!opt.gpg_program)
264     opt.gpg_program = gnupg_module_name (GNUPG_MODULE_NAME_GPG);
265
266   /* Tell call-dirmngr what options we want.  */
267   set_dirmngr_options (opt.verbose, (opt.debug & DBG_IPC_VALUE), 1);
268
269   /* Run the selected command.  */
270   switch (cmd)
271     {
272     case aSupported:
273       if (argc != 1)
274         wrong_args ("--supported USER-ID");
275       err = command_supported (argv[0]);
276       if (err && gpg_err_code (err) != GPG_ERR_FALSE)
277         log_error ("checking support failed: %s\n", gpg_strerror (err));
278       break;
279
280     case aCreate:
281       if (argc != 2)
282         wrong_args ("--create FINGERPRINT USER-ID");
283       err = command_send (argv[0], argv[1]);
284       if (err)
285         log_error ("creating request failed: %s\n", gpg_strerror (err));
286       break;
287
288     case aReceive:
289       if (argc)
290         wrong_args ("--receive < MIME-DATA");
291       err = wks_receive (es_stdin, command_receive_cb, NULL);
292       if (err)
293         log_error ("processing mail failed: %s\n", gpg_strerror (err));
294       break;
295
296     case aRead:
297       if (argc)
298         wrong_args ("--read < WKS-DATA");
299       err = read_confirmation_request (es_stdin);
300       if (err)
301         log_error ("processing mail failed: %s\n", gpg_strerror (err));
302       break;
303
304     case aCheck:
305       if (argc != 1)
306         wrong_args ("--check USER-ID");
307       err = command_check (argv[0]);
308       break;
309
310     default:
311       usage (1);
312       err = 0;
313       break;
314     }
315
316   if (err)
317     wks_write_status (STATUS_FAILURE, "- %u", err);
318   else if (log_get_errorcount (0))
319     wks_write_status (STATUS_FAILURE, "- %u", GPG_ERR_GENERAL);
320   else
321     wks_write_status (STATUS_SUCCESS, NULL);
322   return log_get_errorcount (0)? 1:0;
323 }
324
325
326 \f
327 struct get_key_status_parm_s
328 {
329   const char *fpr;
330   int found;
331   int count;
332 };
333
334 static void
335 get_key_status_cb (void *opaque, const char *keyword, char *args)
336 {
337   struct get_key_status_parm_s *parm = opaque;
338
339   /*log_debug ("%s: %s\n", keyword, args);*/
340   if (!strcmp (keyword, "EXPORTED"))
341     {
342       parm->count++;
343       if (!ascii_strcasecmp (args, parm->fpr))
344         parm->found = 1;
345     }
346 }
347
348
349 /* Get a key by fingerprint from gpg's keyring and make sure that the
350  * mail address ADDRSPEC is included in the key.  The key is returned
351  * as a new memory stream at R_KEY.
352  *
353  * Fixme: After we have implemented import and export filters for gpg
354  * this function shall only return a key with just this user id.  */
355 static gpg_error_t
356 get_key (estream_t *r_key, const char *fingerprint, const char *addrspec)
357 {
358   gpg_error_t err;
359   ccparray_t ccp;
360   const char **argv = NULL;
361   estream_t key = NULL;
362   struct get_key_status_parm_s parm;
363   char *filterexp = NULL;
364
365   memset (&parm, 0, sizeof parm);
366
367   *r_key = NULL;
368
369   key = es_fopenmem (0, "w+b");
370   if (!key)
371     {
372       err = gpg_error_from_syserror ();
373       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
374       goto leave;
375     }
376   /* Prefix the key with the MIME content type.  */
377   es_fputs ("Content-Type: application/pgp-keys\n"
378             "\n", key);
379
380   filterexp = es_bsprintf ("keep-uid=mbox = %s", addrspec);
381   if (!filterexp)
382     {
383       err = gpg_error_from_syserror ();
384       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
385       goto leave;
386     }
387
388   ccparray_init (&ccp, 0);
389
390   ccparray_put (&ccp, "--no-options");
391   if (!opt.verbose)
392     ccparray_put (&ccp, "--quiet");
393   else if (opt.verbose > 1)
394     ccparray_put (&ccp, "--verbose");
395   ccparray_put (&ccp, "--batch");
396   ccparray_put (&ccp, "--status-fd=2");
397   ccparray_put (&ccp, "--always-trust");
398   ccparray_put (&ccp, "--armor");
399   ccparray_put (&ccp, "--export-options=export-minimal");
400   ccparray_put (&ccp, "--export-filter");
401   ccparray_put (&ccp, filterexp);
402   ccparray_put (&ccp, "--export");
403   ccparray_put (&ccp, "--");
404   ccparray_put (&ccp, fingerprint);
405
406   ccparray_put (&ccp, NULL);
407   argv = ccparray_get (&ccp, NULL);
408   if (!argv)
409     {
410       err = gpg_error_from_syserror ();
411       goto leave;
412     }
413   parm.fpr = fingerprint;
414   err = gnupg_exec_tool_stream (opt.gpg_program, argv, NULL,
415                                 NULL, key,
416                                 get_key_status_cb, &parm);
417   if (!err && parm.count > 1)
418     err = gpg_error (GPG_ERR_TOO_MANY);
419   else if (!err && !parm.found)
420     err = gpg_error (GPG_ERR_NOT_FOUND);
421   if (err)
422     {
423       log_error ("export failed: %s\n", gpg_strerror (err));
424       goto leave;
425     }
426
427   es_rewind (key);
428   *r_key = key;
429   key = NULL;
430
431  leave:
432   es_fclose (key);
433   xfree (argv);
434   xfree (filterexp);
435   return err;
436 }
437
438
439 \f
440 static void
441 decrypt_stream_status_cb (void *opaque, const char *keyword, char *args)
442 {
443   (void)opaque;
444
445   if (DBG_CRYPTO)
446     log_debug ("gpg status: %s %s\n", keyword, args);
447 }
448
449
450 /* Decrypt the INPUT stream to a new stream which is stored at success
451  * at R_OUTPUT.  */
452 static gpg_error_t
453 decrypt_stream (estream_t *r_output, estream_t input)
454 {
455   gpg_error_t err;
456   ccparray_t ccp;
457   const char **argv;
458   estream_t output;
459
460   *r_output = NULL;
461
462   output = es_fopenmem (0, "w+b");
463   if (!output)
464     {
465       err = gpg_error_from_syserror ();
466       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
467       return err;
468     }
469
470   ccparray_init (&ccp, 0);
471
472   ccparray_put (&ccp, "--no-options");
473   /* We limit the output to 64 KiB to avoid DoS using compression
474    * tricks.  A regular client will anyway only send a minimal key;
475    * that is one w/o key signatures and attribute packets.  */
476   ccparray_put (&ccp, "--max-output=0x10000");
477   if (!opt.verbose)
478     ccparray_put (&ccp, "--quiet");
479   else if (opt.verbose > 1)
480     ccparray_put (&ccp, "--verbose");
481   ccparray_put (&ccp, "--batch");
482   ccparray_put (&ccp, "--status-fd=2");
483   ccparray_put (&ccp, "--decrypt");
484   ccparray_put (&ccp, "--");
485
486   ccparray_put (&ccp, NULL);
487   argv = ccparray_get (&ccp, NULL);
488   if (!argv)
489     {
490       err = gpg_error_from_syserror ();
491       goto leave;
492     }
493   err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
494                                 NULL, output,
495                                 decrypt_stream_status_cb, NULL);
496   if (err)
497     {
498       log_error ("decryption failed: %s\n", gpg_strerror (err));
499       goto leave;
500     }
501   else if (opt.verbose)
502     log_info ("decryption succeeded\n");
503
504   es_rewind (output);
505   *r_output = output;
506   output = NULL;
507
508  leave:
509   es_fclose (output);
510   xfree (argv);
511   return err;
512 }
513
514
515
516 \f
517 /* Check whether the  provider supports the WKS protocol.  */
518 static gpg_error_t
519 command_supported (char *userid)
520 {
521   gpg_error_t err;
522   char *addrspec = NULL;
523   char *submission_to = NULL;
524
525   addrspec = mailbox_from_userid (userid);
526   if (!addrspec)
527     {
528       log_error (_("\"%s\" is not a proper mail address\n"), userid);
529       err = gpg_error (GPG_ERR_INV_USER_ID);
530       goto leave;
531     }
532
533   /* Get the submission address.  */
534   err = wkd_get_submission_address (addrspec, &submission_to);
535   if (err)
536     {
537       if (gpg_err_code (err) == GPG_ERR_NO_DATA
538           || gpg_err_code (err) == GPG_ERR_UNKNOWN_HOST)
539         {
540           if (opt.verbose)
541             log_info ("provider for '%s' does NOT support WKS (%s)\n",
542                       addrspec, gpg_strerror (err));
543           err = gpg_error (GPG_ERR_FALSE);
544           log_inc_errorcount ();
545         }
546       goto leave;
547     }
548   if (opt.verbose)
549     log_info ("provider for '%s' supports WKS\n", addrspec);
550
551  leave:
552   xfree (submission_to);
553   xfree (addrspec);
554   return err;
555 }
556
557
558 \f
559 /* Check whether the key for USERID is available in the WKD.  */
560 static gpg_error_t
561 command_check (char *userid)
562 {
563   gpg_error_t err;
564   char *addrspec = NULL;
565   estream_t key = NULL;
566   char *fpr = NULL;
567   strlist_t mboxes = NULL;
568   strlist_t sl;
569   int found = 0;
570
571   addrspec = mailbox_from_userid (userid);
572   if (!addrspec)
573     {
574       log_error (_("\"%s\" is not a proper mail address\n"), userid);
575       err = gpg_error (GPG_ERR_INV_USER_ID);
576       goto leave;
577     }
578
579   /* Get the submission address.  */
580   err = wkd_get_key (addrspec, &key);
581   switch (gpg_err_code (err))
582     {
583     case 0:
584       if (opt.verbose)
585         log_info ("public key for '%s' found via WKD\n", addrspec);
586       /* Fixme: Check that the key contains the user id.  */
587       break;
588
589     case GPG_ERR_NO_DATA: /* No such key.  */
590       if (opt.verbose)
591         log_info ("public key for '%s' NOT found via WKD\n", addrspec);
592       err = gpg_error (GPG_ERR_NO_PUBKEY);
593       log_inc_errorcount ();
594       break;
595
596     case GPG_ERR_UNKNOWN_HOST:
597       if (opt.verbose)
598         log_info ("error looking up '%s' via WKD: %s\n",
599                   addrspec, gpg_strerror (err));
600       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
601       break;
602
603     default:
604       log_error ("error looking up '%s' via WKD: %s\n",
605                  addrspec, gpg_strerror (err));
606       break;
607     }
608
609   if (err)
610     goto leave;
611
612   /* Look closer at the key.  */
613   err = wks_list_key (key, &fpr, &mboxes);
614   if (err || !fpr)
615     {
616       log_error ("error parsing key: %s\n",
617                  err? gpg_strerror (err) : "no fingerprint found");
618       err = gpg_error (GPG_ERR_NO_PUBKEY);
619       goto leave;
620     }
621
622   if (opt.verbose)
623     log_info ("fingerprint: %s\n", fpr);
624
625   for (sl = mboxes; sl; sl = sl->next)
626     {
627       if (!strcmp (sl->d, addrspec))
628         found = 1;
629       if (opt.verbose)
630         log_info ("  addr-spec: %s\n", sl->d);
631     }
632   if (!found)
633     {
634       log_error ("public key for '%s' has no user id with the mail address\n",
635                  addrspec);
636       err = gpg_error (GPG_ERR_CERT_REVOKED);
637     }
638
639  leave:
640   xfree (fpr);
641   free_strlist (mboxes);
642   es_fclose (key);
643   xfree (addrspec);
644   return err;
645 }
646
647
648 \f
649 /* Locate the key by fingerprint and userid and send a publication
650  * request.  */
651 static gpg_error_t
652 command_send (const char *fingerprint, char *userid)
653 {
654   gpg_error_t err;
655   KEYDB_SEARCH_DESC desc;
656   char *addrspec = NULL;
657   estream_t key = NULL;
658   estream_t keyenc = NULL;
659   char *submission_to = NULL;
660   mime_maker_t mime = NULL;
661   struct policy_flags_s policy;
662
663   memset (&policy, 0, sizeof policy);
664
665   if (classify_user_id (fingerprint, &desc, 1)
666       || !(desc.mode == KEYDB_SEARCH_MODE_FPR
667            || desc.mode == KEYDB_SEARCH_MODE_FPR20))
668     {
669       log_error (_("\"%s\" is not a fingerprint\n"), fingerprint);
670       err = gpg_error (GPG_ERR_INV_NAME);
671       goto leave;
672     }
673   addrspec = mailbox_from_userid (userid);
674   if (!addrspec)
675     {
676       log_error (_("\"%s\" is not a proper mail address\n"), userid);
677       err = gpg_error (GPG_ERR_INV_USER_ID);
678       goto leave;
679     }
680   err = get_key (&key, fingerprint, addrspec);
681   if (err)
682     goto leave;
683
684   /* Get the submission address.  */
685   if (fake_submission_addr)
686     {
687       submission_to = xstrdup (fake_submission_addr);
688       err = 0;
689     }
690   else
691     err = wkd_get_submission_address (addrspec, &submission_to);
692   if (err)
693     {
694       char *domain = strchr (addrspec, '@');
695       if (domain)
696         domain = domain + 1;
697       log_error (_("looking up WKS submission address for %s: %s\n"),
698                  domain ? domain : addrspec, gpg_strerror (err));
699       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
700         log_error (_("this domain probably doesn't support WKS.\n"));
701       goto leave;
702     }
703   log_info ("submitting request to '%s'\n", submission_to);
704
705   /* Get the policy flags.  */
706   if (!fake_submission_addr)
707     {
708       estream_t mbuf;
709
710       err = wkd_get_policy_flags (addrspec, &mbuf);
711       if (err && gpg_err_code (err) != GPG_ERR_NO_DATA)
712         {
713           log_error ("error reading policy flags for '%s': %s\n",
714                      submission_to, gpg_strerror (err));
715           goto leave;
716         }
717       if (mbuf)
718         {
719           err = wks_parse_policy (&policy, mbuf, 1);
720           es_fclose (mbuf);
721           if (err)
722             goto leave;
723         }
724     }
725
726   if (policy.auth_submit)
727     log_info ("no confirmation required for '%s'\n", addrspec);
728
729   /* Encrypt the key part.  */
730   es_rewind (key);
731   err = encrypt_response (&keyenc, key, submission_to, fingerprint);
732   if (err)
733     goto leave;
734   es_fclose (key);
735   key = NULL;
736
737
738   /* Send the key.  */
739   err = mime_maker_new (&mime, NULL);
740   if (err)
741     goto leave;
742   err = mime_maker_add_header (mime, "From", addrspec);
743   if (err)
744     goto leave;
745   err = mime_maker_add_header (mime, "To", submission_to);
746   if (err)
747     goto leave;
748   err = mime_maker_add_header (mime, "Subject", "Key publishing request");
749   if (err)
750     goto leave;
751
752   /* Tell server that we support draft version 3.  */
753   err = mime_maker_add_header (mime, "Wks-Draft-Version", "3");
754   if (err)
755     goto leave;
756
757   err = mime_maker_add_header (mime, "Content-Type",
758                                "multipart/encrypted; "
759                                "protocol=\"application/pgp-encrypted\"");
760   if (err)
761     goto leave;
762   err = mime_maker_add_container (mime);
763   if (err)
764     goto leave;
765
766   err = mime_maker_add_header (mime, "Content-Type",
767                                "application/pgp-encrypted");
768   if (err)
769     goto leave;
770   err = mime_maker_add_body (mime, "Version: 1\n");
771   if (err)
772     goto leave;
773   err = mime_maker_add_header (mime, "Content-Type",
774                                "application/octet-stream");
775   if (err)
776     goto leave;
777
778   err = mime_maker_add_stream (mime, &keyenc);
779   if (err)
780     goto leave;
781
782   err = wks_send_mime (mime);
783
784  leave:
785   mime_maker_release (mime);
786   xfree (submission_to);
787   es_fclose (keyenc);
788   es_fclose (key);
789   xfree (addrspec);
790   return err;
791 }
792
793
794 \f
795 static void
796 encrypt_response_status_cb (void *opaque, const char *keyword, char *args)
797 {
798   gpg_error_t *failure = opaque;
799   char *fields[2];
800
801   if (DBG_CRYPTO)
802     log_debug ("gpg status: %s %s\n", keyword, args);
803
804   if (!strcmp (keyword, "FAILURE"))
805     {
806       if (split_fields (args, fields, DIM (fields)) >= 2
807           && !strcmp (fields[0], "encrypt"))
808         *failure = strtoul (fields[1], NULL, 10);
809     }
810
811 }
812
813
814 /* Encrypt the INPUT stream to a new stream which is stored at success
815  * at R_OUTPUT.  Encryption is done for ADDRSPEC and for FINGERPRINT
816  * (so that the sent message may later be inspected by the user).  We
817  * currently retrieve that key from the WKD, DANE, or from "local".
818  * "local" is last to prefer the latest key version but use a local
819  * copy in case we are working offline.  It might be useful for the
820  * server to send the fingerprint of its encryption key - or even the
821  * entire key back.  */
822 static gpg_error_t
823 encrypt_response (estream_t *r_output, estream_t input, const char *addrspec,
824                   const char *fingerprint)
825 {
826   gpg_error_t err;
827   ccparray_t ccp;
828   const char **argv;
829   estream_t output;
830   gpg_error_t gpg_err = 0;
831
832   *r_output = NULL;
833
834   output = es_fopenmem (0, "w+b");
835   if (!output)
836     {
837       err = gpg_error_from_syserror ();
838       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
839       return err;
840     }
841
842   ccparray_init (&ccp, 0);
843
844   ccparray_put (&ccp, "--no-options");
845   if (!opt.verbose)
846     ccparray_put (&ccp, "--quiet");
847   else if (opt.verbose > 1)
848     ccparray_put (&ccp, "--verbose");
849   ccparray_put (&ccp, "--batch");
850   ccparray_put (&ccp, "--status-fd=2");
851   ccparray_put (&ccp, "--always-trust");
852   ccparray_put (&ccp, "--armor");
853   if (fake_submission_addr)
854     ccparray_put (&ccp, "--auto-key-locate=clear,local");
855   else
856     ccparray_put (&ccp, "--auto-key-locate=clear,wkd,dane,local");
857   ccparray_put (&ccp, "--recipient");
858   ccparray_put (&ccp, addrspec);
859   ccparray_put (&ccp, "--recipient");
860   ccparray_put (&ccp, fingerprint);
861   ccparray_put (&ccp, "--encrypt");
862   ccparray_put (&ccp, "--");
863
864   ccparray_put (&ccp, NULL);
865   argv = ccparray_get (&ccp, NULL);
866   if (!argv)
867     {
868       err = gpg_error_from_syserror ();
869       goto leave;
870     }
871   err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
872                                 NULL, output,
873                                 encrypt_response_status_cb, &gpg_err);
874   if (err)
875     {
876       if (gpg_err)
877         err = gpg_err;
878       log_error ("encryption failed: %s\n", gpg_strerror (err));
879       goto leave;
880     }
881
882   es_rewind (output);
883   *r_output = output;
884   output = NULL;
885
886  leave:
887   es_fclose (output);
888   xfree (argv);
889   return err;
890 }
891
892
893 static gpg_error_t
894 send_confirmation_response (const char *sender, const char *address,
895                             const char *nonce, int encrypt,
896                             const char *fingerprint)
897 {
898   gpg_error_t err;
899   estream_t body = NULL;
900   estream_t bodyenc = NULL;
901   mime_maker_t mime = NULL;
902
903   body = es_fopenmem (0, "w+b");
904   if (!body)
905     {
906       err = gpg_error_from_syserror ();
907       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
908       return err;
909     }
910
911   /* It is fine to use 8 bit encoding because that is encrypted and
912    * only our client will see it.  */
913   if (encrypt)
914     {
915       es_fputs ("Content-Type: application/vnd.gnupg.wks\n"
916                 "Content-Transfer-Encoding: 8bit\n"
917                 "\n",
918                 body);
919     }
920
921   es_fprintf (body, ("type: confirmation-response\n"
922                      "sender: %s\n"
923                      "address: %s\n"
924                      "nonce: %s\n"),
925               sender,
926               address,
927               nonce);
928
929   es_rewind (body);
930   if (encrypt)
931     {
932       err = encrypt_response (&bodyenc, body, sender, fingerprint);
933       if (err)
934         goto leave;
935       es_fclose (body);
936       body = NULL;
937     }
938
939   err = mime_maker_new (&mime, NULL);
940   if (err)
941     goto leave;
942   err = mime_maker_add_header (mime, "From", address);
943   if (err)
944     goto leave;
945   err = mime_maker_add_header (mime, "To", sender);
946   if (err)
947     goto leave;
948   err = mime_maker_add_header (mime, "Subject", "Key publication confirmation");
949   if (err)
950     goto leave;
951
952   if (encrypt)
953     {
954       err = mime_maker_add_header (mime, "Content-Type",
955                                    "multipart/encrypted; "
956                                    "protocol=\"application/pgp-encrypted\"");
957       if (err)
958         goto leave;
959       err = mime_maker_add_container (mime);
960       if (err)
961         goto leave;
962
963       err = mime_maker_add_header (mime, "Content-Type",
964                                    "application/pgp-encrypted");
965       if (err)
966         goto leave;
967       err = mime_maker_add_body (mime, "Version: 1\n");
968       if (err)
969         goto leave;
970       err = mime_maker_add_header (mime, "Content-Type",
971                                    "application/octet-stream");
972       if (err)
973         goto leave;
974
975       err = mime_maker_add_stream (mime, &bodyenc);
976       if (err)
977         goto leave;
978     }
979   else
980     {
981       err = mime_maker_add_header (mime, "Content-Type",
982                                    "application/vnd.gnupg.wks");
983       if (err)
984         goto leave;
985       err = mime_maker_add_stream (mime, &body);
986       if (err)
987         goto leave;
988     }
989
990   err = wks_send_mime (mime);
991
992  leave:
993   mime_maker_release (mime);
994   es_fclose (bodyenc);
995   es_fclose (body);
996   return err;
997 }
998
999
1000 /* Reply to a confirmation request.  The MSG has already been
1001  * decrypted and we only need to send the nonce back.  */
1002 static gpg_error_t
1003 process_confirmation_request (estream_t msg)
1004 {
1005   gpg_error_t err;
1006   nvc_t nvc;
1007   nve_t item;
1008   const char *value, *sender, *address, *fingerprint, *nonce;
1009
1010   err = nvc_parse (&nvc, NULL, msg);
1011   if (err)
1012     {
1013       log_error ("parsing the WKS message failed: %s\n", gpg_strerror (err));
1014       goto leave;
1015     }
1016
1017   if (DBG_MIME)
1018     {
1019       log_debug ("request follows:\n");
1020       nvc_write (nvc, log_get_stream ());
1021     }
1022
1023   /* Check that this is a confirmation request.  */
1024   if (!((item = nvc_lookup (nvc, "type:")) && (value = nve_value (item))
1025         && !strcmp (value, "confirmation-request")))
1026     {
1027       if (item && value)
1028         log_error ("received unexpected wks message '%s'\n", value);
1029       else
1030         log_error ("received invalid wks message: %s\n", "'type' missing");
1031       err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
1032       goto leave;
1033     }
1034
1035   /* Get the fingerprint.  */
1036   if (!((item = nvc_lookup (nvc, "fingerprint:"))
1037         && (value = nve_value (item))
1038         && strlen (value) >= 40))
1039     {
1040       log_error ("received invalid wks message: %s\n",
1041                  "'fingerprint' missing or invalid");
1042       err = gpg_error (GPG_ERR_INV_DATA);
1043       goto leave;
1044     }
1045   fingerprint = value;
1046
1047   /* FIXME: Check that the fingerprint matches the key used to decrypt the
1048    * message.  */
1049
1050   /* Get the address.  */
1051   if (!((item = nvc_lookup (nvc, "address:")) && (value = nve_value (item))
1052         && is_valid_mailbox (value)))
1053     {
1054       log_error ("received invalid wks message: %s\n",
1055                  "'address' missing or invalid");
1056       err = gpg_error (GPG_ERR_INV_DATA);
1057       goto leave;
1058     }
1059   address = value;
1060   /* FIXME: Check that the "address" matches the User ID we want to
1061    * publish.  Also get the "fingerprint" and compare that to our to
1062    * be published key.  Further we should make sure that we actually
1063    * decrypted using that fingerprint (which is a bit problematic if
1064    * --read is used). */
1065
1066   /* Get the sender.  */
1067   if (!((item = nvc_lookup (nvc, "sender:")) && (value = nve_value (item))
1068         && is_valid_mailbox (value)))
1069     {
1070       log_error ("received invalid wks message: %s\n",
1071                  "'sender' missing or invalid");
1072       err = gpg_error (GPG_ERR_INV_DATA);
1073       goto leave;
1074     }
1075   sender = value;
1076   /* FIXME: Check that the "sender" matches the From: address.  */
1077
1078   /* Get the nonce.  */
1079   if (!((item = nvc_lookup (nvc, "nonce:")) && (value = nve_value (item))
1080         && strlen (value) > 16))
1081     {
1082       log_error ("received invalid wks message: %s\n",
1083                  "'nonce' missing or too short");
1084       err = gpg_error (GPG_ERR_INV_DATA);
1085       goto leave;
1086     }
1087   nonce = value;
1088
1089   /* Send the confirmation.  If no key was found, try again without
1090    * encryption.  */
1091   err = send_confirmation_response (sender, address, nonce, 1, fingerprint);
1092   if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
1093     {
1094       log_info ("no encryption key found - sending response in the clear\n");
1095       err = send_confirmation_response (sender, address, nonce, 0, NULL);
1096     }
1097
1098  leave:
1099   nvc_release (nvc);
1100   return err;
1101 }
1102
1103
1104 /* Read a confirmation request and decrypt it if needed.  This
1105  * function may not be used with a mail or MIME message but only with
1106  * the actual encrypted or plaintext WKS data.  */
1107 static gpg_error_t
1108 read_confirmation_request (estream_t msg)
1109 {
1110   gpg_error_t err;
1111   int c;
1112   estream_t plaintext = NULL;
1113
1114   /* We take a really simple approach to check whether MSG is
1115    * encrypted: We know that an encrypted message is always armored
1116    * and thus starts with a few dashes.  It is even sufficient to
1117    * check for a single dash, because that can never be a proper first
1118    * WKS data octet.  We need to skip leading spaces, though. */
1119   while ((c = es_fgetc (msg)) == ' ' || c == '\t' || c == '\r' || c == '\n')
1120     ;
1121   if (c == EOF)
1122     {
1123       log_error ("can't process an empty message\n");
1124       return gpg_error (GPG_ERR_INV_DATA);
1125     }
1126   if (es_ungetc (c, msg) != c)
1127     {
1128       log_error ("error ungetting octet from message\n");
1129       return gpg_error (GPG_ERR_INTERNAL);
1130     }
1131
1132   if (c != '-')
1133     err = process_confirmation_request (msg);
1134   else
1135     {
1136       err = decrypt_stream (&plaintext, msg);
1137       if (err)
1138         log_error ("decryption failed: %s\n", gpg_strerror (err));
1139       else
1140         err = process_confirmation_request (plaintext);
1141     }
1142
1143   es_fclose (plaintext);
1144   return err;
1145 }
1146
1147
1148 /* Called from the MIME receiver to process the plain text data in MSG.  */
1149 static gpg_error_t
1150 command_receive_cb (void *opaque, const char *mediatype,
1151                     estream_t msg, unsigned int flags)
1152 {
1153   gpg_error_t err;
1154
1155   (void)opaque;
1156   (void)flags;
1157
1158   if (!strcmp (mediatype, "application/vnd.gnupg.wks"))
1159     err = read_confirmation_request (msg);
1160   else
1161     {
1162       log_info ("ignoring unexpected message of type '%s'\n", mediatype);
1163       err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
1164     }
1165
1166   return err;
1167 }