summaryrefslogtreecommitdiff
path: root/sm/keydb.c
blob: 5b28df7ab8b310e5954ad10c4614e11ae4fa6ab5 (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
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
/* keydb.c - key database dispatcher
 * Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc.
 * Copyright (C) 2014, 2020 g10 Code GmbH
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
 */

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

#include "gpgsm.h"
#include <assuan.h>
#include "../kbx/keybox.h"
#include "keydb.h"
#include "../common/i18n.h"
#include "../common/asshelp.h"
#include "../kbx/kbx-client-util.h"


typedef enum {
    KEYDB_RESOURCE_TYPE_NONE = 0,
    KEYDB_RESOURCE_TYPE_KEYBOX
} KeydbResourceType;
#define MAX_KEYDB_RESOURCES 20

struct resource_item {
  KeydbResourceType type;
  union {
    KEYBOX_HANDLE kr;
  } u;
  void *token;
};


/* Data used to keep track of keybox daemon sessions.  This allows us
 * to use several sessions with the keyboxd and also to re-use already
 * established sessions.  Note that gpgdm.h defines the type
 * keydb_local_t for this structure.  */
struct keydb_local_s
{
  /* Link to other keyboxd contexts which are used simultaneously.  */
  struct keydb_local_s *next;

  /* The active Assuan context. */
  assuan_context_t ctx;

  /* The client data helper context.  */
  kbx_client_data_t kcd;

  /* I/O buffer with the last search result or NULL.  Used if
   * D-lines are used to convey the keyblocks. */
  struct {
    char *buf;
    size_t len;
  } search_result;
  /* The "stack" used by keydb_push_found_state.  */
  struct {
    char *buf;
    size_t len;
  } saved_search_result;

  /* This flag set while an operation is running on this context.  */
  unsigned int is_active : 1;

  /* Flag indicating that a search reset is required.  */
  unsigned int need_search_reset : 1;
};


static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
static int used_resources;

/* Whether we have successfully registered any resource.  */
static int any_registered;

/* Number of active handles.  */
static int active_handles;



struct keydb_handle {

  /* CTRL object passed to keydb_new.  */
  ctrl_t ctrl;

  /* If set the keyboxdd is used instead of the local files.  */
  int use_keyboxd;

  /* BEGIN USE_KEYBOXD */
  /* (These fields are only valid if USE_KEYBOXD is set.) */

  /* Connection info which also keeps the local state.  (This points
   * into the CTRL->keybox_local list.) */
  keydb_local_t kbl;

  /* Various flags.  */
  unsigned int last_ubid_valid:1;
  unsigned int last_is_ephemeral;  /* Last found key is ephemeral.  */

  /* The UBID of the last returned keyblock.  */
  unsigned char last_ubid[UBID_LEN];

  /* END USE_KEYBOXD */

  /* BEGIN !USE_KEYBOXD */
  /* (The remaining fields are only valid if USE_KEYBOXD is cleared.)  */

  /* If this flag is set the resources is locked.  */
  int locked;

  /* If this flag is set a lock will only be released by
   * keydb_release.  */
  int keep_lock;

  int found;
  int saved_found;
  int current;
  int is_ephemeral;
  int used; /* items in active */
  struct resource_item active[MAX_KEYDB_RESOURCES];

  /* END !USE_KEYBOXD */
};


static int lock_all (KEYDB_HANDLE hd);
static void unlock_all (KEYDB_HANDLE hd);



/* Deinitialize all session resources pertaining to the keyboxd.  */
void
gpgsm_keydb_deinit_session_data (ctrl_t ctrl)
{
  keydb_local_t kbl;

  while ((kbl = ctrl->keydb_local))
    {
      ctrl->keydb_local = kbl->next;
      if (kbl->is_active)
        log_error ("oops: trying to cleanup an active keydb context\n");
      else
        {
          kbx_client_data_release (kbl->kcd);
          kbl->kcd = NULL;
          assuan_release (kbl->ctx);
          kbl->ctx = NULL;
        }
      xfree (kbl);
    }
}


static void
try_make_homedir (const char *fname)
{
  if ( opt.dry_run || opt.no_homedir_creation )
    return;

  gnupg_maybe_make_homedir (fname, opt.quiet);
}


/* Handle the creation of a keybox if it does not yet exist.  Take
   into account that other processes might have the keybox already
   locked.  This lock check does not work if the directory itself is
   not yet available.  If R_CREATED is not NULL it will be set to true
   if the function created a new keybox.  */
static gpg_error_t
maybe_create_keybox (char *filename, int force, int *r_created)
{
  gpg_err_code_t ec;
  dotlock_t lockhd = NULL;
  estream_t fp;
  int rc;
  mode_t oldmask;
  char *last_slash_in_filename;
  int save_slash;

  if (r_created)
    *r_created = 0;

  /* A quick test whether the filename already exists. */
  if (!gnupg_access (filename, F_OK))
    return !gnupg_access (filename, R_OK)? 0 : gpg_error (GPG_ERR_EACCES);

  /* If we don't want to create a new file at all, there is no need to
     go any further - bail out right here.  */
  if (!force)
    return gpg_error (GPG_ERR_ENOENT);

  /* First of all we try to create the home directory.  Note, that we
     don't do any locking here because any sane application of gpg
     would create the home directory by itself and not rely on gpg's
     tricky auto-creation which is anyway only done for some home
     directory name patterns. */
  last_slash_in_filename = strrchr (filename, DIRSEP_C);
#if HAVE_W32_SYSTEM
  {
    /* Windows may either have a slash or a backslash.  Take care of it.  */
    char *p = strrchr (filename, '/');
    if (!last_slash_in_filename || p > last_slash_in_filename)
      last_slash_in_filename = p;
  }
#endif /*HAVE_W32_SYSTEM*/
  if (!last_slash_in_filename)
    return gpg_error (GPG_ERR_ENOENT);  /* No slash at all - should
                                           not happen though.  */
  save_slash = *last_slash_in_filename;
  *last_slash_in_filename = 0;
  if (gnupg_access(filename, F_OK))
    {
      static int tried;

      if (!tried)
        {
          tried = 1;
          try_make_homedir (filename);
        }
      if ((ec = gnupg_access (filename, F_OK)))
        {
          rc = gpg_error (ec);
          *last_slash_in_filename = save_slash;
          goto leave;
        }
    }
  *last_slash_in_filename = save_slash;

  /* To avoid races with other instances of gpg trying to create or
     update the keybox (it is removed during an update for a short
     time), we do the next stuff in a locked state. */
  lockhd = dotlock_create (filename, 0);
  if (!lockhd)
    {
      /* A reason for this to fail is that the directory is not
         writable. However, this whole locking stuff does not make
         sense if this is the case. An empty non-writable directory
         with no keyring is not really useful at all. */
      if (opt.verbose)
        log_info ("can't allocate lock for '%s'\n", filename );

      if (!force)
        return gpg_error (GPG_ERR_ENOENT);
      else
        return gpg_error (GPG_ERR_GENERAL);
    }

  if ( dotlock_take (lockhd, -1) )
    {
      /* This is something bad.  Probably a stale lockfile.  */
      log_info ("can't lock '%s'\n", filename);
      rc = gpg_error (GPG_ERR_GENERAL);
      goto leave;
    }

  /* Now the real test while we are locked. */
  if (!gnupg_access(filename, F_OK))
    {
      rc = 0;  /* Okay, we may access the file now.  */
      goto leave;
    }

  /* The file does not yet exist, create it now. */
  oldmask = umask (077);
  fp = es_fopen (filename, "wb");
  if (!fp)
    {
      rc = gpg_error_from_syserror ();
      umask (oldmask);
      log_error (_("error creating keybox '%s': %s\n"),
                 filename, gpg_strerror (rc));
      goto leave;
    }
  umask (oldmask);

  /* Make sure that at least one record is in a new keybox file, so
     that the detection magic for OpenPGP keyboxes works the next time
     it is used.  */
  rc = _keybox_write_header_blob (fp, 0);
  if (rc)
    {
      es_fclose (fp);
      log_error (_("error creating keybox '%s': %s\n"),
                 filename, gpg_strerror (rc));
      goto leave;
    }

  if (!opt.quiet)
    log_info (_("keybox '%s' created\n"), filename);
  if (r_created)
    *r_created = 1;

  es_fclose (fp);
  rc = 0;

 leave:
  if (lockhd)
    {
      dotlock_release (lockhd);
      dotlock_destroy (lockhd);
    }
  return rc;
}


/*
 * Register a resource (which currently may only be a keybox file).
 * The first keybox which is added by this function is created if it
 * does not exist.  If AUTO_CREATED is not NULL it will be set to true
 * if the function has created a new keybox.
 */
gpg_error_t
keydb_add_resource (ctrl_t ctrl, const char *url, int force, int *auto_created)
{
  const char *resname = url;
  char *filename = NULL;
  gpg_error_t err = 0;
  KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;

  if (auto_created)
    *auto_created = 0;

  /* Do we have an URL?
     gnupg-kbx:filename := this is a plain keybox
     filename := See what it is, but create as plain keybox.
  */
  if (strlen (resname) > 10)
    {
      if (!strncmp (resname, "gnupg-kbx:", 10) )
        {
          rt = KEYDB_RESOURCE_TYPE_KEYBOX;
          resname += 10;
	}
#if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
      else if (strchr (resname, ':'))
        {
          log_error ("invalid key resource URL '%s'\n", url );
          err = gpg_error (GPG_ERR_GENERAL);
          goto leave;
	}
#endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
    }

  if (*resname != DIRSEP_C )
    { /* do tilde expansion etc */
      if (strchr(resname, DIRSEP_C) )
        filename = make_filename (resname, NULL);
      else
        filename = make_filename (gnupg_homedir (), resname, NULL);
    }
  else
    filename = xstrdup (resname);

  if (!force)
    force = !any_registered;

  /* see whether we can determine the filetype */
  if (rt == KEYDB_RESOURCE_TYPE_NONE)
    {
      estream_t fp;

      fp = es_fopen( filename, "rb" );
      if (fp)
        {
          u32 magic;

          /* FIXME: check for the keybox magic */
          if (es_fread (&magic, 4, 1, fp) == 1 )
            {
              if (magic == 0x13579ace || magic == 0xce9a5713)
                ; /* GDBM magic - no more support */
              else
                rt = KEYDB_RESOURCE_TYPE_KEYBOX;
            }
          else /* maybe empty: assume keybox */
            rt = KEYDB_RESOURCE_TYPE_KEYBOX;

          es_fclose (fp);
        }
      else /* no file yet: create keybox */
        rt = KEYDB_RESOURCE_TYPE_KEYBOX;
    }

  switch (rt)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      log_error ("unknown type of key resource '%s'\n", url );
      err = gpg_error (GPG_ERR_GENERAL);
      goto leave;

    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = maybe_create_keybox (filename, force, auto_created);
      if (err)
        goto leave;
      /* Now register the file */
      {
        void *token;

        err = keybox_register_file (filename, 0, &token);
        if (gpg_err_code (err) == GPG_ERR_EEXIST)
          ; /* Already registered - ignore.  */
        else if (err)
          ; /* Other error.  */
        else if (used_resources >= MAX_KEYDB_RESOURCES)
          err = gpg_error (GPG_ERR_RESOURCE_LIMIT);
        else
          {
            KEYBOX_HANDLE kbxhd;

            all_resources[used_resources].type = rt;
            all_resources[used_resources].u.kr = NULL; /* Not used here */
            all_resources[used_resources].token = token;

            /* Do a compress run if needed and the keybox is not locked. */
            kbxhd = keybox_new_x509 (token, 0);
            if (kbxhd)
              {
                if (!keybox_lock (kbxhd, 1, 0))
                  {
                    keybox_compress (kbxhd);
                    keybox_lock (kbxhd, 0, 0);
                  }

                keybox_release (kbxhd);
              }

            used_resources++;
          }
      }
      break;

    default:
      log_error ("resource type of '%s' not supported\n", url);
      err = gpg_error (GPG_ERR_NOT_SUPPORTED);
      goto leave;
    }

  /* fixme: check directory permissions and print a warning */

 leave:
  if (err)
    {
      log_error ("keyblock resource '%s': %s\n", filename, gpg_strerror (err));
      gpgsm_status_with_error (ctrl, STATUS_ERROR,
                               "add_keyblock_resource", err);
    }
  else
    any_registered = 1;
  xfree (filename);
  return err;
}


