summaryrefslogtreecommitdiffstats
path: root/tools/gpg-wks-server.c
blob: 2ea5d9117246e91e7ecc585a198f2c3a490d70ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
/* gpg-wks-server.c - A server for the Web Key Service protocols.
 * Copyright (C) 2016, 2018 Werner Koch
 * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik
 *
 * This file is part of GnuPG.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

/* The Web Key Service I-D defines an update protocol to store a
 * public key in the Web Key Directory.  The current specification is
 * draft-koch-openpgp-webkey-service-05.txt.
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

#define INCLUDED_BY_MAIN_MODULE 1
#include "../common/util.h"
#include "../common/init.h"
#include "../common/sysutils.h"
#include "../common/userids.h"
#include "../common/ccparray.h"
#include "../common/exectool.h"
#include "../common/zb32.h"
#include "../common/mbox-util.h"
#include "../common/name-value.h"
#include "mime-maker.h"
#include "send-mail.h"
#include "gpg-wks.h"


/* The time we wait for a confirmation response.  */
#define PENDING_TTL (86400 * 3)  /* 3 days.  */


/* Constants to identify the commands and options. */
enum cmd_and_opt_values
  {
    aNull = 0,

    oQuiet      = 'q',
    oVerbose	= 'v',
    oOutput     = 'o',
    oDirectory  = 'C',

    oDebug      = 500,

    aReceive,
    aCron,
    aListDomains,
    aInstallKey,
    aRevokeKey,
    aRemoveKey,
    aCheck,

    oGpgProgram,
    oSend,
    oFrom,
    oHeader,
    oWithDir,
    oWithFile,

    oDummy
  };


/* The list of commands and options. */
static gpgrt_opt_t opts[] = {
  ARGPARSE_group (300, ("@Commands:\n ")),

  ARGPARSE_c (aReceive,   "receive",
              ("receive a submission or confirmation")),
  ARGPARSE_c (aCron,      "cron",
              ("run regular jobs")),
  ARGPARSE_c (aListDomains, "list-domains",
              ("list configured domains")),
  ARGPARSE_c (aCheck, "check",
              ("check whether a key is installed")),
  ARGPARSE_c (aCheck, "check-key", "@"),
  ARGPARSE_c (aInstallKey, "install-key",
              "install a key from FILE into the WKD"),
  ARGPARSE_c (aRemoveKey, "remove-key",
              "remove a key from the WKD"),
  ARGPARSE_c (aRevokeKey, "revoke-key",
              "mark a key as revoked"),

  ARGPARSE_group (301, ("@\nOptions:\n ")),

  ARGPARSE_s_n (oVerbose, "verbose", ("verbose")),
  ARGPARSE_s_n (oQuiet,	"quiet",  ("be somewhat more quiet")),
  ARGPARSE_s_s (oDebug, "debug", "@"),
  ARGPARSE_s_s (oGpgProgram, "gpg", "@"),
  ARGPARSE_s_n (oSend, "send", "send the mail using sendmail"),
  ARGPARSE_s_s (oOutput, "output", "|FILE|write the mail to FILE"),
  ARGPARSE_s_s (oDirectory, "directory", "|DIR|use DIR as top directory"),
  ARGPARSE_s_s (oFrom, "from", "|ADDR|use ADDR as the default sender"),
  ARGPARSE_s_s (oHeader, "header" ,
                "|NAME=VALUE|add \"NAME: VALUE\" as header to all mails"),
  ARGPARSE_s_n (oWithDir, "with-dir", "@"),
  ARGPARSE_s_n (oWithFile, "with-file", "@"),

  ARGPARSE_end ()
};


/* The list of supported debug flags.  */
static struct debug_flags_s debug_flags [] =
  {
    { DBG_MIME_VALUE   , "mime"    },
    { DBG_PARSER_VALUE , "parser"  },
    { DBG_CRYPTO_VALUE , "crypto"  },
    { DBG_MEMORY_VALUE , "memory"  },
    { DBG_MEMSTAT_VALUE, "memstat" },
    { DBG_IPC_VALUE    , "ipc"     },
    { DBG_EXTPROG_VALUE, "extprog" },
    { 0, NULL }
  };


/* State for processing a message.  */
struct server_ctx_s
{
  char *fpr;
  uidinfo_list_t mboxes;  /* List with addr-specs taken from the UIDs.  */
  unsigned int draft_version_2:1; /* Client supports the draft 2.  */
};
typedef struct server_ctx_s *server_ctx_t;


/* Flag for --with-dir.  */
static int opt_with_dir;
/* Flag for --with-file.  */
static int opt_with_file;


/* Prototypes.  */
static gpg_error_t get_domain_list (strlist_t *r_list);

static gpg_error_t command_receive_cb (void *opaque,
                                       const char *mediatype, estream_t fp,
                                       unsigned int flags);
static gpg_error_t command_list_domains (void);
static gpg_error_t command_revoke_key (const char *mailaddr);
static gpg_error_t command_check_key (const char *mailaddr);
static gpg_error_t command_cron (void);



/* Print usage information and provide strings for help. */
static const char *
my_strusage( int level )
{
  const char *p;

  switch (level)
    {
    case  9: p = "LGPL-2.1-or-later"; break;
    case 11: p = "gpg-wks-server"; break;
    case 12: p = "@GNUPG@"; break;
    case 13: p = VERSION; break;
    case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
    case 17: p = PRINTABLE_OS_NAME; break;
    case 19: p = ("Please report bugs to <@EMAIL@>.\n"); break;

    case 1:
    case 40:
      p = ("Usage: gpg-wks-server command [options] (-h for help)");
      break;
    case 41:
      p = ("Syntax: gpg-wks-server command [options]\n"
           "Server for the Web Key Service protocol\n");
      break;

    default: p = NULL; break;
    }
  return p;
}


static void
wrong_args (const char *text)
{
  es_fprintf (es_stderr, "usage: %s [options] %s\n", gpgrt_strusage (11), text);
  exit (2);
}



