chiark / gitweb /
agent: Allow threads to interrupt main select loop with SIGCONT.
[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     goto leave;
694   log_info ("submitting request to '%s'\n", submission_to);
695
696   /* Get the policy flags.  */
697   if (!fake_submission_addr)
698     {
699       estream_t mbuf;
700
701       err = wkd_get_policy_flags (addrspec, &mbuf);
702       if (err)
703         {
704           log_error ("error reading policy flags for '%s': %s\n",
705                      submission_to, gpg_strerror (err));
706           goto leave;
707       }
708       if (mbuf)
709         {
710           err = wks_parse_policy (&policy, mbuf, 1);
711           es_fclose (mbuf);
712           if (err)
713             goto leave;
714         }
715     }
716
717   if (policy.auth_submit)
718     log_info ("no confirmation required for '%s'\n", addrspec);
719
720   /* Encrypt the key part.  */
721   es_rewind (key);
722   err = encrypt_response (&keyenc, key, submission_to, fingerprint);
723   if (err)
724     goto leave;
725   es_fclose (key);
726   key = NULL;
727
728
729   /* Send the key.  */
730   err = mime_maker_new (&mime, NULL);
731   if (err)
732     goto leave;
733   err = mime_maker_add_header (mime, "From", addrspec);
734   if (err)
735     goto leave;
736   err = mime_maker_add_header (mime, "To", submission_to);
737   if (err)
738     goto leave;
739   err = mime_maker_add_header (mime, "Subject", "Key publishing request");
740   if (err)
741     goto leave;
742
743   /* Tell server that we support draft version 3.  */
744   err = mime_maker_add_header (mime, "Wks-Draft-Version", "3");
745   if (err)
746     goto leave;
747
748   err = mime_maker_add_header (mime, "Content-Type",
749                                "multipart/encrypted; "
750                                "protocol=\"application/pgp-encrypted\"");
751   if (err)
752     goto leave;
753   err = mime_maker_add_container (mime);
754   if (err)
755     goto leave;
756
757   err = mime_maker_add_header (mime, "Content-Type",
758                                "application/pgp-encrypted");
759   if (err)
760     goto leave;
761   err = mime_maker_add_body (mime, "Version: 1\n");
762   if (err)
763     goto leave;
764   err = mime_maker_add_header (mime, "Content-Type",
765                                "application/octet-stream");
766   if (err)
767     goto leave;
768
769   err = mime_maker_add_stream (mime, &keyenc);
770   if (err)
771     goto leave;
772
773   err = wks_send_mime (mime);
774
775  leave:
776   mime_maker_release (mime);
777   xfree (submission_to);
778   es_fclose (keyenc);
779   es_fclose (key);
780   xfree (addrspec);
781   return err;
782 }
783
784
785 \f
786 static void
787 encrypt_response_status_cb (void *opaque, const char *keyword, char *args)
788 {
789   gpg_error_t *failure = opaque;
790   char *fields[2];
791
792   if (DBG_CRYPTO)
793     log_debug ("gpg status: %s %s\n", keyword, args);
794
795   if (!strcmp (keyword, "FAILURE"))
796     {
797       if (split_fields (args, fields, DIM (fields)) >= 2
798           && !strcmp (fields[0], "encrypt"))
799         *failure = strtoul (fields[1], NULL, 10);
800     }
801
802 }
803
804
805 /* Encrypt the INPUT stream to a new stream which is stored at success
806  * at R_OUTPUT.  Encryption is done for ADDRSPEC and for FINGERPRINT
807  * (so that the sent message may later be inspected by the user).  We
808  * currently retrieve that key from the WKD, DANE, or from "local".
809  * "local" is last to prefer the latest key version but use a local
810  * copy in case we are working offline.  It might be useful for the
811  * server to send the fingerprint of its encryption key - or even the
812  * entire key back.  */
813 static gpg_error_t
814 encrypt_response (estream_t *r_output, estream_t input, const char *addrspec,
815                   const char *fingerprint)
816 {
817   gpg_error_t err;
818   ccparray_t ccp;
819   const char **argv;
820   estream_t output;
821   gpg_error_t gpg_err = 0;
822
823   *r_output = NULL;
824
825   output = es_fopenmem (0, "w+b");
826   if (!output)
827     {
828       err = gpg_error_from_syserror ();
829       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
830       return err;
831     }
832
833   ccparray_init (&ccp, 0);
834
835   ccparray_put (&ccp, "--no-options");
836   if (!opt.verbose)
837     ccparray_put (&ccp, "--quiet");
838   else if (opt.verbose > 1)
839     ccparray_put (&ccp, "--verbose");
840   ccparray_put (&ccp, "--batch");
841   ccparray_put (&ccp, "--status-fd=2");
842   ccparray_put (&ccp, "--always-trust");
843   ccparray_put (&ccp, "--armor");
844   if (fake_submission_addr)
845     ccparray_put (&ccp, "--auto-key-locate=clear,local");
846   else
847     ccparray_put (&ccp, "--auto-key-locate=clear,wkd,dane,local");
848   ccparray_put (&ccp, "--recipient");
849   ccparray_put (&ccp, addrspec);
850   ccparray_put (&ccp, "--recipient");
851   ccparray_put (&ccp, fingerprint);
852   ccparray_put (&ccp, "--encrypt");
853   ccparray_put (&ccp, "--");
854
855   ccparray_put (&ccp, NULL);
856   argv = ccparray_get (&ccp, NULL);
857   if (!argv)
858     {
859       err = gpg_error_from_syserror ();
860       goto leave;
861     }
862   err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
863                                 NULL, output,
864                                 encrypt_response_status_cb, &gpg_err);
865   if (err)
866     {
867       if (gpg_err)
868         err = gpg_err;
869       log_error ("encryption failed: %s\n", gpg_strerror (err));
870       goto leave;
871     }
872
873   es_rewind (output);
874   *r_output = output;
875   output = NULL;
876
877  leave:
878   es_fclose (output);
879   xfree (argv);
880   return err;
881 }
882
883
884 static gpg_error_t
885 send_confirmation_response (const char *sender, const char *address,
886                             const char *nonce, int encrypt,
887                             const char *fingerprint)
888 {
889   gpg_error_t err;
890   estream_t body = NULL;
891   estream_t bodyenc = NULL;
892   mime_maker_t mime = NULL;
893
894   body = es_fopenmem (0, "w+b");
895   if (!body)
896     {
897       err = gpg_error_from_syserror ();
898       log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
899       return err;
900     }
901
902   /* It is fine to use 8 bit encoding because that is encrypted and
903    * only our client will see it.  */
904   if (encrypt)
905     {
906       es_fputs ("Content-Type: application/vnd.gnupg.wks\n"
907                 "Content-Transfer-Encoding: 8bit\n"
908                 "\n",
909                 body);
910     }
911
912   es_fprintf (body, ("type: confirmation-response\n"
913                      "sender: %s\n"
914                      "address: %s\n"
915                      "nonce: %s\n"),
916               sender,
917               address,
918               nonce);
919
920   es_rewind (body);
921   if (encrypt)
922     {
923       err = encrypt_response (&bodyenc, body, sender, fingerprint);
924       if (err)
925         goto leave;
926       es_fclose (body);
927       body = NULL;
928     }
929
930   err = mime_maker_new (&mime, NULL);
931   if (err)
932     goto leave;
933   err = mime_maker_add_header (mime, "From", address);
934   if (err)
935     goto leave;
936   err = mime_maker_add_header (mime, "To", sender);
937   if (err)
938     goto leave;
939   err = mime_maker_add_header (mime, "Subject", "Key publication confirmation");
940   if (err)
941     goto leave;
942
943   if (encrypt)
944     {
945       err = mime_maker_add_header (mime, "Content-Type",
946                                    "multipart/encrypted; "
947                                    "protocol=\"application/pgp-encrypted\"");
948       if (err)
949         goto leave;
950       err = mime_maker_add_container (mime);
951       if (err)
952         goto leave;
953
954       err = mime_maker_add_header (mime, "Content-Type",
955                                    "application/pgp-encrypted");
956       if (err)
957         goto leave;
958       err = mime_maker_add_body (mime, "Version: 1\n");
959       if (err)
960         goto leave;
961       err = mime_maker_add_header (mime, "Content-Type",
962                                    "application/octet-stream");
963       if (err)
964         goto leave;
965
966       err = mime_maker_add_stream (mime, &bodyenc);
967       if (err)
968         goto leave;
969     }
970   else
971     {
972       err = mime_maker_add_header (mime, "Content-Type",
973                                    "application/vnd.gnupg.wks");
974       if (err)
975         goto leave;
976       err = mime_maker_add_stream (mime, &body);
977       if (err)
978         goto leave;
979     }
980
981   err = wks_send_mime (mime);
982
983  leave:
984   mime_maker_release (mime);
985   es_fclose (bodyenc);
986   es_fclose (body);
987   return err;
988 }
989
990
991 /* Reply to a confirmation request.  The MSG has already been
992  * decrypted and we only need to send the nonce back.  */
993 static gpg_error_t
994 process_confirmation_request (estream_t msg)
995 {
996   gpg_error_t err;
997   nvc_t nvc;
998   nve_t item;
999   const char *value, *sender, *address, *fingerprint, *nonce;
1000
1001   err = nvc_parse (&nvc, NULL, msg);
1002   if (err)
1003     {
1004       log_error ("parsing the WKS message failed: %s\n", gpg_strerror (err));
1005       goto leave;
1006     }
1007
1008   if (DBG_MIME)
1009     {
1010       log_debug ("request follows:\n");
1011       nvc_write (nvc, log_get_stream ());
1012     }
1013
1014   /* Check that this is a confirmation request.  */
1015   if (!((item = nvc_lookup (nvc, "type:")) && (value = nve_value (item))
1016         && !strcmp (value, "confirmation-request")))
1017     {
1018       if (item && value)
1019         log_error ("received unexpected wks message '%s'\n", value);
1020       else
1021         log_error ("received invalid wks message: %s\n", "'type' missing");
1022       err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
1023       goto leave;
1024     }
1025
1026   /* Get the fingerprint.  */
1027   if (!((item = nvc_lookup (nvc, "fingerprint:"))
1028         && (value = nve_value (item))
1029         && strlen (value) >= 40))
1030     {
1031       log_error ("received invalid wks message: %s\n",
1032                  "'fingerprint' missing or invalid");
1033       err = gpg_error (GPG_ERR_INV_DATA);
1034       goto leave;
1035     }
1036   fingerprint = value;
1037
1038   /* FIXME: Check that the fingerprint matches the key used to decrypt the
1039    * message.  */
1040
1041   /* Get the address.  */
1042   if (!((item = nvc_lookup (nvc, "address:")) && (value = nve_value (item))
1043         && is_valid_mailbox (value)))
1044     {
1045       log_error ("received invalid wks message: %s\n",
1046                  "'address' missing or invalid");
1047       err = gpg_error (GPG_ERR_INV_DATA);
1048       goto leave;
1049     }
1050   address = value;
1051   /* FIXME: Check that the "address" matches the User ID we want to
1052    * publish.  Also get the "fingerprint" and compare that to our to
1053    * be published key.  Further we should make sure that we actually
1054    * decrypted using that fingerprint (which is a bit problematic if
1055    * --read is used). */
1056
1057   /* Get the sender.  */
1058   if (!((item = nvc_lookup (nvc, "sender:")) && (value = nve_value (item))
1059         && is_valid_mailbox (value)))
1060     {
1061       log_error ("received invalid wks message: %s\n",
1062                  "'sender' missing or invalid");
1063       err = gpg_error (GPG_ERR_INV_DATA);
1064       goto leave;
1065     }
1066   sender = value;
1067   /* FIXME: Check that the "sender" matches the From: address.  */
1068
1069   /* Get the nonce.  */
1070   if (!((item = nvc_lookup (nvc, "nonce:")) && (value = nve_value (item))
1071         && strlen (value) > 16))
1072     {
1073       log_error ("received invalid wks message: %s\n",
1074                  "'nonce' missing or too short");
1075       err = gpg_error (GPG_ERR_INV_DATA);
1076       goto leave;
1077     }
1078   nonce = value;
1079
1080   /* Send the confirmation.  If no key was found, try again without
1081    * encryption.  */
1082   err = send_confirmation_response (sender, address, nonce, 1, fingerprint);
1083   if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
1084     {
1085       log_info ("no encryption key found - sending response in the clear\n");
1086       err = send_confirmation_response (sender, address, nonce, 0, NULL);
1087     }
1088
1089  leave:
1090   nvc_release (nvc);
1091   return err;
1092 }
1093
1094
1095 /* Read a confirmation request and decrypt it if needed.  This
1096  * function may not be used with a mail or MIME message but only with
1097  * the actual encrypted or plaintext WKS data.  */
1098 static gpg_error_t
1099 read_confirmation_request (estream_t msg)
1100 {
1101   gpg_error_t err;
1102   int c;
1103   estream_t plaintext = NULL;
1104
1105   /* We take a really simple approach to check whether MSG is
1106    * encrypted: We know that an encrypted message is always armored
1107    * and thus starts with a few dashes.  It is even sufficient to
1108    * check for a single dash, because that can never be a proper first
1109    * WKS data octet.  We need to skip leading spaces, though. */
1110   while ((c = es_fgetc (msg)) == ' ' || c == '\t' || c == '\r' || c == '\n')
1111     ;
1112   if (c == EOF)
1113     {
1114       log_error ("can't process an empty message\n");
1115       return gpg_error (GPG_ERR_INV_DATA);
1116     }
1117   if (es_ungetc (c, msg) != c)
1118     {
1119       log_error ("error ungetting octet from message\n");
1120       return gpg_error (GPG_ERR_INTERNAL);
1121     }
1122
1123   if (c != '-')
1124     err = process_confirmation_request (msg);
1125   else
1126     {
1127       err = decrypt_stream (&plaintext, msg);
1128       if (err)
1129         log_error ("decryption failed: %s\n", gpg_strerror (err));
1130       else
1131         err = process_confirmation_request (plaintext);
1132     }
1133
1134   es_fclose (plaintext);
1135   return err;
1136 }
1137
1138
1139 /* Called from the MIME receiver to process the plain text data in MSG.  */
1140 static gpg_error_t
1141 command_receive_cb (void *opaque, const char *mediatype,
1142                     estream_t msg, unsigned int flags)
1143 {
1144   gpg_error_t err;
1145
1146   (void)opaque;
1147   (void)flags;
1148
1149   if (!strcmp (mediatype, "application/vnd.gnupg.wks"))
1150     err = read_confirmation_request (msg);
1151   else
1152     {
1153       log_info ("ignoring unexpected message of type '%s'\n", mediatype);
1154       err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
1155     }
1156
1157   return err;
1158 }