/* Print a warning if the server's version number is less than our
   version number.  Returns an error code on a connection problem.  */
static gpg_error_t
warn_version_mismatch (ctrl_t ctrl, assuan_context_t ctx,
                       const char *servername)
{
  return warn_server_version_mismatch (ctx, servername, 0,
                                       gpgsm_status2, ctrl,
                                       !opt.quiet);
}


/* Connect to the keybox daemon and launch it if necessary.  Handle
 * the server's initial greeting and set global options.  Returns a
 * new assuan context or an error.  */
static gpg_error_t
create_new_context (ctrl_t ctrl, assuan_context_t *r_ctx)
{
  gpg_error_t err;
  assuan_context_t ctx;

  *r_ctx = NULL;

  err = start_new_keyboxd (&ctx,
                           GPG_ERR_SOURCE_DEFAULT,
                           opt.keyboxd_program,
                           opt.autostart, opt.verbose, DBG_IPC,
                           NULL, ctrl);
  if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_KEYBOXD)
    {
      static int shown;

      if (!shown)
        {
          shown = 1;
          log_info (_("no keyboxd running in this session\n"));
        }
    }
  else if (!err && !(err = warn_version_mismatch (ctrl, ctx, KEYBOXD_NAME)))
    {
      /* Place to emit global options.  */
    }

  if (err)
    assuan_release (ctx);
  else
    *r_ctx = ctx;

  return err;
}