/* Command line parsing.  */
static enum cmd_and_opt_values
parse_arguments (gpgrt_argparse_t *pargs, gpgrt_opt_t *popts)
{
  enum cmd_and_opt_values cmd = 0;
  int no_more_options = 0;

  while (!no_more_options && gpgrt_argparse (NULL, pargs, popts))
    {
      switch (pargs->r_opt)
        {
	case oQuiet:     opt.quiet = 1; break;
        case oVerbose:   opt.verbose++; break;
        case oDebug:
          if (parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags))
            {
              pargs->r_opt = ARGPARSE_INVALID_ARG;
              pargs->err = ARGPARSE_PRINT_ERROR;
            }
          break;

        case oGpgProgram:
          opt.gpg_program = pargs->r.ret_str;
          break;
        case oDirectory:
          opt.directory = pargs->r.ret_str;
          break;
        case oFrom:
          opt.default_from = pargs->r.ret_str;
          break;
        case oHeader:
          append_to_strlist (&opt.extra_headers, pargs->r.ret_str);
          break;
        case oSend:
          opt.use_sendmail = 1;
          break;
        case oOutput:
          opt.output = pargs->r.ret_str;
          break;
        case oWithDir:
          opt_with_dir = 1;
          break;
        case oWithFile:
          opt_with_file = 1;
          break;

	case aReceive:
        case aCron:
        case aListDomains:
        case aCheck:
        case aInstallKey:
        case aRemoveKey:
        case aRevokeKey:
          cmd = pargs->r_opt;
          break;

        default: pargs->err = ARGPARSE_PRINT_ERROR; break;
	}
    }

  return cmd;
}



/* gpg-wks-server main. */
int
main (int argc, char **argv)
{
  gpg_error_t err, firsterr;
  gpgrt_argparse_t pargs;
  enum cmd_and_opt_values cmd;

  gnupg_reopen_std ("gpg-wks-server");
  gpgrt_set_strusage (my_strusage);
  log_set_prefix ("gpg-wks-server", GPGRT_LOG_WITH_PREFIX);

  /* Make sure that our subsystems are ready.  */
  init_common_subsystems (&argc, &argv);

  /* Parse the command line. */
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags = ARGPARSE_FLAG_KEEP;
  cmd = parse_arguments (&pargs, opts);
  gpgrt_argparse (NULL, &pargs, NULL);

  if (log_get_errorcount (0))
    exit (2);

  /* Print a warning if an argument looks like an option.  */
  if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
    {
      int i;

      for (i=0; i < argc; i++)
        if (argv[i][0] == '-' && argv[i][1] == '-')
          log_info (("NOTE: '%s' is not considered an option\n"), argv[i]);
    }

  /* Set defaults for non given options.  */
  if (!opt.gpg_program)
    opt.gpg_program = gnupg_module_name (GNUPG_MODULE_NAME_GPG);

  if (!opt.directory)
    opt.directory = "/var/lib/gnupg/wks";

  /* Check for syntax errors in the --header option to avoid later
   * error messages with a not easy to find cause */
  if (opt.extra_headers)
    {
      strlist_t sl;

      for (sl = opt.extra_headers; sl; sl = sl->next)
        {
          err = mime_maker_add_header (NULL, sl->d, NULL);
          if (err)
            log_error ("syntax error in \"--header %s\": %s\n",
                       sl->d, gpg_strerror (err));
        }
    }

  if (log_get_errorcount (0))
    exit (2);


  /* Check that we have a working directory.  */
#if defined(HAVE_STAT)
  {
    struct stat sb;

    if (gnupg_stat (opt.directory, &sb))
      {
        err = gpg_error_from_syserror ();
        log_error ("error accessing directory '%s': %s\n",
                   opt.directory, gpg_strerror (err));
        exit (2);
      }
    if (!S_ISDIR(sb.st_mode))
      {
        log_error ("error accessing directory '%s': %s\n",
                   opt.directory, "not a directory");
        exit (2);
      }
    if (sb.st_uid != getuid())
      {
        log_error ("directory '%s' not owned by user\n", opt.directory);
        exit (2);
      }
    if ((sb.st_mode & (S_IROTH|S_IWOTH)))
      {
        log_error ("directory '%s' has too relaxed permissions\n",
                   opt.directory);
        log_info ("Fix by running: chmod o-rw '%s'\n", opt.directory);
        exit (2);
      }
  }
#else /*!HAVE_STAT*/
  log_fatal ("program build w/o stat() call\n");
#endif /*!HAVE_STAT*/

  /* Run the selected command.  */
  switch (cmd)
    {
    case aReceive:
      if (argc)
        wrong_args ("--receive");
      err = wks_receive (es_stdin, command_receive_cb, NULL);
      break;

    case aCron:
      if (argc)
        wrong_args ("--cron");
      err = command_cron ();
      break;

    case aListDomains:
      err = command_list_domains ();
      break;

    case aInstallKey:
      if (!argc)
        err = wks_cmd_install_key (NULL, NULL);
      else if (argc == 2)
        err = wks_cmd_install_key (*argv, argv[1]);
      else
        wrong_args ("--install-key [FILE|FINGERPRINT USER-ID]");
      break;

    case aRemoveKey:
      if (argc != 1)
        wrong_args ("--remove-key USER-ID");
      err = wks_cmd_remove_key (*argv);
      break;

    case aRevokeKey:
      if (argc != 1)
        wrong_args ("--revoke-key USER-ID");
      err = command_revoke_key (*argv);
      break;

    case aCheck:
      if (!argc)
        wrong_args ("--check USER-IDs");
      firsterr = 0;
      for (; argc; argc--, argv++)
        {
          err = command_check_key (*argv);
          if (!firsterr)
            firsterr = err;
        }
      err = firsterr;
      break;

    default:
      gpgrt_usage (1);
      err = gpg_error (GPG_ERR_BUG);
      break;
    }

  if (err)
    log_error ("command failed: %s\n", gpg_strerror (err));
  return log_get_errorcount (0)? 1:0;
}


/* Take the key in KEYFILE and write it to OUTFILE in binary encoding.
 * If ADDRSPEC is given only matching user IDs are included in the
 * output.  */
static gpg_error_t
copy_key_as_binary (const char *keyfile, const char *outfile,
                    const char *addrspec)
{
  gpg_error_t err;
  ccparray_t ccp;
  const char **argv = NULL;
  char *filterexp = NULL;

  if (addrspec)
    {
      filterexp = es_bsprintf ("keep-uid=mbox = %s", addrspec);
      if (!filterexp)
        {
          err = gpg_error_from_syserror ();
          log_error ("error allocating memory buffer: %s\n",
                     gpg_strerror (err));
          goto leave;
        }
    }

  ccparray_init (&ccp, 0);

  ccparray_put (&ccp, "--no-options");
  if (!opt.verbose)
    ccparray_put (&ccp, "--quiet");
  else if (opt.verbose > 1)
    ccparray_put (&ccp, "--verbose");
  ccparray_put (&ccp, "--batch");
  ccparray_put (&ccp, "--yes");
  ccparray_put (&ccp, "--always-trust");
  ccparray_put (&ccp, "--no-keyring");
  ccparray_put (&ccp, "--output");
  ccparray_put (&ccp, outfile);
  ccparray_put (&ccp, "--import-options=import-export");
  if (filterexp)
    {
      ccparray_put (&ccp, "--import-filter");
      ccparray_put (&ccp, filterexp);
    }
  ccparray_put (&ccp, "--import");
  ccparray_put (&ccp, "--");
  ccparray_put (&ccp, keyfile);

  ccparray_put (&ccp, NULL);
  argv = ccparray_get (&ccp, NULL);
  if (!argv)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }
  err = gnupg_exec_tool_stream (opt.gpg_program, argv, NULL,
                                NULL, NULL, NULL, NULL);
  if (err)
    {
      log_error ("%s failed: %s\n", __func__, gpg_strerror (err));
      goto leave;
    }

 leave:
  xfree (filterexp);
  xfree (argv);
  return err;
}


/* Take the key in KEYFILE and write it to DANEFILE using the DANE
 * output format. */
static gpg_error_t
copy_key_as_dane (const char *keyfile, const char *danefile)
{
  gpg_error_t err;
  ccparray_t ccp;
  const char **argv;

  ccparray_init (&ccp, 0);

  ccparray_put (&ccp, "--no-options");
  if (!opt.verbose)
    ccparray_put (&ccp, "--quiet");
  else if (opt.verbose > 1)
    ccparray_put (&ccp, "--verbose");
  ccparray_put (&ccp, "--batch");
  ccparray_put (&ccp, "--yes");
  ccparray_put (&ccp, "--always-trust");
  ccparray_put (&ccp, "--no-keyring");
  ccparray_put (&ccp, "--output");
  ccparray_put (&ccp, danefile);
  ccparray_put (&ccp, "--export-options=export-dane");
  ccparray_put (&ccp, "--import-options=import-export");
  ccparray_put (&ccp, "--import");
  ccparray_put (&ccp, "--");
  ccparray_put (&ccp, keyfile);

  ccparray_put (&ccp, NULL);
  argv = ccparray_get (&ccp, NULL);
  if (!argv)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }
  err = gnupg_exec_tool_stream (opt.gpg_program, argv, NULL,
                                NULL, NULL, NULL, NULL);
  if (err)
    {
      log_error ("%s failed: %s\n", __func__, gpg_strerror (err));
      goto leave;
    }

 leave:
  xfree (argv);
  return err;
}


static void
encrypt_stream_status_cb (void *opaque, const char *keyword, char *args)
{
  (void)opaque;

  if (DBG_CRYPTO)
    log_debug ("gpg status: %s %s\n", keyword, args);
}


/* Encrypt the INPUT stream to a new stream which is stored at success
 * at R_OUTPUT.  Encryption is done for the key in file KEYFIL.  */
static gpg_error_t
encrypt_stream (estream_t *r_output, estream_t input, const char *keyfile)
{
  gpg_error_t err;
  ccparray_t ccp;
  const char **argv;
  estream_t output;

  *r_output = NULL;

  output = es_fopenmem (0, "w+b");
  if (!output)
    {
      err = gpg_error_from_syserror ();
      log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
      return err;
    }

  ccparray_init (&ccp, 0);

  ccparray_put (&ccp, "--no-options");
  if (!opt.verbose)
    ccparray_put (&ccp, "--quiet");
  else if (opt.verbose > 1)
    ccparray_put (&ccp, "--verbose");
  ccparray_put (&ccp, "--batch");
  ccparray_put (&ccp, "--status-fd=2");
  ccparray_put (&ccp, "--always-trust");
  ccparray_put (&ccp, "--no-keyring");
  ccparray_put (&ccp, "--armor");
  ccparray_put (&ccp, "-z0");  /* No compression for improved robustness.  */
  ccparray_put (&ccp, "--recipient-file");
  ccparray_put (&ccp, keyfile);
  ccparray_put (&ccp, "--encrypt");
  ccparray_put (&ccp, "--");

  ccparray_put (&ccp, NULL);
  argv = ccparray_get (&ccp, NULL);
  if (!argv)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }
  err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
                                NULL, output,
                                encrypt_stream_status_cb, NULL);
  if (err)
    {
      log_error ("encryption failed: %s\n", gpg_strerror (err));
      goto leave;
    }

  es_rewind (output);
  *r_output = output;
  output = NULL;

 leave:
  es_fclose (output);
  xfree (argv);
  return err;
}


static void
sign_stream_status_cb (void *opaque, const char *keyword, char *args)
{
  (void)opaque;

  if (DBG_CRYPTO)
    log_debug ("gpg status: %s %s\n", keyword, args);
}

/* Sign the INPUT stream to a new stream which is stored at success at
 * R_OUTPUT.  A detached signature is created using the key specified
 * by USERID.  */
static gpg_error_t
sign_stream (estream_t *r_output, estream_t input, const char *userid)
{
  gpg_error_t err;
  ccparray_t ccp;
  const char **argv;
  estream_t output;

  *r_output = NULL;

  output = es_fopenmem (0, "w+b");
  if (!output)
    {
      err = gpg_error_from_syserror ();
      log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
      return err;
    }

  ccparray_init (&ccp, 0);

  ccparray_put (&ccp, "--no-options");
  if (!opt.verbose)
    ccparray_put (&ccp, "--quiet");
  else if (opt.verbose > 1)
    ccparray_put (&ccp, "--verbose");
  ccparray_put (&ccp, "--batch");
  ccparray_put (&ccp, "--status-fd=2");
  ccparray_put (&ccp, "--armor");
  ccparray_put (&ccp, "--local-user");
  ccparray_put (&ccp, userid);
  ccparray_put (&ccp, "--detach-sign");
  ccparray_put (&ccp, "--");

  ccparray_put (&ccp, NULL);
  argv = ccparray_get (&ccp, NULL);
  if (!argv)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }
  err = gnupg_exec_tool_stream (opt.gpg_program, argv, input,
                                NULL, output,
                                sign_stream_status_cb, NULL);
  if (err)
    {
      log_error ("signing failed: %s\n", gpg_strerror (err));
      goto leave;
    }

  es_rewind (output);
  *r_output = output;
  output = NULL;

 leave:
  es_fclose (output);
  xfree (argv);
  return err;
}


/* Get the submission address for address MBOX.  Caller must free the
 * value.  If no address can be found NULL is returned.  */