/* Get a context for accessing keyboxd.  If no context is available a
 * new one is created and if necessary keyboxd is started.  R_KBL
 * receives a pointer to the local context object.  */
static gpg_error_t
open_context (ctrl_t ctrl, keydb_local_t *r_kbl)
{
  gpg_error_t err;
  keydb_local_t kbl;

  *r_kbl = NULL;
  for (;;)
    {
      for (kbl = ctrl->keydb_local; kbl && kbl->is_active; kbl = kbl->next)
        ;
      if (kbl)
        {
          /* Found an inactive keyboxd session - return that.  */
          log_assert (!kbl->is_active);

          kbl->is_active = 1;
          kbl->need_search_reset = 1;

          *r_kbl = kbl;
          return 0;
        }

      /* None found.  Create a new session and retry.  */
      kbl = xtrycalloc (1, sizeof *kbl);
      if (!kbl)
        return gpg_error_from_syserror ();

      err = create_new_context (ctrl, &kbl->ctx);
      if (err)
        {
          xfree (kbl);
          return err;
        }

      err = kbx_client_data_new (&kbl->kcd, kbl->ctx, 1);
      if (err)
        {
          assuan_release (kbl->ctx);
          xfree (kbl);
          return err;
        }

      /* For thread-saftey we add it to the list and retry; this is
       * easier than to employ a lock.  */
      kbl->next = ctrl->keydb_local;
      ctrl->keydb_local = kbl;
    }
  /*NOTREACHED*/
}


KEYDB_HANDLE
keydb_new (ctrl_t ctrl)
{
  gpg_error_t err;
  KEYDB_HANDLE hd;
  int rc, i, j;

  if (DBG_CLOCK)
    log_clock ("%s: enter\n", __func__);

  hd = xcalloc (1, sizeof *hd);
  hd->found = -1;
  hd->saved_found = -1;
  hd->use_keyboxd = opt.use_keyboxd;
  hd->ctrl = ctrl;
  if (hd->use_keyboxd)
    {
      err = open_context (ctrl, &hd->kbl);
      if (err)
        {
          log_error (_("error opening key DB: %s\n"), gpg_strerror (err));
          xfree (hd);
          hd = NULL;
          if (!(rc = gpg_err_code_to_errno (err)))
            rc = gpg_err_code_to_errno (GPG_ERR_EIO);
          gpg_err_set_errno (rc);
          goto leave;
        }
    }
  else /* Use the local keybox.  */
    {
      log_assert (used_resources <= MAX_KEYDB_RESOURCES);
      for (i=j=0; i < used_resources; i++)
        {
          switch (all_resources[i].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
              break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              hd->active[j].type   = all_resources[i].type;
              hd->active[j].token  = all_resources[i].token;
              hd->active[j].u.kr = keybox_new_x509 (all_resources[i].token, 0);
              if (!hd->active[j].u.kr)
                {
                  xfree (hd);
                  return NULL; /* fixme: free all previously allocated handles*/
                }
              j++;
              break;
            }
        }
      hd->used = j;
    }

  active_handles++;

 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (hd=%p)\n", __func__, hd);
  return hd;
}

void
keydb_release (KEYDB_HANDLE hd)
{
  keydb_local_t kbl;
  int i;

  if (!hd)
    return;

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  log_assert (active_handles > 0);
  active_handles--;

  if (hd->use_keyboxd)
    {
      kbl = hd->kbl;
      if (DBG_CLOCK)
        log_clock ("close_context (found)");
      if (!kbl->is_active)
        log_fatal ("closing inactive keyboxd context %p\n", kbl);
      kbl->is_active = 0;
      hd->kbl = NULL;
    }
  else
    {
      hd->keep_lock = 0;
      unlock_all (hd);
      for (i=0; i < hd->used; i++)
        {
          switch (hd->active[i].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE:
          break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              keybox_release (hd->active[i].u.kr);
              break;
            }
        }
    }

  xfree (hd);
  if (DBG_CLOCK)
    log_clock ("%s: leave\n", __func__);
}


/* Return the name of the current resource.  This is function first
   looks for the last found found, then for the current search
   position, and last returns the first available resource.  The
   returned string is only valid as long as the handle exists.  This
   function does only return NULL if no handle is specified, in all
   other error cases an empty string is returned.  */
const char *
keydb_get_resource_name (KEYDB_HANDLE hd)
{
  int idx;
  const char *s = NULL;

  if (!hd)
    return NULL;

  if (hd->use_keyboxd)
    return "[keyboxd]";

  if ( hd->found >= 0 && hd->found < hd->used)
    idx = hd->found;
  else if ( hd->current >= 0 && hd->current < hd->used)
    idx = hd->current;
  else
    idx = 0;

  switch (hd->active[idx].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      s = NULL;
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      s = keybox_get_resource_name (hd->active[idx].u.kr);
      break;
    }

  return s? s: "";
}

/* Switch the handle into ephemeral mode and return the original value. */
int
keydb_set_ephemeral (KEYDB_HANDLE hd, int yes)
{
  int i;

  if (!hd)
    return 0;

  if (hd->use_keyboxd)
    return 0; /* FIXME: No support yet.  */


  yes = !!yes;
  if (hd->is_ephemeral != yes)
    {
      for (i=0; i < hd->used; i++)
        {
          switch (hd->active[i].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE:
              break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              keybox_set_ephemeral (hd->active[i].u.kr, yes);
              break;
            }
        }
    }

  i = hd->is_ephemeral;
  hd->is_ephemeral = yes;
  return i;
}


/* If the keyring has not yet been locked, lock it now.  This
 * operation is required before any update operation; it is optional
 * for an insert operation.  The lock is kept until a keydb_release so
 * that internal unlock_all calls have no effect.  */
gpg_error_t
keydb_lock (KEYDB_HANDLE hd)
{
  gpg_error_t err;

  if (!hd)
    return gpg_error (GPG_ERR_INV_HANDLE);
  if (hd->use_keyboxd)
    return 0;

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);
  err = lock_all (hd);
  if (!err)
    hd->keep_lock = 1;

  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
}



static int
lock_all (KEYDB_HANDLE hd)
{
  int i, rc = 0;

  if (hd->use_keyboxd)
    return 0;

  /* Fixme: This locking scheme may lead to deadlock if the resources
     are not added in the same order by all processes.  We are
     currently only allowing one resource so it is not a problem. */
  for (i=0; i < hd->used; i++)
    {
      switch (hd->active[i].type)
        {
        case KEYDB_RESOURCE_TYPE_NONE:
          break;
        case KEYDB_RESOURCE_TYPE_KEYBOX:
          rc = keybox_lock (hd->active[i].u.kr, 1, -1);
          break;
        }
      if (rc)
        break;
    }

    if (rc)
      {
        /* Revert the already set locks.  */
        for (i--; i >= 0; i--)
          {
            switch (hd->active[i].type)
              {
              case KEYDB_RESOURCE_TYPE_NONE:
                break;
              case KEYDB_RESOURCE_TYPE_KEYBOX:
                keybox_lock (hd->active[i].u.kr, 0, 0);
                break;
              }
          }
      }
    else
      hd->locked = 1;

    return rc;
}