static char *
get_submission_address (const char *mbox)
{
  gpg_error_t err;
  const char *domain;
  char *fname, *line, *p;
  size_t n;
  estream_t fp;

  domain = strchr (mbox, '@');
  if (!domain)
    return NULL;
  domain++;

  fname = make_filename_try (opt.directory, domain, "submission-address", NULL);
  if (!fname)
    {
      err = gpg_error_from_syserror ();
      log_error ("make_filename failed in %s: %s\n",
                 __func__, gpg_strerror (err));
      return NULL;
    }

  fp = es_fopen (fname, "r");
  if (!fp)
    {
      err = gpg_error_from_syserror ();
      if (gpg_err_code (err) == GPG_ERR_ENOENT)
        log_info ("Note: no specific submission address configured"
                  " for domain '%s'\n", domain);
      else
        log_error ("error reading '%s': %s\n", fname, gpg_strerror (err));
      xfree (fname);
      return NULL;
    }

  line = NULL;
  n = 0;
  if (es_getline (&line, &n, fp) < 0)
    {
      err = gpg_error_from_syserror ();
      log_error ("error reading '%s': %s\n", fname, gpg_strerror (err));
      xfree (line);
      es_fclose (fp);
      xfree (fname);
      return NULL;
    }
  es_fclose (fp);
  xfree (fname);

  p = strchr (line, '\n');
  if (p)
    *p = 0;
  trim_spaces (line);
  if (!is_valid_mailbox (line))
    {
      log_error ("invalid submission address for domain '%s' detected\n",
                 domain);
      xfree (line);
      return NULL;
    }

  return line;
}


/* Get the policy flags for address MBOX and store them in POLICY.  */
static gpg_error_t
get_policy_flags (policy_flags_t policy, const char *mbox)
{
  gpg_error_t err;
  const char *domain;
  char *fname;
  estream_t fp;

  memset (policy, 0, sizeof *policy);

  domain = strchr (mbox, '@');
  if (!domain)
    return gpg_error (GPG_ERR_INV_USER_ID);
  domain++;

  fname = make_filename_try (opt.directory, domain, "policy", NULL);
  if (!fname)
    {
      err = gpg_error_from_syserror ();
      log_error ("make_filename failed in %s: %s\n",
                 __func__, gpg_strerror (err));
      return err;
    }

  fp = es_fopen (fname, "r");
  if (!fp)
    {
      err = gpg_error_from_syserror ();
      if (gpg_err_code (err) == GPG_ERR_ENOENT)
        err = 0;
      else
        log_error ("error reading '%s': %s\n", fname, gpg_strerror (err));
      xfree (fname);
      return err;
    }

  err = wks_parse_policy (policy, fp, 0);
  es_fclose (fp);
  xfree (fname);
  return err;
}


/* We store the key under the name of the nonce we will then send to
 * the user.  On success the nonce is stored at R_NONCE and the file
 * name at R_FNAME.  */
static gpg_error_t
store_key_as_pending (const char *dir, estream_t key,
                      char **r_nonce, char **r_fname)
{
  gpg_error_t err;
  char *dname = NULL;
  char *fname = NULL;
  char *nonce = NULL;
  estream_t outfp = NULL;
  char buffer[1024];
  size_t nbytes, nwritten;

  *r_nonce = NULL;
  *r_fname = NULL;

  dname = make_filename_try (dir, "pending", NULL);
  if (!dname)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }

  /* Create the nonce.  We use 20 bytes so that we don't waste a
   * character in our zBase-32 encoding.  Using the gcrypt's nonce
   * function is faster than using the strong random function; this is
   * Good Enough for our purpose.  */
  log_assert (sizeof buffer > 20);
  gcry_create_nonce (buffer, 20);
  nonce = zb32_encode (buffer, 8 * 20);
  memset (buffer, 0, 20);  /* Not actually needed but it does not harm. */
  if (!nonce)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }

  fname = strconcat (dname, "/", nonce, NULL);
  if (!fname)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }

  /* With 128 bits of random we can expect that no other file exists
   * under this name.  We use "x" to detect internal errors.  */
  outfp = es_fopen (fname, "wbx,mode=-rw");
  if (!outfp)
    {
      err = gpg_error_from_syserror ();
      log_error ("error creating '%s': %s\n", fname, gpg_strerror (err));
      goto leave;
    }
  es_rewind (key);
  for (;;)
    {
      if (es_read (key, buffer, sizeof buffer, &nbytes))
        {
          err = gpg_error_from_syserror ();
          log_error ("error reading '%s': %s\n",
                     es_fname_get (key), gpg_strerror (err));
          break;
        }

      if (!nbytes)
        {
          err = 0;
          goto leave; /* Ready.  */
        }
      if (es_write (outfp, buffer, nbytes, &nwritten))
        {
          err = gpg_error_from_syserror ();
          log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
          goto leave;
        }
      else if (nwritten != nbytes)
        {
          err = gpg_error (GPG_ERR_EIO);
          log_error ("error writing '%s': %s\n", fname, "short write");
          goto leave;
        }
    }

 leave:
  if (err)
    {
      es_fclose (outfp);
      gnupg_remove (fname);
    }
  else if (es_fclose (outfp))
    {
      err = gpg_error_from_syserror ();
      log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
    }

  if (!err)
    {
      *r_nonce = nonce;
      *r_fname = fname;
    }
  else
    {
      xfree (nonce);
      xfree (fname);
    }
  xfree (dname);
  return err;
}


/* Send a confirmation request.  DIR is the directory used for the
 * address MBOX.  NONCE is the nonce we want to see in the response to
 * this mail.  FNAME the name of the file with the key.  */
static gpg_error_t
send_confirmation_request (server_ctx_t ctx,
                           const char *mbox, const char *nonce,
                           const char *keyfile)
{
  gpg_error_t err;
  estream_t body = NULL;
  estream_t bodyenc = NULL;
  estream_t signeddata = NULL;
  estream_t signature = NULL;
  mime_maker_t mime = NULL;
  char *from_buffer = NULL;
  const char *from;
  strlist_t sl;

  from = from_buffer = get_submission_address (mbox);
  if (!from)
    {
      from = opt.default_from;
      if (!from)
        {
          log_error ("no sender address found for '%s'\n", mbox);
          err = gpg_error (GPG_ERR_CONFIGURATION);
          goto leave;
        }
      log_info ("Note: using default sender address '%s'\n", from);
    }

  body = es_fopenmem (0, "w+b");
  if (!body)
    {
      err = gpg_error_from_syserror ();
      log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
      goto leave;
    }

  if (!ctx->draft_version_2)
    {
      /* It is fine to use 8 bit encoding because that is encrypted and
       * only our client will see it.  */
      es_fputs ("Content-Type: application/vnd.gnupg.wks\n"
                "Content-Transfer-Encoding: 8bit\n"
                "\n",
                body);
    }

  es_fprintf (body, ("type: confirmation-request\n"
                     "sender: %s\n"
                     "address: %s\n"
                     "fingerprint: %s\n"
                     "nonce: %s\n"),
              from,
              mbox,
              ctx->fpr,
              nonce);

  es_rewind (body);
  err = encrypt_stream (&bodyenc, body, keyfile);
  if (err)
    goto leave;
  es_fclose (body);
  body = NULL;


  err = mime_maker_new (&mime, NULL);
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "From", from);
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "To", mbox);
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "Subject", "Confirm your key publication");
  if (err)
    goto leave;

  err = mime_maker_add_header (mime, "Wks-Draft-Version",
                               STR2(WKS_DRAFT_VERSION));
  if (err)
    goto leave;

  /* Help Enigmail to identify messages.  Note that this is in no way
   * secured.  */
  err = mime_maker_add_header (mime, "WKS-Phase", "confirm");
  if (err)
    goto leave;

  for (sl = opt.extra_headers; sl; sl = sl->next)
    {
      err = mime_maker_add_header (mime, sl->d, NULL);
      if (err)
        goto leave;
    }

  if (!ctx->draft_version_2)
    {
      err = mime_maker_add_header (mime, "Content-Type",
                                   "multipart/encrypted; "
                                   "protocol=\"application/pgp-encrypted\"");
      if (err)
        goto leave;
      err = mime_maker_add_container (mime);
      if (err)
        goto leave;

      err = mime_maker_add_header (mime, "Content-Type",
                                   "application/pgp-encrypted");
      if (err)
        goto leave;
      err = mime_maker_add_body (mime, "Version: 1\n");
      if (err)
        goto leave;
      err = mime_maker_add_header (mime, "Content-Type",
                                   "application/octet-stream");
      if (err)
        goto leave;

      err = mime_maker_add_stream (mime, &bodyenc);
      if (err)
        goto leave;

    }
  else
    {
      unsigned int partid;

      /* FIXME: Add micalg.  */
      err = mime_maker_add_header (mime, "Content-Type",
                                   "multipart/signed; "
                                   "protocol=\"application/pgp-signature\"");
      if (err)
        goto leave;
      err = mime_maker_add_container (mime);
      if (err)
        goto leave;

      err = mime_maker_add_header (mime, "Content-Type", "multipart/mixed");
      if (err)
        goto leave;

      err = mime_maker_add_container (mime);
      if (err)
        goto leave;
      partid = mime_maker_get_partid (mime);

      err = mime_maker_add_header (mime, "Content-Type", "text/plain");
      if (err)
        goto leave;

      err = mime_maker_add_body
        (mime,
         "This message has been send to confirm your request\n"
         "to publish your key.  If you did not request a key\n"
         "publication, simply ignore this message.\n"
         "\n"
         "Most mail software can handle this kind of message\n"
         "automatically and thus you would not have seen this\n"
         "message.  It seems that your client does not fully\n"
         "support this service.  The web page\n"
         "\n"
         "       https://gnupg.org/faq/wkd.html\n"
         "\n"
         "explains how you can process this message anyway in\n"
         "a few manual steps.\n");
      if (err)
        goto leave;

      err = mime_maker_add_header (mime, "Content-Type",
                                   "application/vnd.gnupg.wks");
      if (err)
        goto leave;

      err = mime_maker_add_stream (mime, &bodyenc);
      if (err)
        goto leave;

      err = mime_maker_end_container (mime);
      if (err)
        goto leave;

      /* mime_maker_dump_tree (mime); */
      err = mime_maker_get_part (mime, partid, &signeddata);
      if (err)
        goto leave;

      err = sign_stream (&signature, signeddata, from);
      if (err)
        goto leave;

      err = mime_maker_add_header (mime, "Content-Type",
                                   "application/pgp-signature");
      if (err)
        goto leave;

      err = mime_maker_add_stream (mime, &signature);
      if (err)
        goto leave;
    }

  err = wks_send_mime (mime);

 leave:
  mime_maker_release (mime);
  es_fclose (signature);
  es_fclose (signeddata);
  es_fclose (bodyenc);
  es_fclose (body);
  xfree (from_buffer);
  return err;
}


/* Store the key given by KEY into the pending directory and send a
 * confirmation requests.  */
static gpg_error_t
process_new_key (server_ctx_t ctx, estream_t key)
{
  gpg_error_t err;
  uidinfo_list_t sl;
  const char *s;
  char *dname = NULL;
  char *nonce = NULL;
  char *fname = NULL;
  struct policy_flags_s policybuf;

  memset (&policybuf, 0, sizeof policybuf);

  /* First figure out the user id from the key.  */
  xfree (ctx->fpr);
  free_uidinfo_list (ctx->mboxes);
  err = wks_list_key (key, &ctx->fpr, &ctx->mboxes);
  if (err)
    goto leave;
  log_assert (ctx->fpr);
  log_info ("fingerprint: %s\n", ctx->fpr);
  for (sl = ctx->mboxes; sl; sl = sl->next)
    {
      if (sl->mbox)
        log_info ("  addr-spec: %s\n", sl->mbox);
    }

  /* Walk over all user ids and send confirmation requests for those
   * we support.  */
  for (sl = ctx->mboxes; sl; sl = sl->next)
    {
      if (!sl->mbox)
        continue;
      s = strchr (sl->mbox, '@');
      log_assert (s && s[1]);
      xfree (dname);
      dname = make_filename_try (opt.directory, s+1, NULL);
      if (!dname)
        {
          err = gpg_error_from_syserror ();
          goto leave;
        }

      if (gnupg_access (dname, W_OK))
        {
          log_info ("skipping address '%s': Domain not configured\n", sl->mbox);
          continue;
        }
      if (get_policy_flags (&policybuf, sl->mbox))
        {
          log_info ("skipping address '%s': Bad policy flags\n", sl->mbox);
          continue;
        }

      if (policybuf.auth_submit)
        {
          /* Bypass the confirmation stuff and publish the key as is.  */
          log_info ("publishing address '%s'\n", sl->mbox);
          /* FIXME: We need to make sure that we do this only for the
           * address in the mail.  */
          log_debug ("auth-submit not yet working!\n");
        }
      else
        {
          log_info ("storing address '%s'\n", sl->mbox);

          xfree (nonce);
          xfree (fname);
          err = store_key_as_pending (dname, key, &nonce, &fname);
          if (err)
            goto leave;

          err = send_confirmation_request (ctx, sl->mbox, nonce, fname);
          if (err)
            goto leave;
        }
    }

 leave:
  if (nonce)
    wipememory (nonce, strlen (nonce));
  xfree (nonce);
  xfree (fname);
  xfree (dname);
  wks_free_policy (&policybuf);
  return err;
}



/* Send a message to tell the user at MBOX that their key has been
 * published.  FNAME the name of the file with the key.  */