static void
unlock_all (KEYDB_HANDLE hd)
{
  int i;

  if (hd->use_keyboxd)
    return;

  if (!hd->locked || hd->keep_lock)
    return;

  for (i=hd->used-1; i >= 0; i--)
    {
      switch (hd->active[i].type)
        {
        case KEYDB_RESOURCE_TYPE_NONE:
          break;
        case KEYDB_RESOURCE_TYPE_KEYBOX:
          keybox_lock (hd->active[i].u.kr, 0, 0);
          break;
        }
    }
  hd->locked = 0;
}



/* Push the last found state if any.   Only one state is saved.  */
void
keydb_push_found_state (KEYDB_HANDLE hd)
{
  if (!hd)
    return;

  if (hd->use_keyboxd)
    {
      xfree (hd->kbl->saved_search_result.buf);
      hd->kbl->saved_search_result.buf = hd->kbl->search_result.buf;
      hd->kbl->saved_search_result.len = hd->kbl->search_result.len;
      hd->kbl->search_result.buf = NULL;
      hd->kbl->search_result.len = 0;
    }
  else
    {
      if (hd->found < 0 || hd->found >= hd->used)
        hd->saved_found = -1;
      else
        {
          switch (hd->active[hd->found].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE:
              break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              keybox_push_found_state (hd->active[hd->found].u.kr);
              break;
            }

          hd->saved_found = hd->found;
          hd->found = -1;
        }
    }

  if (DBG_CLOCK)
    log_clock ("%s: done (hd=%p)\n", __func__, hd);
}


/* Pop the last found state.  */
void
keydb_pop_found_state (KEYDB_HANDLE hd)
{
  if (!hd)
    return;

  if (hd->use_keyboxd)
    {
      xfree (hd->kbl->search_result.buf);
      hd->kbl->search_result.buf = hd->kbl->saved_search_result.buf;
      hd->kbl->search_result.len = hd->kbl->saved_search_result.len;
      hd->kbl->saved_search_result.buf = NULL;
      hd->kbl->saved_search_result.len = 0;
    }
  else
    {
      hd->found = hd->saved_found;
      hd->saved_found = -1;
      if (hd->found < 0 || hd->found >= hd->used)
        ;
      else
        {
          switch (hd->active[hd->found].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE:
              break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              keybox_pop_found_state (hd->active[hd->found].u.kr);
              break;
            }
        }
    }

  if (DBG_CLOCK)
    log_clock ("%s: done (hd=%p)\n", __func__, hd);
}



/* Return the last found certificate.  Caller must free it.  */
int
keydb_get_cert (KEYDB_HANDLE hd, ksba_cert_t *r_cert)
{
  int err = 0;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (hd->use_keyboxd)
    {
      ksba_cert_t cert;

      /* Fixme: We should clear that also in non-keyboxd mode but we
       * did not in the past and thus all code should be checked
       * whether this is okay.  If we run into error in keyboxd mode,
       * this is a not as severe because keyboxd is currently
       * experimental.  */
      *r_cert = NULL;

      if (!hd->kbl->search_result.buf || !hd->kbl->search_result.len)
        {
          err = gpg_error (GPG_ERR_VALUE_NOT_FOUND);
          goto leave;
        }
      err = ksba_cert_new (&cert);
      if (err)
        goto leave;
      err = ksba_cert_init_from_mem (cert,
                                     hd->kbl->search_result.buf,
                                     hd->kbl->search_result.len);
      if (err)
        {
          ksba_cert_release (cert);
          goto leave;
        }
      *r_cert = cert;
      goto leave;
    }

  if ( hd->found < 0 || hd->found >= hd->used)
    {
      /* Fixme: It would be better to use GPG_ERR_VALUE_NOT_FOUND here
       * but for now we use NOT_FOUND because that is our standard
       * replacement for the formerly used (-1).  */
      err = gpg_error (GPG_ERR_NOT_FOUND); /* nothing found */
      goto leave;
    }

  err = GPG_ERR_BUG;
  switch (hd->active[hd->found].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      err = gpg_error (GPG_ERR_GENERAL); /* oops */
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = keybox_get_cert (hd->active[hd->found].u.kr, r_cert);
      break;
    }

 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (rc=%d)\n", __func__, err);
  return err;
}


/* Return a flag of the last found object. WHICH is the flag requested;
   it should be one of the KEYBOX_FLAG_ values.  If the operation is
   successful, the flag value will be stored at the address given by
   VALUE.  Return 0 on success or an error code. */
gpg_error_t
keydb_get_flags (KEYDB_HANDLE hd, int which, int idx, unsigned int *value)
{
  gpg_error_t err;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (hd->use_keyboxd)
    {
      /* FIXME */
      *value = 0;
      err = 0;
      goto leave;
    }

  if ( hd->found < 0 || hd->found >= hd->used)
    {
      err = gpg_error (GPG_ERR_NOTHING_FOUND);
      goto leave;
    }

  err = gpg_error (GPG_ERR_BUG);
  switch (hd->active[hd->found].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      err = gpg_error (GPG_ERR_GENERAL); /* oops */
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = keybox_get_flags (hd->active[hd->found].u.kr, which, idx, value);
      break;
    }

 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
}


/* Set a flag of the last found object. WHICH is the flag to be set; it
   should be one of the KEYBOX_FLAG_ values.  If the operation is
   successful, the flag value will be stored in the keybox.  Note,
   that some flag values can't be updated and thus may return an
   error, some other flag values may be masked out before an update.
   Returns 0 on success or an error code. */
gpg_error_t
keydb_set_flags (KEYDB_HANDLE hd, int which, int idx, unsigned int value)
{
  gpg_error_t err = 0;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (hd->use_keyboxd)
    {
      /* FIXME */
      goto leave;
    }

  if ( hd->found < 0 || hd->found >= hd->used)
    {
      err = gpg_error (GPG_ERR_NOTHING_FOUND);
      goto leave;
    }

  if (!hd->locked)
    {
      err = gpg_error (GPG_ERR_NOT_LOCKED);
      goto leave;
    }

  switch (hd->active[hd->found].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      err = gpg_error (GPG_ERR_GENERAL); /* oops */
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = keybox_set_flags (hd->active[hd->found].u.kr, which, idx, value);
      break;
    }

 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
}



/* Communication object for Keyboxd STORE commands.  */
struct store_parm_s
{
  assuan_context_t ctx;
  const void *data;   /* The certificate in X.509 binary format.  */
  size_t datalen;     /* The length of DATA.  */
};


/* Handle the inquiries from the STORE command.  */
static gpg_error_t
store_inq_cb (void *opaque, const char *line)
{
  struct store_parm_s *parm = opaque;
  gpg_error_t err = 0;

  if (has_leading_keyword (line, "BLOB"))
    {
      if (parm->data)
        err = assuan_send_data (parm->ctx, parm->data, parm->datalen);
    }
  else
    return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);

  return err;
}