static gpg_error_t
send_congratulation_message (const char *mbox, const char *keyfile)
{
  gpg_error_t err;
  estream_t body = NULL;
  estream_t bodyenc = NULL;
  mime_maker_t mime = NULL;
  char *from_buffer = NULL;
  const char *from;
  strlist_t sl;

  from = from_buffer = get_submission_address (mbox);
  if (!from)
    {
      from = opt.default_from;
      if (!from)
        {
          log_error ("no sender address found for '%s'\n", mbox);
          err = gpg_error (GPG_ERR_CONFIGURATION);
          goto leave;
        }
      log_info ("Note: using default sender address '%s'\n", from);
    }

  body = es_fopenmem (0, "w+b");
  if (!body)
    {
      err = gpg_error_from_syserror ();
      log_error ("error allocating memory buffer: %s\n", gpg_strerror (err));
      goto leave;
    }
  /* It is fine to use 8 bit encoding because that is encrypted and
   * only our client will see it.  */
  es_fputs ("Content-Type: text/plain; charset=utf-8\n"
            "Content-Transfer-Encoding: 8bit\n"
            "\n",
            body);

  es_fprintf (body,
              "Hello!\n\n"
              "The key for your address '%s' has been published\n"
              "and can now be retrieved from the Web Key Directory.\n"
              "\n"
              "For more information on this system see:\n"
              "\n"
              "  https://gnupg.org/faq/wkd.html\n"
              "\n"
              "Best regards\n"
              "\n"
              "  GnuPG Key Publisher\n\n\n"
              "-- \n"
              "For information on GnuPG see: %s\n",
              mbox, "https://gnupg.org");

  es_rewind (body);
  err = encrypt_stream (&bodyenc, body, keyfile);
  if (err)
    goto leave;
  es_fclose (body);
  body = NULL;

  err = mime_maker_new (&mime, NULL);
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "From", from);
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "To", mbox);
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "Subject", "Your key has been published");
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "Wks-Draft-Version",
                               STR2(WKS_DRAFT_VERSION));
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "WKS-Phase", "done");
  if (err)
    goto leave;
  for (sl = opt.extra_headers; sl; sl = sl->next)
    {
      err = mime_maker_add_header (mime, sl->d, NULL);
      if (err)
        goto leave;
    }

  err = mime_maker_add_header (mime, "Content-Type",
                               "multipart/encrypted; "
                               "protocol=\"application/pgp-encrypted\"");
  if (err)
    goto leave;
  err = mime_maker_add_container (mime);
  if (err)
    goto leave;

  err = mime_maker_add_header (mime, "Content-Type",
                               "application/pgp-encrypted");
  if (err)
    goto leave;
  err = mime_maker_add_body (mime, "Version: 1\n");
  if (err)
    goto leave;
  err = mime_maker_add_header (mime, "Content-Type",
                               "application/octet-stream");
  if (err)
    goto leave;

  err = mime_maker_add_stream (mime, &bodyenc);
  if (err)
    goto leave;

  err = wks_send_mime (mime);

 leave:
  mime_maker_release (mime);
  es_fclose (bodyenc);
  es_fclose (body);
  xfree (from_buffer);
  return err;
}


/* Check that we have send a request with NONCE and publish the key.  */
static gpg_error_t
check_and_publish (server_ctx_t ctx, const char *address, const char *nonce)
{
  gpg_error_t err;
  char *fname = NULL;
  char *fnewname = NULL;
  estream_t key = NULL;
  char *hash = NULL;
  const char *domain;
  const char *s;
  uidinfo_list_t sl;
  char shaxbuf[32]; /* Used for SHA-1 and SHA-256 */

  /* FIXME: There is a bug in name-value.c which adds white space for
   * the last pair and thus we strip the nonce here until this has
   * been fixed.  */
  char *nonce2 = xstrdup (nonce);
  trim_trailing_spaces (nonce2);
  nonce = nonce2;


  domain = strchr (address, '@');
  log_assert (domain && domain[1]);
  domain++;
  fname = make_filename_try (opt.directory, domain, "pending", nonce, NULL);
  if (!fname)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }

  /* Try to open the file with the key.  */
  key = es_fopen (fname, "rb");
  if (!key)
    {
      err = gpg_error_from_syserror ();
      if (gpg_err_code (err) == GPG_ERR_ENOENT)
        {
          log_info ("no pending request for '%s'\n", address);
          err = gpg_error (GPG_ERR_NOT_FOUND);
        }
      else
        log_error ("error reading '%s': %s\n", fname, gpg_strerror (err));
      goto leave;
    }

  /* We need to get the fingerprint from the key.  */
  xfree (ctx->fpr);
  free_uidinfo_list (ctx->mboxes);
  err = wks_list_key (key, &ctx->fpr, &ctx->mboxes);
  if (err)
    goto leave;
  log_assert (ctx->fpr);
  log_info ("fingerprint: %s\n", ctx->fpr);
  for (sl = ctx->mboxes; sl; sl = sl->next)
    if (sl->mbox)
      log_info ("  addr-spec: %s\n", sl->mbox);

  /* Check that the key has 'address' as a user id.  We use
   * case-insensitive matching because the client is expected to
   * return the address verbatim.  */
  for (sl = ctx->mboxes; sl; sl = sl->next)
    if (sl->mbox && !strcmp (sl->mbox, address))
      break;
  if (!sl)
    {
      log_error ("error publishing key: '%s' is not a user ID of %s\n",
                 address, ctx->fpr);
      err = gpg_error (GPG_ERR_NO_PUBKEY);
      goto leave;
    }

  /* Hash user ID and create filename.  */
  err = wks_compute_hu_fname (&fnewname, address);
  if (err)
    goto leave;

  /* Publish.  */
  err = copy_key_as_binary (fname, fnewname, address);
  if (err)
    {
      err = gpg_error_from_syserror ();
      log_error ("copying '%s' to '%s' failed: %s\n",
                 fname, fnewname, gpg_strerror (err));
      goto leave;
    }

  /* Make sure it is world readable.  */
  if (gnupg_chmod (fnewname, "-rw-r--r--"))
    log_error ("can't set permissions of '%s': %s\n",
               fnewname, gpg_strerror (gpg_err_code_from_syserror()));

  log_info ("key %s published for '%s'\n", ctx->fpr, address);
  send_congratulation_message (address, fnewname);

  /* Try to publish as DANE record if the DANE directory exists.  */
  xfree (fname);
  fname = fnewname;
  fnewname = make_filename_try (opt.directory, domain, "dane", NULL);
  if (!fnewname)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }
  if (!gnupg_access (fnewname, W_OK))
    {
      /* Yes, we have a dane directory.  */
      s = strchr (address, '@');
      log_assert (s);
      gcry_md_hash_buffer (GCRY_MD_SHA256, shaxbuf, address, s - address);
      xfree (hash);
      hash = bin2hex (shaxbuf, 28, NULL);
      if (!hash)
        {
          err = gpg_error_from_syserror ();
          goto leave;
        }
      xfree (fnewname);
      fnewname = make_filename_try (opt.directory, domain, "dane", hash, NULL);
      if (!fnewname)
        {
          err = gpg_error_from_syserror ();
          goto leave;
        }
      err = copy_key_as_dane (fname, fnewname);
      if (err)
        goto leave;
      log_info ("key %s published for '%s' (DANE record)\n", ctx->fpr, address);
    }

 leave:
  es_fclose (key);
  xfree (hash);
  xfree (fnewname);
  xfree (fname);
  xfree (nonce2);
  return err;
}


/* Process a confirmation response in MSG.  */
static gpg_error_t
process_confirmation_response (server_ctx_t ctx, estream_t msg)
{
  gpg_error_t err;
  nvc_t nvc;
  nve_t item;
  const char *value, *sender, *address, *nonce;

  err = nvc_parse (&nvc, NULL, msg);
  if (err)
    {
      log_error ("parsing the WKS message failed: %s\n", gpg_strerror (err));
      goto leave;
    }

  if (opt.debug)
    {
      log_debug ("response follows:\n");
      nvc_write (nvc, log_get_stream ());
    }

  /* Check that this is a confirmation response.  */
  if (!((item = nvc_lookup (nvc, "type:")) && (value = nve_value (item))
        && !strcmp (value, "confirmation-response")))
    {
      if (item && value)
        log_error ("received unexpected wks message '%s'\n", value);
      else
        log_error ("received invalid wks message: %s\n", "'type' missing");
      err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
      goto leave;
    }

  /* Get the sender.  */
  if (!((item = nvc_lookup (nvc, "sender:")) && (value = nve_value (item))
        && is_valid_mailbox (value)))
    {
      log_error ("received invalid wks message: %s\n",
                 "'sender' missing or invalid");
      err = gpg_error (GPG_ERR_INV_DATA);
      goto leave;
    }
  sender = value;
  (void)sender;
  /* FIXME: Do we really need the sender?.  */

  /* Get the address.  */
  if (!((item = nvc_lookup (nvc, "address:")) && (value = nve_value (item))
        && is_valid_mailbox (value)))
    {
      log_error ("received invalid wks message: %s\n",
                 "'address' missing or invalid");
      err = gpg_error (GPG_ERR_INV_DATA);
      goto leave;
    }
  address = value;

  /* Get the nonce.  */
  if (!((item = nvc_lookup (nvc, "nonce:")) && (value = nve_value (item))
        && strlen (value) > 16))
    {
      log_error ("received invalid wks message: %s\n",
                 "'nonce' missing or too short");
      err = gpg_error (GPG_ERR_INV_DATA);
      goto leave;
    }
  nonce = value;

  err = check_and_publish (ctx, address, nonce);


 leave:
  nvc_release (nvc);
  return err;
}



/* Called from the MIME receiver to process the plain text data in MSG .  */
static gpg_error_t
command_receive_cb (void *opaque, const char *mediatype,
                    estream_t msg, unsigned int flags)
{
  gpg_error_t err;
  struct server_ctx_s ctx;

  (void)opaque;

  memset (&ctx, 0, sizeof ctx);
  if ((flags & WKS_RECEIVE_DRAFT2))
    ctx.draft_version_2 = 1;

  if (!strcmp (mediatype, "application/pgp-keys"))
    err = process_new_key (&ctx, msg);
  else if (!strcmp (mediatype, "application/vnd.gnupg.wks"))
    err = process_confirmation_response (&ctx, msg);
  else
    {
      log_info ("ignoring unexpected message of type '%s'\n", mediatype);
      err = gpg_error (GPG_ERR_UNEXPECTED_MSG);
    }

  xfree (ctx.fpr);
  free_uidinfo_list (ctx.mboxes);

  return err;
}



/* Return a list of all configured domains.  Each list element is the
 * top directory for the domain.  To figure out the actual domain
 * name strrchr(name, '/') can be used.  */
static gpg_error_t
get_domain_list (strlist_t *r_list)
{
  gpg_error_t err;
  gnupg_dir_t dir = NULL;
  char *fname = NULL;
  gnupg_dirent_t dentry;
  struct stat sb;
  strlist_t list = NULL;

  *r_list = NULL;

  dir = gnupg_opendir (opt.directory);
  if (!dir)
    {
      err = gpg_error_from_syserror ();
      goto leave;
    }

  while ((dentry = gnupg_readdir (dir)))
    {
      if (*dentry->d_name == '.')
        continue;
      if (!strchr (dentry->d_name, '.'))
        continue; /* No dot - can't be a domain subdir.  */

      xfree (fname);
      fname = make_filename_try (opt.directory, dentry->d_name, NULL);
      if (!fname)
        {
          err = gpg_error_from_syserror ();
          log_error ("make_filename failed in %s: %s\n",
                     __func__, gpg_strerror (err));
          goto leave;
        }

      if (gnupg_stat (fname, &sb))
        {
          err = gpg_error_from_syserror ();
          log_error ("error accessing '%s': %s\n", fname, gpg_strerror (err));
          continue;
        }
      if (!S_ISDIR(sb.st_mode))
        continue;

      if (!add_to_strlist_try (&list, fname))
        {
          err = gpg_error_from_syserror ();
          log_error ("add_to_strlist failed in %s: %s\n",
                     __func__, gpg_strerror (err));
          goto leave;
        }
    }
  err = 0;
  *r_list = list;
  list = NULL;

 leave:
  free_strlist (list);
  gnupg_closedir (dir);
  xfree (fname);
  return err;
}



static gpg_error_t
expire_one_domain (const char *top_dirname, const char *domain)
{
  gpg_error_t err;
  char *dirname;
  char *fname = NULL;
  gnupg_dir_t dir = NULL;
  gnupg_dirent_t dentry;
  struct stat sb;
  time_t now = gnupg_get_time ();

  dirname = make_filename_try (top_dirname, "pending", NULL);
  if (!dirname)
    {
      err = gpg_error_from_syserror ();
      log_error ("make_filename failed in %s: %s\n",
                 __func__, gpg_strerror (err));
      goto leave;
    }

  dir = gnupg_opendir (dirname);
  if (!dir)
    {
      err = gpg_error_from_syserror ();
      log_error (("can't access directory '%s': %s\n"),
                 dirname, gpg_strerror (err));
      goto leave;
    }

  while ((dentry = gnupg_readdir (dir)))
    {
      if (*dentry->d_name == '.')
        continue;
      xfree (fname);
      fname = make_filename_try (dirname, dentry->d_name, NULL);
      if (!fname)
        {
          err = gpg_error_from_syserror ();
          log_error ("make_filename failed in %s: %s\n",
                     __func__, gpg_strerror (err));
          goto leave;
        }
      if (strlen (dentry->d_name) != 32)
        {
          log_info ("garbage file '%s' ignored\n", fname);
          continue;
        }
      if (gnupg_stat (fname, &sb))
        {
          err = gpg_error_from_syserror ();
          log_error ("error accessing '%s': %s\n", fname, gpg_strerror (err));
          continue;
        }
      if (S_ISDIR(sb.st_mode))
        {
          log_info ("garbage directory '%s' ignored\n", fname);
          continue;
        }
      if (sb.st_mtime + PENDING_TTL < now)
        {
          if (opt.verbose)
            log_info ("domain %s: removing pending key '%s'\n",
                      domain, dentry->d_name);
          if (remove (fname))
            {
              err = gpg_error_from_syserror ();
              /* In case the file has just been renamed or another
               * processes is cleaning up, we don't print a diagnostic
               * for ENOENT.  */
              if (gpg_err_code (err) != GPG_ERR_ENOENT)
                log_error ("error removing '%s': %s\n",
                           fname, gpg_strerror (err));
            }
        }
    }
  err = 0;

 leave:
  gnupg_closedir (dir);
  xfree (dirname);
  xfree (fname);
  return err;

}