/*
 * Insert a new Certificate into one of the resources.
 */
gpg_error_t
keydb_insert_cert (KEYDB_HANDLE hd, ksba_cert_t cert)
{
  gpg_error_t err;
  int idx;
  unsigned char digest[20];

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (opt.dry_run)
    return 0;

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (hd->use_keyboxd)
    {
      struct store_parm_s parm;

      parm.ctx = hd->kbl->ctx;
      parm.data = ksba_cert_get_image (cert, &parm.datalen);
      if (!parm.data)
        {
          log_debug ("broken ksba cert object\n");
          err = gpg_error (GPG_ERR_GENERAL);
          goto leave;
        }
      err = assuan_transact (hd->kbl->ctx, "STORE --insert",
                             NULL, NULL,
                             store_inq_cb, &parm,
                             NULL, NULL);
      goto leave;
    }

  if ( hd->found >= 0 && hd->found < hd->used)
    idx = hd->found;
  else if ( hd->current >= 0 && hd->current < hd->used)
    idx = hd->current;
  else
    {
      err = gpg_error (GPG_ERR_GENERAL);
      goto leave;
    }

  if (!hd->locked)
    {
      err = gpg_error (GPG_ERR_NOT_LOCKED);
      goto leave;
    }

  gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/

  err = gpg_error (GPG_ERR_BUG);
  switch (hd->active[idx].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      err = gpg_error (GPG_ERR_GENERAL);
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = keybox_insert_cert (hd->active[idx].u.kr, cert, digest);
      break;
    }

  unlock_all (hd);

 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
}



/* Update the current keyblock with KB.  */
/* Note: This function is currently not called.  */
gpg_error_t
keydb_update_cert (KEYDB_HANDLE hd, ksba_cert_t cert)
{
  (void)hd;
  (void)cert;
  return GPG_ERR_BUG;
#if 0
  gpg_error_t err;
  unsigned char digest[20];

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if ( hd->found < 0 || hd->found >= hd->used)
    return gpg_error (GPG_ERR_NOT_FOUND);

  if (opt.dry_run)
    return 0;

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (hd->use_keyboxd)
    {
      /* FIXME */
      goto leave;
    }

  err = lock_all (hd);
  if (err)
    goto leave;

  gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/

  err = gpg_error (GPG_ERR_BUG);
  switch (hd->active[hd->found].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      err = gpg_error (GPG_ERR_GENERAL); /* oops */
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = keybox_update_cert (hd->active[hd->found].u.kr, cert, digest);
      break;
    }

  unlock_all (hd);
 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
#endif /*0*/
}


/*
 * The current keyblock or cert will be deleted.
 */
gpg_error_t
keydb_delete (KEYDB_HANDLE hd)
{
  gpg_error_t err;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (!hd->use_keyboxd && (hd->found < 0 || hd->found >= hd->used))
    return gpg_error (GPG_ERR_NOT_FOUND);

  if (opt.dry_run)
    return 0;

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (hd->use_keyboxd)
    {
      unsigned char hexubid[UBID_LEN * 2 + 1];
      char line[ASSUAN_LINELENGTH];

      if (!hd->last_ubid_valid)
        {
          err = gpg_error (GPG_ERR_VALUE_NOT_FOUND);
          goto leave;
        }

      bin2hex (hd->last_ubid, UBID_LEN, hexubid);
      snprintf (line, sizeof line, "DELETE %s", hexubid);
      err = assuan_transact (hd->kbl->ctx, line,
                             NULL, NULL,
                             NULL, NULL,
                             NULL, NULL);
      goto leave;
    }

  if (!hd->locked)
    {
      err = gpg_error (GPG_ERR_NOT_LOCKED);
      goto leave;
    }

  err = gpg_error (GPG_ERR_BUG);
  switch (hd->active[hd->found].type)
    {
    case KEYDB_RESOURCE_TYPE_NONE:
      err = gpg_error (GPG_ERR_GENERAL);
      break;
    case KEYDB_RESOURCE_TYPE_KEYBOX:
      err = keybox_delete (hd->active[hd->found].u.kr);
      break;
    }

  unlock_all (hd);

 leave:
  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
}



/*
 * Locate the default writable key resource, so that the next
 * operation (which is only relevant for inserts) will be done on this
 * resource.
 */
static gpg_error_t
keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
{
  int rc;

  (void)reserved;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (hd->use_keyboxd)
    return 0;  /* Not required.  */

  rc = keydb_search_reset (hd); /* this does reset hd->current */
  if (rc)
    return rc;

  for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
    {
      switch (hd->active[hd->current].type)
        {
        case KEYDB_RESOURCE_TYPE_NONE:
          BUG();
          break;
        case KEYDB_RESOURCE_TYPE_KEYBOX:
          if (keybox_is_writable (hd->active[hd->current].token))
            return 0; /* found (hd->current is set to it) */
          break;
        }
    }

  return gpg_error (GPG_ERR_NOT_FOUND);
}

/*
 * Rebuild the caches of all key resources.
 */
void
keydb_rebuild_caches (void)
{
  int i;

  /* This function does nothing and thus we don't need to handle keyboxd in a
   * special way.  */

  for (i=0; i < used_resources; i++)
    {
      switch (all_resources[i].type)
        {
        case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
          break;
        case KEYDB_RESOURCE_TYPE_KEYBOX:
/*            rc = keybox_rebuild_cache (all_resources[i].token); */
/*            if (rc) */
/*              log_error (_("failed to rebuild keybox cache: %s\n"), */
/*                         g10_errstr (rc)); */
          break;
        }
    }
}



/*
 * Start the next search on this handle right at the beginning
 */
gpg_error_t
keydb_search_reset (KEYDB_HANDLE hd)
{
  gpg_error_t err = 0;
  int i;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  hd->current = 0;
  hd->found = -1;
  if (hd->use_keyboxd)
    {
      /* All we need is to tell search that a reset is pending.  Note that
       * keydb_new sets this flag as well.  To comply with the
       * specification of keydb_delete_keyblock we also need to clear the
       * ubid flag so that after a reset a delete can't be performed.  */
      hd->kbl->need_search_reset = 1;
      hd->last_ubid_valid = 0;
   }
  else
    {
      /* Reset all resources */
      for (i=0; !err && i < hd->used; i++)
        {
          switch (hd->active[i].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE:
              break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              err = keybox_search_reset (hd->active[i].u.kr);
              break;
            }
        }
    }

  if (DBG_CLOCK)
    log_clock ("%s: leave (err=%s)\n", __func__, gpg_strerror (err));
  return err;
}