/* Scan spool directories and expire too old pending keys.  */
static gpg_error_t
expire_pending_confirmations (strlist_t domaindirs)
{
  gpg_error_t err = 0;
  strlist_t sl;
  const char *domain;

  for (sl = domaindirs; sl; sl = sl->next)
    {
      domain = strrchr (sl->d, '/');
      log_assert (domain);
      domain++;

      expire_one_domain (sl->d, domain);
    }

  return err;
}


/* List all configured domains.  */
static gpg_error_t
command_list_domains (void)
{
  static struct {
    const char *name;
    const char *perm;
  } requireddirs[] = {
    { "pending", "-rwx" },
    { "hu",      "-rwxr-xr-x" }
  };
  gpg_err_code_t ec;
  gpg_error_t err;
  strlist_t domaindirs;
  strlist_t sl;
  const char *domain;
  char *fname = NULL;
  int i;
  estream_t fp;

  err = get_domain_list (&domaindirs);
  if (err)
    {
      log_error ("error reading list of domains: %s\n", gpg_strerror (err));
      return err;
    }

  for (sl = domaindirs; sl; sl = sl->next)
    {
      domain = strrchr (sl->d, '/');
      log_assert (domain);
      domain++;
      if (opt_with_dir)
        es_printf ("%s %s\n", domain, sl->d);
      else
        es_printf ("%s\n", domain);


      /* Check that the required directories are there.  */
      for (i=0; i < DIM (requireddirs); i++)
        {
          xfree (fname);
          fname = make_filename_try (sl->d, requireddirs[i].name, NULL);
          if (!fname)
            {
              err = gpg_error_from_syserror ();
              goto leave;
            }
          if ((ec = gnupg_access (fname, W_OK)))
            {
              err = gpg_error (ec);
              if (gpg_err_code (err) == GPG_ERR_ENOENT)
                {
                  if (gnupg_mkdir (fname, requireddirs[i].perm))
                    {
                      err = gpg_error_from_syserror ();
                      log_error ("domain %s: error creating subdir '%s': %s\n",
                                 domain, requireddirs[i].name,
                                 gpg_strerror (err));
                    }
                  else
                    log_info ("domain %s: subdir '%s' created\n",
                              domain, requireddirs[i].name);
                }
              else if (err)
                log_error ("domain %s: problem with subdir '%s': %s\n",
                           domain, requireddirs[i].name, gpg_strerror (err));
            }
        }

      /* Print a warning if the submission address is not configured.  */
      xfree (fname);
      fname = make_filename_try (sl->d, "submission-address", NULL);
      if (!fname)
        {
          err = gpg_error_from_syserror ();
          goto leave;
        }
      if ((ec = gnupg_access (fname, F_OK)))
        {
          err = gpg_error (ec);
          if (gpg_err_code (err) == GPG_ERR_ENOENT)
            log_error ("domain %s: submission address not configured\n",
                       domain);
          else
            log_error ("domain %s: problem with '%s': %s\n",
                       domain, fname, gpg_strerror (err));
        }

      /* Check the syntax of the optional policy file.  */
      xfree (fname);
      fname = make_filename_try (sl->d, "policy", NULL);
      if (!fname)
        {
          err = gpg_error_from_syserror ();
          goto leave;
        }
      fp = es_fopen (fname, "r");
      if (!fp)
        {
          err = gpg_error_from_syserror ();
          if (gpg_err_code (err) == GPG_ERR_ENOENT)
            {
              fp = es_fopen (fname, "w");
              if (!fp)
                log_error ("domain %s: can't create policy file: %s\n",
                           domain, gpg_strerror (err));
              else
                es_fclose (fp);
              fp = NULL;
            }
          else
            log_error ("domain %s: error in policy file: %s\n",
                       domain, gpg_strerror (err));
        }
      else
        {
          struct policy_flags_s policy;
          err = wks_parse_policy (&policy, fp, 0);
          es_fclose (fp);
          wks_free_policy (&policy);
        }
    }
  err = 0;

 leave:
  xfree (fname);
  free_strlist (domaindirs);
  return err;
}


/* Run regular maintenance jobs.  */
static gpg_error_t
command_cron (void)
{
  gpg_error_t err;
  strlist_t domaindirs;

  err = get_domain_list (&domaindirs);
  if (err)
    {
      log_error ("error reading list of domains: %s\n", gpg_strerror (err));
      return err;
    }

  err = expire_pending_confirmations (domaindirs);

  free_strlist (domaindirs);
  return err;
}


/* Check whether the key with USER_ID is installed.  */
static gpg_error_t
command_check_key (const char *userid)
{
  gpg_err_code_t ec;
  gpg_error_t err;
  char *addrspec = NULL;
  char *fname = NULL;

  err = wks_fname_from_userid (userid, 0, &fname, &addrspec);
  if (err)
    goto leave;

  if ((ec = gnupg_access (fname, R_OK)))
    {
      err = gpg_error (ec);
      if (opt_with_file)
        es_printf ("%s n %s\n", addrspec, fname);
      if (gpg_err_code (err) == GPG_ERR_ENOENT)
        {
          if (!opt.quiet)
            log_info ("key for '%s' is NOT installed\n", addrspec);
          log_inc_errorcount ();
          err = 0;
        }
      else
        log_error ("error stating '%s': %s\n", fname, gpg_strerror (err));
      goto leave;
    }

  if (opt_with_file)
    es_printf ("%s i %s\n", addrspec, fname);

  if (opt.verbose)
    log_info ("key for '%s' is installed\n", addrspec);
  err = 0;

 leave:
  xfree (fname);
  xfree (addrspec);
  return err;
}


/* Revoke the key with mail address MAILADDR.  */
static gpg_error_t
command_revoke_key (const char *mailaddr)
{
  /* Remove should be different from removing but we have not yet
   * defined a suitable way to do this.  */
  return wks_cmd_remove_key (mailaddr);
}