char *
keydb_search_desc_dump (struct keydb_search_desc *desc)
{
  char *fpr;
  char *result;

  switch (desc->mode)
    {
    case KEYDB_SEARCH_MODE_EXACT:
      return xasprintf ("EXACT: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_SUBSTR:
      return xasprintf ("SUBSTR: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_MAIL:
      return xasprintf ("MAIL: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_MAILSUB:
      return xasprintf ("MAILSUB: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_MAILEND:
      return xasprintf ("MAILEND: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_WORDS:
      return xasprintf ("WORDS: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_SHORT_KID:
      return xasprintf ("SHORT_KID: '%08lX'", (ulong)desc->u.kid[1]);
    case KEYDB_SEARCH_MODE_LONG_KID:
      return xasprintf ("LONG_KID: '%08lX%08lX'",
                        (ulong)desc->u.kid[0], (ulong)desc->u.kid[1]);
    case KEYDB_SEARCH_MODE_FPR:
      fpr = bin2hexcolon (desc->u.fpr, desc->fprlen, NULL);
      result = xasprintf ("FPR%02d: '%s'", desc->fprlen, fpr);
      xfree (fpr);
      return result;
    case KEYDB_SEARCH_MODE_ISSUER:
      return xasprintf ("ISSUER: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_ISSUER_SN:
      return xasprintf ("ISSUER_SN: '#%.*s/%s'",
                        (int)desc->snlen,desc->sn, desc->u.name);
    case KEYDB_SEARCH_MODE_SN:
      return xasprintf ("SN: '%.*s'",
                        (int)desc->snlen, desc->sn);
    case KEYDB_SEARCH_MODE_SUBJECT:
      return xasprintf ("SUBJECT: '%s'", desc->u.name);
    case KEYDB_SEARCH_MODE_KEYGRIP:
      return xasprintf ("KEYGRIP: %s", desc->u.grip);
    case KEYDB_SEARCH_MODE_FIRST:
      return xasprintf ("FIRST");
    case KEYDB_SEARCH_MODE_NEXT:
      return xasprintf ("NEXT");
    default:
      return xasprintf ("Bad search mode (%d)", desc->mode);
    }
}



/* Status callback for SEARCH and NEXT operaions.  */
static gpg_error_t
search_status_cb (void *opaque, const char *line)
{
  KEYDB_HANDLE hd = opaque;
  gpg_error_t err = 0;
  const char *s;
  unsigned int n;

  if ((s = has_leading_keyword (line, "PUBKEY_INFO")))
    {
      if (atoi (s) != PUBKEY_TYPE_X509)
        err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE);
      else
        {
          hd->last_ubid_valid = 0;
          while (*s && !spacep (s))
            s++;
          if (!(n=hex2fixedbuf (s, hd->last_ubid, sizeof hd->last_ubid)))
            err = gpg_error (GPG_ERR_INV_VALUE);
          else
            {
              hd->last_ubid_valid = 1;
              s += n;
              hd->last_is_ephemeral = (*s == 'e');
            }
        }
    }

  return err;
}

/* Search through all keydb resources, starting at the current
 * position, for a keyblock which contains one of the keys described
 * in the DESC array.  In keyboxd mode the search is instead delegated
 * to the keyboxd.
 *
 * DESC is an array of search terms with NDESC entries.  The search
 * terms are or'd together.  That is, the next entry in the DB that
 * matches any of the descriptions will be returned.
 *
 * Note: this function resumes searching where the last search left
 * off (i.e., at the current file position).  If you want to search
 * from the start of the database, then you need to first call
 * keydb_search_reset().
 *
 * If no key matches the search description, the error code
 * GPG_ERR_NOT_FOUND is retruned.  If there was a match, 0 is
 * returned.  If an error occurred, that error code is returned.
 *
 * The returned key is considered to be selected and the certificate
 * can be detched via keydb_get_cert.  */
gpg_error_t
keydb_search (ctrl_t ctrl, KEYDB_HANDLE hd,
              KEYDB_SEARCH_DESC *desc, size_t ndesc)
{
  gpg_error_t err = gpg_error (GPG_ERR_EOF);
  unsigned long skipped;
  int i;

  if (!hd)
    return gpg_error (GPG_ERR_INV_VALUE);

  if (!any_registered && !hd->use_keyboxd)
    {
      gpgsm_status_with_error (ctrl, STATUS_ERROR, "keydb_search",
                               gpg_error (GPG_ERR_KEYRING_OPEN));
      return gpg_error (GPG_ERR_NOT_FOUND);
    }

  if (DBG_CLOCK)
    log_clock ("%s: enter (hd=%p)\n", __func__, hd);

  if (DBG_LOOKUP)
    {
      log_debug ("%s: %zd search description(s):\n", __func__, ndesc);
      for (i = 0; i < ndesc; i ++)
        {
          char *t = keydb_search_desc_dump (&desc[i]);
          log_debug ("%s:   %d: %s\n", __func__, i, t);
          xfree (t);
        }
    }

  if (hd->use_keyboxd)
    {
      char line[ASSUAN_LINELENGTH];

      /* Clear the result objects.  */
      if (hd->kbl->search_result.buf)
        {
          xfree (hd->kbl->search_result.buf);
          hd->kbl->search_result.buf = NULL;
          hd->kbl->search_result.len = 0;
        }

      /* Check whether this is a NEXT search.  */
      if (!hd->kbl->need_search_reset)
        {
          /* A reset was not requested thus continue the search.  The
           * keyboxd keeps the context of the search and thus the NEXT
           * operates on the last search pattern.  This is the way how
           * we always used the keydb functions.  In theory we were
           * able to modify the search pattern between searches but
           * that is not anymore supported by keyboxd and a cursory
           * check does not show that we actually made use of that
           * misfeature.  */
          snprintf (line, sizeof line, "NEXT --x509");
          goto do_search;
        }

      hd->kbl->need_search_reset = 0;

      if (!ndesc)
        {
          err = gpg_error (GPG_ERR_INV_ARG);
          goto leave;
        }

      /* FIXME: Implement --multi */
      switch (desc->mode)
        {
        case KEYDB_SEARCH_MODE_EXACT:
          snprintf (line, sizeof line, "SEARCH --x509 =%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_SUBSTR:
          snprintf (line, sizeof line, "SEARCH --x509 *%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_MAIL:
          snprintf (line, sizeof line, "SEARCH --x509 <%s",
                    desc[0].u.name + (desc[0].u.name[0] == '<'));
          break;

        case KEYDB_SEARCH_MODE_MAILSUB:
          snprintf (line, sizeof line, "SEARCH --x509 @%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_MAILEND:
          snprintf (line, sizeof line, "SEARCH --x509 .%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_WORDS:
          snprintf (line, sizeof line, "SEARCH --x509 +%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_SHORT_KID:
          snprintf (line, sizeof line, "SEARCH --x509 0x%08lX",
                    (ulong)desc->u.kid[1]);
          break;

        case KEYDB_SEARCH_MODE_LONG_KID:
          snprintf (line, sizeof line, "SEARCH --x509 0x%08lX%08lX",
                    (ulong)desc->u.kid[0], (ulong)desc->u.kid[1]);
          break;

        case KEYDB_SEARCH_MODE_FPR:
          {
            unsigned char hexfpr[MAX_FINGERPRINT_LEN * 2 + 1];
            log_assert (desc[0].fprlen <= MAX_FINGERPRINT_LEN);
            bin2hex (desc[0].u.fpr, desc[0].fprlen, hexfpr);
            snprintf (line, sizeof line, "SEARCH --x509 0x%s", hexfpr);
          }
          break;

        case KEYDB_SEARCH_MODE_ISSUER:
          snprintf (line, sizeof line, "SEARCH --x509 #/%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_ISSUER_SN:
          if (desc[0].snhex)
            snprintf (line, sizeof line, "SEARCH --x509 #%.*s/%s",
                      (int)desc[0].snlen, desc[0].sn, desc[0].u.name);
          else
            {
              char *hexsn = bin2hex (desc[0].sn, desc[0].snlen, NULL);
              if (!hexsn)
                {
                  err = gpg_error_from_syserror ();
                  goto leave;
                }
              snprintf (line, sizeof line, "SEARCH --x509 #%s/%s",
                        hexsn, desc[0].u.name);
              xfree (hexsn);
            }
          break;

        case KEYDB_SEARCH_MODE_SN:
          snprintf (line, sizeof line, "SEARCH --x509 #%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_SUBJECT:
          snprintf (line, sizeof line, "SEARCH --x509 /%s", desc[0].u.name);
          break;

        case KEYDB_SEARCH_MODE_KEYGRIP:
          {
            unsigned char hexgrip[KEYGRIP_LEN * 2 + 1];
            bin2hex (desc[0].u.grip, KEYGRIP_LEN, hexgrip);
            snprintf (line, sizeof line, "SEARCH --x509 &%s", hexgrip);
          }
          break;

        case KEYDB_SEARCH_MODE_UBID:
          {
            unsigned char hexubid[UBID_LEN * 2 + 1];
            bin2hex (desc[0].u.ubid, UBID_LEN, hexubid);
            snprintf (line, sizeof line, "SEARCH --x509 ^%s", hexubid);
          }
          break;

        case KEYDB_SEARCH_MODE_FIRST:
          snprintf (line, sizeof line, "SEARCH --x509");
          break;

        case KEYDB_SEARCH_MODE_NEXT:
          log_debug ("%s: mode next - we should not get to here!\n", __func__);
          snprintf (line, sizeof line, "NEXT --x509");
          break;

        default:
          err = gpg_error (GPG_ERR_INV_ARG);
          goto leave;
        }

    do_search:
      hd->last_ubid_valid = 0;
      /* To avoid silent truncation we error out on a too long line.  */
      if (strlen (line) + 5 >= sizeof line)
        err = gpg_error (GPG_ERR_ASS_LINE_TOO_LONG);
      else
        err = kbx_client_data_cmd (hd->kbl->kcd, line, search_status_cb, hd);
      if (!err && !(err = kbx_client_data_wait (hd->kbl->kcd,
                                                &hd->kbl->search_result.buf,
                                                &hd->kbl->search_result.len)))
        {
          /* if (hd->last_ubid_valid) */
          /*   log_printhex (hd->last_ubid, 20, "found UBID%s:", */
          /*                 hd->last_is_ephemeral? "(ephemeral)":""); */
        }

    }
  else /* Local keyring search.  */
    {
      while (gpg_err_code (err) == GPG_ERR_EOF
             && hd->current >= 0 && hd->current < hd->used)
        {
          switch (hd->active[hd->current].type)
            {
            case KEYDB_RESOURCE_TYPE_NONE:
              BUG(); /* we should never see it here */
              break;
            case KEYDB_RESOURCE_TYPE_KEYBOX:
              err = keybox_search (hd->active[hd->current].u.kr, desc, ndesc,
                                   KEYBOX_BLOBTYPE_X509,
                                   NULL, &skipped);
              if (err == -1) /* Map legacy code.  */
                err = gpg_error (GPG_ERR_EOF);
              break;
            }

          if (DBG_LOOKUP)
            log_debug ("%s: searched %s (resource %d of %d) => %s\n",
                       __func__,
                       hd->active[hd->current].type==KEYDB_RESOURCE_TYPE_KEYBOX
                       ? "keybox" : "unknown type",
                       hd->current, hd->used, gpg_strerror (err));

          if (gpg_err_code (err) == GPG_ERR_EOF)
            { /* EOF -> switch to next resource */
              hd->current++;
            }
          else if (!err)
            hd->found = hd->current;
        }
    }

 leave:
  /* The NOTHING_FOUND error is triggered by a NEXT command.  */
  if (gpg_err_code (err) == GPG_ERR_EOF
      || gpg_err_code (err) == GPG_ERR_NOTHING_FOUND)
    err = gpg_error (GPG_ERR_NOT_FOUND);
  if (DBG_CLOCK)
    log_clock ("%s: leave (%s)\n", __func__, gpg_strerror (err));
  return err;
}


int
keydb_search_first (ctrl_t ctrl, KEYDB_HANDLE hd)
{
  KEYDB_SEARCH_DESC desc;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_FIRST;
  return keydb_search (ctrl, hd, &desc, 1);
}

int
keydb_search_next (ctrl_t ctrl, KEYDB_HANDLE hd)
{
  KEYDB_SEARCH_DESC desc;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_NEXT;
  return keydb_search (ctrl, hd, &desc, 1);
}

int
keydb_search_kid (ctrl_t ctrl, KEYDB_HANDLE hd, u32 *kid)
{
  KEYDB_SEARCH_DESC desc;

  (void)kid;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
  desc.u.kid[0] = kid[0];
  desc.u.kid[1] = kid[1];
  return keydb_search (ctrl, hd, &desc, 1);
}

int
keydb_search_fpr (ctrl_t ctrl, KEYDB_HANDLE hd, const byte *fpr)
{
  KEYDB_SEARCH_DESC desc;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_FPR;
  memcpy (desc.u.fpr, fpr, 20);
  desc.fprlen = 20;
  return keydb_search (ctrl, hd, &desc, 1);
}

int
keydb_search_issuer (ctrl_t ctrl, KEYDB_HANDLE hd, const char *issuer)
{
  KEYDB_SEARCH_DESC desc;
  int rc;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_ISSUER;
  desc.u.name = issuer;
  rc = keydb_search (ctrl, hd, &desc, 1);
  return rc;
}

int
keydb_search_issuer_sn (ctrl_t ctrl, KEYDB_HANDLE hd,
                        const char *issuer, ksba_const_sexp_t serial)
{
  KEYDB_SEARCH_DESC desc;
  int rc;
  const unsigned char *s;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_ISSUER_SN;
  s = serial;
  if (*s !='(')
    return gpg_error (GPG_ERR_INV_VALUE);
  s++;
  for (desc.snlen = 0; digitp (s); s++)
    desc.snlen = 10*desc.snlen + atoi_1 (s);
  if (*s !=':')
    return gpg_error (GPG_ERR_INV_VALUE);
  desc.sn = s+1;
  desc.u.name = issuer;
  rc = keydb_search (ctrl, hd, &desc, 1);
  return rc;
}

int
keydb_search_subject (ctrl_t ctrl, KEYDB_HANDLE hd, const char *name)
{
  KEYDB_SEARCH_DESC desc;
  int rc;

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_SUBJECT;
  desc.u.name = name;
  rc = keydb_search (ctrl, hd, &desc, 1);
  return rc;
}



/* Store the certificate in the key DB but make sure that it does not
   already exists.  We do this simply by comparing the fingerprint.
   If EXISTED is not NULL it will be set to true if the certificate
   was already in the DB. */
int
keydb_store_cert (ctrl_t ctrl, ksba_cert_t cert, int ephemeral, int *existed)
{
  KEYDB_HANDLE kh;
  int rc;
  unsigned char fpr[20];

  if (existed)
    *existed = 0;

  if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL))
    {
      log_error (_("failed to get the fingerprint\n"));
      return gpg_error (GPG_ERR_GENERAL);
    }

  kh = keydb_new (ctrl);
  if (!kh)
    {
      log_error (_("failed to allocate keyDB handle\n"));
      return gpg_error (GPG_ERR_ENOMEM);;
    }

  /* Set the ephemeral flag so that the search looks at all
     records.  */
  keydb_set_ephemeral (kh, 1);

  if (!kh->use_keyboxd)
    {
      rc = lock_all (kh);
      if (rc)
        return rc;
    }

  rc = keydb_search_fpr (ctrl, kh, fpr);
  if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
    {
      keydb_release (kh);
      if (!rc)
        {
          if (existed)
            *existed = 1;
          if (!ephemeral)
            {
              /* Remove ephemeral flags from existing certificate to "store"
                 it permanently. */
              rc = keydb_set_cert_flags (ctrl, cert, 1, KEYBOX_FLAG_BLOB, 0,
                                         KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
              if (rc)
                {
                  log_error ("clearing ephemeral flag failed: %s\n",
                             gpg_strerror (rc));
                  return rc;
                }
            }
          return 0; /* okay */
        }
      log_error (_("problem looking for existing certificate: %s\n"),
                 gpg_strerror (rc));
      return rc;
    }

  /* Reset the ephemeral flag if not requested.  */
  if (!ephemeral)
    keydb_set_ephemeral (kh, 0);

  rc = keydb_locate_writable (kh, 0);
  if (rc)
    {
      log_error (_("error finding writable keyDB: %s\n"), gpg_strerror (rc));
      keydb_release (kh);
      return rc;
    }

  rc = keydb_insert_cert (kh, cert);
  if (rc)
    {
      log_error (_("error storing certificate: %s\n"), gpg_strerror (rc));
      keydb_release (kh);
      return rc;
    }
  keydb_release (kh);
  return 0;
}


/* This is basically keydb_set_flags but it implements a complete
   transaction by locating the certificate in the DB and updating the
   flags. */
gpg_error_t
keydb_set_cert_flags (ctrl_t ctrl, ksba_cert_t cert, int ephemeral,
                      int which, int idx,
                      unsigned int mask, unsigned int value)
{
  KEYDB_HANDLE kh;
  gpg_error_t err;
  unsigned char fpr[20];
  unsigned int old_value;

  if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL))
    {
      log_error (_("failed to get the fingerprint\n"));
      return gpg_error (GPG_ERR_GENERAL);
    }

  kh = keydb_new (ctrl);
  if (!kh)
    {
      log_error (_("failed to allocate keyDB handle\n"));
      return gpg_error (GPG_ERR_ENOMEM);;
    }

  if (ephemeral)
    keydb_set_ephemeral (kh, 1);

  if (!kh->use_keyboxd)
    {
      err = keydb_lock (kh);
      if (err)
        {
          log_error (_("error locking keybox: %s\n"), gpg_strerror (err));
          keydb_release (kh);
          return err;
        }
    }

  err = keydb_search_fpr (ctrl, kh, fpr);
  if (err)
    {
      if (gpg_err_code (err) != gpg_error (GPG_ERR_NOT_FOUND))
        log_error (_("problem re-searching certificate: %s\n"),
                   gpg_strerror (err));
      keydb_release (kh);
      return err;
    }

  err = keydb_get_flags (kh, which, idx, &old_value);
  if (err)
    {
      log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
      keydb_release (kh);
      return err;
    }

  value = ((old_value & ~mask) | (value & mask));

  if (value != old_value)
    {
      err = keydb_set_flags (kh, which, idx, value);
      if (err)
        {
          log_error (_("error storing flags: %s\n"), gpg_strerror (err));
          keydb_release (kh);
          return err;
        }
    }

  keydb_release (kh);
  return 0;
}


/* Reset all the certificate flags we have stored with the certificates
   for performance reasons. */
void
keydb_clear_some_cert_flags (ctrl_t ctrl, strlist_t names)
{
  gpg_error_t err;
  KEYDB_HANDLE hd = NULL;
  KEYDB_SEARCH_DESC *desc = NULL;
  int ndesc;
  strlist_t sl;
  int rc=0;
  unsigned int old_value, value;

  (void)ctrl;

  hd = keydb_new (ctrl);
  if (!hd)
    {
      log_error ("keydb_new failed\n");
      goto leave;
    }

  if (!names)
    ndesc = 1;
  else
    {
      for (sl=names, ndesc=0; sl; sl = sl->next, ndesc++)
        ;
    }

  desc = xtrycalloc (ndesc, sizeof *desc);
  if (!ndesc)
    {
      log_error ("allocating memory failed: %s\n",
                 gpg_strerror (out_of_core ()));
      goto leave;
    }

  if (!names)
    desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
  else
    {
      for (ndesc=0, sl=names; sl; sl = sl->next)
        {
          rc = classify_user_id (sl->d, desc+ndesc, 0);
          if (rc)
            log_error ("key '%s' not found: %s\n", sl->d, gpg_strerror (rc));
          else
            ndesc++;
        }
    }

  if (!hd->use_keyboxd)
    {
      err = keydb_lock (hd);
      if (err)
        {
          log_error (_("error locking keybox: %s\n"), gpg_strerror (err));
          goto leave;
        }
    }

  while (!(rc = keydb_search (ctrl, hd, desc, ndesc)))
    {
      if (!names)
        desc[0].mode = KEYDB_SEARCH_MODE_NEXT;

      err = keydb_get_flags (hd, KEYBOX_FLAG_VALIDITY, 0, &old_value);
      if (err)
        {
          log_error (_("error getting stored flags: %s\n"),
                     gpg_strerror (err));
          goto leave;
        }

      value = (old_value & ~VALIDITY_REVOKED);
      if (value != old_value)
        {
          err = keydb_set_flags (hd, KEYBOX_FLAG_VALIDITY, 0, value);
          if (err)
            {
              log_error (_("error storing flags: %s\n"), gpg_strerror (err));
              goto leave;
            }
        }
    }
  if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
    log_error ("keydb_search failed: %s\n", gpg_strerror (rc));

 leave:
  xfree (desc);
  keydb_release (hd);
}