2007-07-05 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / sm / keydb.c
blob1fbf9b6c128ead87d45c1da4036b39facecd03ee
1 /* keydb.c - key database dispatcher
2 * Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <assert.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
30 #include "gpgsm.h"
31 #include "../kbx/keybox.h"
32 #include "keydb.h"
33 #include "i18n.h"
35 static int active_handles;
37 typedef enum {
38 KEYDB_RESOURCE_TYPE_NONE = 0,
39 KEYDB_RESOURCE_TYPE_KEYBOX
40 } KeydbResourceType;
41 #define MAX_KEYDB_RESOURCES 20
43 struct resource_item {
44 KeydbResourceType type;
45 union {
46 KEYBOX_HANDLE kr;
47 } u;
48 void *token;
49 int secret;
50 DOTLOCK lockhandle;
53 static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
54 static int used_resources;
56 struct keydb_handle {
57 int locked;
58 int found;
59 int current;
60 int is_ephemeral;
61 int used; /* items in active */
62 struct resource_item active[MAX_KEYDB_RESOURCES];
66 static int lock_all (KEYDB_HANDLE hd);
67 static void unlock_all (KEYDB_HANDLE hd);
71 * Register a resource (which currently may only be a keybox file).
72 * The first keybox which is added by this function is created if it
73 * does not exist. If AUTO_CREATED is not NULL it will be set to true
74 * if the function has created a a new keybox.
76 int
77 keydb_add_resource (const char *url, int force, int secret, int *auto_created)
79 static int any_secret, any_public;
80 const char *resname = url;
81 char *filename = NULL;
82 int rc = 0;
83 FILE *fp;
84 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
85 const char *created_fname = NULL;
87 if (auto_created)
88 *auto_created = 0;
90 /* Do we have an URL?
91 gnupg-kbx:filename := this is a plain keybox
92 filename := See what is is, but create as plain keybox.
94 if (strlen (resname) > 10)
96 if (!strncmp (resname, "gnupg-kbx:", 10) )
98 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
99 resname += 10;
101 #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
102 else if (strchr (resname, ':'))
104 log_error ("invalid key resource URL `%s'\n", url );
105 rc = gpg_error (GPG_ERR_GENERAL);
106 goto leave;
108 #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
111 if (*resname != DIRSEP_C )
112 { /* do tilde expansion etc */
113 if (strchr(resname, DIRSEP_C) )
114 filename = make_filename (resname, NULL);
115 else
116 filename = make_filename (opt.homedir, resname, NULL);
118 else
119 filename = xstrdup (resname);
121 if (!force)
122 force = secret? !any_secret : !any_public;
124 /* see whether we can determine the filetype */
125 if (rt == KEYDB_RESOURCE_TYPE_NONE)
127 FILE *fp2 = fopen( filename, "rb" );
129 if (fp2) {
130 u32 magic;
132 /* FIXME: check for the keybox magic */
133 if (fread( &magic, 4, 1, fp2) == 1 )
135 if (magic == 0x13579ace || magic == 0xce9a5713)
136 ; /* GDBM magic - no more support */
137 else
138 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
140 else /* maybe empty: assume ring */
141 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
142 fclose (fp2);
144 else /* no file yet: create ring */
145 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
148 switch (rt)
150 case KEYDB_RESOURCE_TYPE_NONE:
151 log_error ("unknown type of key resource `%s'\n", url );
152 rc = gpg_error (GPG_ERR_GENERAL);
153 goto leave;
155 case KEYDB_RESOURCE_TYPE_KEYBOX:
156 fp = fopen (filename, "rb");
157 if (!fp && !force)
159 rc = gpg_error (gpg_err_code_from_errno (errno));
160 goto leave;
163 if (!fp)
164 { /* no file */
165 #if 0 /* no autocreate of the homedirectory yet */
167 char *last_slash_in_filename;
169 last_slash_in_filename = strrchr (filename, DIRSEP_C);
170 *last_slash_in_filename = 0;
171 if (access (filename, F_OK))
172 { /* on the first time we try to create the default
173 homedir and in this case the process will be
174 terminated, so that on the next invocation can
175 read the options file in on startup */
176 try_make_homedir (filename);
177 rc = gpg_error (GPG_ERR_FILE_OPEN_ERROR);
178 *last_slash_in_filename = DIRSEP_C;
179 goto leave;
181 *last_slash_in_filename = DIRSEP_C;
183 #endif
184 fp = fopen (filename, "w");
185 if (!fp)
187 rc = gpg_error (gpg_err_code_from_errno (errno));
188 log_error (_("error creating keybox `%s': %s\n"),
189 filename, strerror(errno));
190 if (errno == ENOENT)
191 log_info (_("you may want to start the gpg-agent first\n"));
192 goto leave;
195 if (!opt.quiet)
196 log_info (_("keybox `%s' created\n"), filename);
197 created_fname = filename;
198 if (auto_created)
199 *auto_created = 1;
201 fclose (fp);
202 fp = NULL;
203 /* now register the file */
206 void *token = keybox_register_file (filename, secret);
207 if (!token)
208 ; /* already registered - ignore it */
209 else if (used_resources >= MAX_KEYDB_RESOURCES)
210 rc = gpg_error (GPG_ERR_RESOURCE_LIMIT);
211 else
213 all_resources[used_resources].type = rt;
214 all_resources[used_resources].u.kr = NULL; /* Not used here */
215 all_resources[used_resources].token = token;
216 all_resources[used_resources].secret = secret;
218 all_resources[used_resources].lockhandle
219 = create_dotlock (filename);
220 if (!all_resources[used_resources].lockhandle)
221 log_fatal ( _("can't create lock for `%s'\n"), filename);
223 /* Do a compress run if needed and the file is not locked. */
224 if (!make_dotlock (all_resources[used_resources].lockhandle, 0))
226 KEYBOX_HANDLE kbxhd = keybox_new (token, secret);
228 if (kbxhd)
230 keybox_compress (kbxhd);
231 keybox_release (kbxhd);
233 release_dotlock (all_resources[used_resources].lockhandle);
236 used_resources++;
241 break;
242 default:
243 log_error ("resource type of `%s' not supported\n", url);
244 rc = gpg_error (GPG_ERR_NOT_SUPPORTED);
245 goto leave;
248 /* fixme: check directory permissions and print a warning */
250 leave:
251 if (rc)
252 log_error ("keyblock resource `%s': %s\n", filename, gpg_strerror(rc));
253 else if (secret)
254 any_secret = 1;
255 else
256 any_public = 1;
257 xfree (filename);
258 return rc;
262 KEYDB_HANDLE
263 keydb_new (int secret)
265 KEYDB_HANDLE hd;
266 int i, j;
268 hd = xcalloc (1, sizeof *hd);
269 hd->found = -1;
271 assert (used_resources <= MAX_KEYDB_RESOURCES);
272 for (i=j=0; i < used_resources; i++)
274 if (!all_resources[i].secret != !secret)
275 continue;
276 switch (all_resources[i].type)
278 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
279 break;
280 case KEYDB_RESOURCE_TYPE_KEYBOX:
281 hd->active[j].type = all_resources[i].type;
282 hd->active[j].token = all_resources[i].token;
283 hd->active[j].secret = all_resources[i].secret;
284 hd->active[j].lockhandle = all_resources[i].lockhandle;
285 hd->active[j].u.kr = keybox_new (all_resources[i].token, secret);
286 if (!hd->active[j].u.kr)
288 xfree (hd);
289 return NULL; /* fixme: release all previously allocated handles*/
291 j++;
292 break;
295 hd->used = j;
297 active_handles++;
298 return hd;
301 void
302 keydb_release (KEYDB_HANDLE hd)
304 int i;
306 if (!hd)
307 return;
308 assert (active_handles > 0);
309 active_handles--;
311 unlock_all (hd);
312 for (i=0; i < hd->used; i++)
314 switch (hd->active[i].type)
316 case KEYDB_RESOURCE_TYPE_NONE:
317 break;
318 case KEYDB_RESOURCE_TYPE_KEYBOX:
319 keybox_release (hd->active[i].u.kr);
320 break;
324 xfree (hd);
328 /* Return the name of the current resource. This is function first
329 looks for the last found found, then for the current search
330 position, and last returns the first available resource. The
331 returned string is only valid as long as the handle exists. This
332 function does only return NULL if no handle is specified, in all
333 other error cases an empty string is returned. */
334 const char *
335 keydb_get_resource_name (KEYDB_HANDLE hd)
337 int idx;
338 const char *s = NULL;
340 if (!hd)
341 return NULL;
343 if ( hd->found >= 0 && hd->found < hd->used)
344 idx = hd->found;
345 else if ( hd->current >= 0 && hd->current < hd->used)
346 idx = hd->current;
347 else
348 idx = 0;
350 switch (hd->active[idx].type)
352 case KEYDB_RESOURCE_TYPE_NONE:
353 s = NULL;
354 break;
355 case KEYDB_RESOURCE_TYPE_KEYBOX:
356 s = keybox_get_resource_name (hd->active[idx].u.kr);
357 break;
360 return s? s: "";
363 /* Switch the handle into ephemeral mode and return the orginal value. */
365 keydb_set_ephemeral (KEYDB_HANDLE hd, int yes)
367 int i;
369 if (!hd)
370 return 0;
372 yes = !!yes;
373 if (hd->is_ephemeral != yes)
375 for (i=0; i < hd->used; i++)
377 switch (hd->active[i].type)
379 case KEYDB_RESOURCE_TYPE_NONE:
380 break;
381 case KEYDB_RESOURCE_TYPE_KEYBOX:
382 keybox_set_ephemeral (hd->active[i].u.kr, yes);
383 break;
388 i = hd->is_ephemeral;
389 hd->is_ephemeral = yes;
390 return i;
394 /* If the keyring has not yet been locked, lock it now. This
395 operation is required before any update opeations; it is optionaly
396 for an insert operation. The lock is released with
397 keydb_released. */
398 gpg_error_t
399 keydb_lock (KEYDB_HANDLE hd)
401 if (!hd)
402 return gpg_error (GPG_ERR_INV_HANDLE);
403 if (hd->locked)
404 return 0; /* Already locked. */
405 return lock_all (hd);
410 static int
411 lock_all (KEYDB_HANDLE hd)
413 int i, rc = 0;
415 /* Fixme: This locking scheme may lead to deadlock if the resources
416 are not added in the same order by all processes. We are
417 currently only allowing one resource so it is not a problem. */
418 for (i=0; i < hd->used; i++)
420 switch (hd->active[i].type)
422 case KEYDB_RESOURCE_TYPE_NONE:
423 break;
424 case KEYDB_RESOURCE_TYPE_KEYBOX:
425 if (hd->active[i].lockhandle)
426 rc = make_dotlock (hd->active[i].lockhandle, -1);
427 break;
429 if (rc)
430 break;
433 if (rc)
435 /* revert the already set locks */
436 for (i--; i >= 0; i--)
438 switch (hd->active[i].type)
440 case KEYDB_RESOURCE_TYPE_NONE:
441 break;
442 case KEYDB_RESOURCE_TYPE_KEYBOX:
443 if (hd->active[i].lockhandle)
444 release_dotlock (hd->active[i].lockhandle);
445 break;
449 else
450 hd->locked = 1;
452 /* make_dotlock () does not yet guarantee that errno is set, thus
453 we can't rely on the error reason and will simply use
454 EACCES. */
455 return rc? gpg_error (GPG_ERR_EACCES) : 0;
458 static void
459 unlock_all (KEYDB_HANDLE hd)
461 int i;
463 if (!hd->locked)
464 return;
466 for (i=hd->used-1; i >= 0; i--)
468 switch (hd->active[i].type)
470 case KEYDB_RESOURCE_TYPE_NONE:
471 break;
472 case KEYDB_RESOURCE_TYPE_KEYBOX:
473 if (hd->active[i].lockhandle)
474 release_dotlock (hd->active[i].lockhandle);
475 break;
478 hd->locked = 0;
482 #if 0
484 * Return the last found keybox. Caller must free it.
485 * The returned keyblock has the kbode flag bit 0 set for the node with
486 * the public key used to locate the keyblock or flag bit 1 set for
487 * the user ID node.
490 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
492 int rc = 0;
494 if (!hd)
495 return G10ERR_INV_ARG;
497 if ( hd->found < 0 || hd->found >= hd->used)
498 return -1; /* nothing found */
500 switch (hd->active[hd->found].type) {
501 case KEYDB_RESOURCE_TYPE_NONE:
502 rc = G10ERR_GENERAL; /* oops */
503 break;
504 case KEYDB_RESOURCE_TYPE_KEYBOX:
505 rc = keybox_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
506 break;
509 return rc;
513 * update the current keyblock with KB
516 keydb_update_keyblock (KEYDB_HANDLE hd, KBNODE kb)
518 int rc = 0;
520 if (!hd)
521 return G10ERR_INV_ARG;
523 if ( hd->found < 0 || hd->found >= hd->used)
524 return -1; /* nothing found */
526 if( opt.dry_run )
527 return 0;
529 if (!hd->locked)
530 return gpg_error (GPG_ERR_NOT_LOCKED);
532 switch (hd->active[hd->found].type) {
533 case KEYDB_RESOURCE_TYPE_NONE:
534 rc = G10ERR_GENERAL; /* oops */
535 break;
536 case KEYDB_RESOURCE_TYPE_KEYBOX:
537 rc = keybox_update_keyblock (hd->active[hd->found].u.kr, kb);
538 break;
541 unlock_all (hd);
542 return rc;
547 * Insert a new KB into one of the resources.
550 keydb_insert_keyblock (KEYDB_HANDLE hd, KBNODE kb)
552 int rc = -1;
553 int idx;
555 if (!hd)
556 return G10ERR_INV_ARG;
558 if( opt.dry_run )
559 return 0;
561 if ( hd->found >= 0 && hd->found < hd->used)
562 idx = hd->found;
563 else if ( hd->current >= 0 && hd->current < hd->used)
564 idx = hd->current;
565 else
566 return G10ERR_GENERAL;
568 rc = lock_all (hd);
569 if (rc)
570 return rc;
572 switch (hd->active[idx].type) {
573 case KEYDB_RESOURCE_TYPE_NONE:
574 rc = G10ERR_GENERAL; /* oops */
575 break;
576 case KEYDB_RESOURCE_TYPE_KEYBOX:
577 rc = keybox_insert_keyblock (hd->active[idx].u.kr, kb);
578 break;
581 unlock_all (hd);
582 return rc;
585 #endif /*disabled code*/
590 Return the last found object. Caller must free it. The returned
591 keyblock has the kbode flag bit 0 set for the node with the public
592 key used to locate the keyblock or flag bit 1 set for the user ID
593 node. */
595 keydb_get_cert (KEYDB_HANDLE hd, ksba_cert_t *r_cert)
597 int rc = 0;
599 if (!hd)
600 return gpg_error (GPG_ERR_INV_VALUE);
602 if ( hd->found < 0 || hd->found >= hd->used)
603 return -1; /* nothing found */
605 switch (hd->active[hd->found].type)
607 case KEYDB_RESOURCE_TYPE_NONE:
608 rc = gpg_error (GPG_ERR_GENERAL); /* oops */
609 break;
610 case KEYDB_RESOURCE_TYPE_KEYBOX:
611 rc = keybox_get_cert (hd->active[hd->found].u.kr, r_cert);
612 break;
615 return rc;
618 /* Return a flag of the last found object. WHICH is the flag requested;
619 it should be one of the KEYBOX_FLAG_ values. If the operation is
620 successful, the flag value will be stored at the address given by
621 VALUE. Return 0 on success or an error code. */
622 gpg_error_t
623 keydb_get_flags (KEYDB_HANDLE hd, int which, int idx, unsigned int *value)
625 int err = 0;
627 if (!hd)
628 return gpg_error (GPG_ERR_INV_VALUE);
630 if ( hd->found < 0 || hd->found >= hd->used)
631 return gpg_error (GPG_ERR_NOTHING_FOUND);
633 switch (hd->active[hd->found].type)
635 case KEYDB_RESOURCE_TYPE_NONE:
636 err = gpg_error (GPG_ERR_GENERAL); /* oops */
637 break;
638 case KEYDB_RESOURCE_TYPE_KEYBOX:
639 err = keybox_get_flags (hd->active[hd->found].u.kr, which, idx, value);
640 break;
643 return err;
646 /* Set a flag of the last found object. WHICH is the flag to be set; it
647 should be one of the KEYBOX_FLAG_ values. If the operation is
648 successful, the flag value will be stored in the keybox. Note,
649 that some flag values can't be updated and thus may return an
650 error, some other flag values may be masked out before an update.
651 Returns 0 on success or an error code. */
652 gpg_error_t
653 keydb_set_flags (KEYDB_HANDLE hd, int which, int idx, unsigned int value)
655 int err = 0;
657 if (!hd)
658 return gpg_error (GPG_ERR_INV_VALUE);
660 if ( hd->found < 0 || hd->found >= hd->used)
661 return gpg_error (GPG_ERR_NOTHING_FOUND);
663 if (!hd->locked)
664 return gpg_error (GPG_ERR_NOT_LOCKED);
666 switch (hd->active[hd->found].type)
668 case KEYDB_RESOURCE_TYPE_NONE:
669 err = gpg_error (GPG_ERR_GENERAL); /* oops */
670 break;
671 case KEYDB_RESOURCE_TYPE_KEYBOX:
672 err = keybox_set_flags (hd->active[hd->found].u.kr, which, idx, value);
673 break;
676 return err;
680 * Insert a new Certificate into one of the resources.
683 keydb_insert_cert (KEYDB_HANDLE hd, ksba_cert_t cert)
685 int rc = -1;
686 int idx;
687 unsigned char digest[20];
689 if (!hd)
690 return gpg_error (GPG_ERR_INV_VALUE);
692 if (opt.dry_run)
693 return 0;
695 if ( hd->found >= 0 && hd->found < hd->used)
696 idx = hd->found;
697 else if ( hd->current >= 0 && hd->current < hd->used)
698 idx = hd->current;
699 else
700 return gpg_error (GPG_ERR_GENERAL);
702 if (!hd->locked)
703 return gpg_error (GPG_ERR_NOT_LOCKED);
705 gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/
707 switch (hd->active[idx].type)
709 case KEYDB_RESOURCE_TYPE_NONE:
710 rc = gpg_error (GPG_ERR_GENERAL);
711 break;
712 case KEYDB_RESOURCE_TYPE_KEYBOX:
713 rc = keybox_insert_cert (hd->active[idx].u.kr, cert, digest);
714 break;
717 unlock_all (hd);
718 return rc;
723 /* Update the current keyblock with KB. */
725 keydb_update_cert (KEYDB_HANDLE hd, ksba_cert_t cert)
727 int rc = 0;
728 unsigned char digest[20];
730 if (!hd)
731 return gpg_error (GPG_ERR_INV_VALUE);
733 if ( hd->found < 0 || hd->found >= hd->used)
734 return -1; /* nothing found */
736 if (opt.dry_run)
737 return 0;
739 rc = lock_all (hd);
740 if (rc)
741 return rc;
743 gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, digest, NULL); /* kludge*/
745 switch (hd->active[hd->found].type)
747 case KEYDB_RESOURCE_TYPE_NONE:
748 rc = gpg_error (GPG_ERR_GENERAL); /* oops */
749 break;
750 case KEYDB_RESOURCE_TYPE_KEYBOX:
751 rc = keybox_update_cert (hd->active[hd->found].u.kr, cert, digest);
752 break;
755 unlock_all (hd);
756 return rc;
761 * The current keyblock or cert will be deleted.
764 keydb_delete (KEYDB_HANDLE hd, int unlock)
766 int rc = -1;
768 if (!hd)
769 return gpg_error (GPG_ERR_INV_VALUE);
771 if ( hd->found < 0 || hd->found >= hd->used)
772 return -1; /* nothing found */
774 if( opt.dry_run )
775 return 0;
777 if (!hd->locked)
778 return gpg_error (GPG_ERR_NOT_LOCKED);
780 switch (hd->active[hd->found].type)
782 case KEYDB_RESOURCE_TYPE_NONE:
783 rc = gpg_error (GPG_ERR_GENERAL);
784 break;
785 case KEYDB_RESOURCE_TYPE_KEYBOX:
786 rc = keybox_delete (hd->active[hd->found].u.kr);
787 break;
790 if (unlock)
791 unlock_all (hd);
792 return rc;
798 * Locate the default writable key resource, so that the next
799 * operation (which is only relevant for inserts) will be done on this
800 * resource.
803 keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
805 int rc;
807 if (!hd)
808 return gpg_error (GPG_ERR_INV_VALUE);
810 rc = keydb_search_reset (hd); /* this does reset hd->current */
811 if (rc)
812 return rc;
814 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
816 switch (hd->active[hd->current].type)
818 case KEYDB_RESOURCE_TYPE_NONE:
819 BUG();
820 break;
821 case KEYDB_RESOURCE_TYPE_KEYBOX:
822 if (keybox_is_writable (hd->active[hd->current].token))
823 return 0; /* found (hd->current is set to it) */
824 break;
828 return -1;
832 * Rebuild the caches of all key resources.
834 void
835 keydb_rebuild_caches (void)
837 int i;
839 for (i=0; i < used_resources; i++)
841 if (all_resources[i].secret)
842 continue;
843 switch (all_resources[i].type)
845 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
846 break;
847 case KEYDB_RESOURCE_TYPE_KEYBOX:
848 /* rc = keybox_rebuild_cache (all_resources[i].token); */
849 /* if (rc) */
850 /* log_error (_("failed to rebuild keybox cache: %s\n"), */
851 /* g10_errstr (rc)); */
852 break;
860 * Start the next search on this handle right at the beginning
862 int
863 keydb_search_reset (KEYDB_HANDLE hd)
865 int i, rc = 0;
867 if (!hd)
868 return gpg_error (GPG_ERR_INV_VALUE);
870 hd->current = 0;
871 hd->found = -1;
872 /* and reset all resources */
873 for (i=0; !rc && i < hd->used; i++)
875 switch (hd->active[i].type)
877 case KEYDB_RESOURCE_TYPE_NONE:
878 break;
879 case KEYDB_RESOURCE_TYPE_KEYBOX:
880 rc = keybox_search_reset (hd->active[i].u.kr);
881 break;
884 return rc; /* fixme: we need to map error codes or share them with
885 all modules*/
889 * Search through all keydb resources, starting at the current position,
890 * for a keyblock which contains one of the keys described in the DESC array.
892 int
893 keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc)
895 int rc = -1;
897 if (!hd)
898 return gpg_error (GPG_ERR_INV_VALUE);
900 while (rc == -1 && hd->current >= 0 && hd->current < hd->used)
902 switch (hd->active[hd->current].type)
904 case KEYDB_RESOURCE_TYPE_NONE:
905 BUG(); /* we should never see it here */
906 break;
907 case KEYDB_RESOURCE_TYPE_KEYBOX:
908 rc = keybox_search (hd->active[hd->current].u.kr, desc, ndesc);
909 break;
911 if (rc == -1) /* EOF -> switch to next resource */
912 hd->current++;
913 else if (!rc)
914 hd->found = hd->current;
917 return rc;
922 keydb_search_first (KEYDB_HANDLE hd)
924 KEYDB_SEARCH_DESC desc;
926 memset (&desc, 0, sizeof desc);
927 desc.mode = KEYDB_SEARCH_MODE_FIRST;
928 return keydb_search (hd, &desc, 1);
932 keydb_search_next (KEYDB_HANDLE hd)
934 KEYDB_SEARCH_DESC desc;
936 memset (&desc, 0, sizeof desc);
937 desc.mode = KEYDB_SEARCH_MODE_NEXT;
938 return keydb_search (hd, &desc, 1);
942 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
944 KEYDB_SEARCH_DESC desc;
946 memset (&desc, 0, sizeof desc);
947 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
948 /* desc.u.kid[0] = kid[0]; */
949 /* desc.u.kid[1] = kid[1]; */
950 return keydb_search (hd, &desc, 1);
954 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
956 KEYDB_SEARCH_DESC desc;
958 memset (&desc, 0, sizeof desc);
959 desc.mode = KEYDB_SEARCH_MODE_FPR;
960 memcpy (desc.u.fpr, fpr, 20);
961 return keydb_search (hd, &desc, 1);
965 keydb_search_issuer (KEYDB_HANDLE hd, const char *issuer)
967 KEYDB_SEARCH_DESC desc;
968 int rc;
970 memset (&desc, 0, sizeof desc);
971 desc.mode = KEYDB_SEARCH_MODE_ISSUER;
972 desc.u.name = issuer;
973 rc = keydb_search (hd, &desc, 1);
974 return rc;
978 keydb_search_issuer_sn (KEYDB_HANDLE hd,
979 const char *issuer, ksba_const_sexp_t serial)
981 KEYDB_SEARCH_DESC desc;
982 int rc;
983 const unsigned char *s;
985 memset (&desc, 0, sizeof desc);
986 desc.mode = KEYDB_SEARCH_MODE_ISSUER_SN;
987 s = serial;
988 if (*s !='(')
989 return gpg_error (GPG_ERR_INV_VALUE);
990 s++;
991 for (desc.snlen = 0; digitp (s); s++)
992 desc.snlen = 10*desc.snlen + atoi_1 (s);
993 if (*s !=':')
994 return gpg_error (GPG_ERR_INV_VALUE);
995 desc.sn = s+1;
996 desc.u.name = issuer;
997 rc = keydb_search (hd, &desc, 1);
998 return rc;
1002 keydb_search_subject (KEYDB_HANDLE hd, const char *name)
1004 KEYDB_SEARCH_DESC desc;
1005 int rc;
1007 memset (&desc, 0, sizeof desc);
1008 desc.mode = KEYDB_SEARCH_MODE_SUBJECT;
1009 desc.u.name = name;
1010 rc = keydb_search (hd, &desc, 1);
1011 return rc;
1015 static int
1016 classify_user_id (const char *name,
1017 KEYDB_SEARCH_DESC *desc,
1018 int *force_exact )
1020 const char *s;
1021 int hexprefix = 0;
1022 int hexlength;
1023 int mode = 0;
1025 /* clear the structure so that the mode field is set to zero unless
1026 * we set it to the correct value right at the end of this function */
1027 memset (desc, 0, sizeof *desc);
1028 *force_exact = 0;
1029 /* Skip leading spaces. Fixme: what about trailing white space? */
1030 for(s = name; *s && spacep (s); s++ )
1033 switch (*s)
1035 case 0: /* empty string is an error */
1036 return 0;
1038 case '.': /* an email address, compare from end */
1039 mode = KEYDB_SEARCH_MODE_MAILEND;
1040 s++;
1041 desc->u.name = s;
1042 break;
1044 case '<': /* an email address */
1045 mode = KEYDB_SEARCH_MODE_MAIL;
1046 s++;
1047 desc->u.name = s;
1048 break;
1050 case '@': /* part of an email address */
1051 mode = KEYDB_SEARCH_MODE_MAILSUB;
1052 s++;
1053 desc->u.name = s;
1054 break;
1056 case '=': /* exact compare */
1057 mode = KEYDB_SEARCH_MODE_EXACT;
1058 s++;
1059 desc->u.name = s;
1060 break;
1062 case '*': /* case insensitive substring search */
1063 mode = KEYDB_SEARCH_MODE_SUBSTR;
1064 s++;
1065 desc->u.name = s;
1066 break;
1068 case '+': /* compare individual words */
1069 mode = KEYDB_SEARCH_MODE_WORDS;
1070 s++;
1071 desc->u.name = s;
1072 break;
1074 case '/': /* subject's DN */
1075 s++;
1076 if (!*s || spacep (s))
1077 return 0; /* no DN or prefixed with a space */
1078 desc->u.name = s;
1079 mode = KEYDB_SEARCH_MODE_SUBJECT;
1080 break;
1082 case '#':
1084 const char *si;
1086 s++;
1087 if ( *s == '/')
1088 { /* "#/" indicates an issuer's DN */
1089 s++;
1090 if (!*s || spacep (s))
1091 return 0; /* no DN or prefixed with a space */
1092 desc->u.name = s;
1093 mode = KEYDB_SEARCH_MODE_ISSUER;
1095 else
1096 { /* serialnumber + optional issuer ID */
1097 for (si=s; *si && *si != '/'; si++)
1099 if (!strchr("01234567890abcdefABCDEF", *si))
1100 return 0; /* invalid digit in serial number*/
1102 desc->sn = (const unsigned char*)s;
1103 desc->snlen = -1;
1104 if (!*si)
1105 mode = KEYDB_SEARCH_MODE_SN;
1106 else
1108 s = si+1;
1109 if (!*s || spacep (s))
1110 return 0; /* no DN or prefixed with a space */
1111 desc->u.name = s;
1112 mode = KEYDB_SEARCH_MODE_ISSUER_SN;
1116 break;
1118 case ':': /*Unified fingerprint */
1120 const char *se, *si;
1121 int i;
1123 se = strchr (++s,':');
1124 if (!se)
1125 return 0;
1126 for (i=0,si=s; si < se; si++, i++ )
1128 if (!strchr("01234567890abcdefABCDEF", *si))
1129 return 0; /* invalid digit */
1131 if (i != 32 && i != 40)
1132 return 0; /* invalid length of fpr*/
1133 for (i=0,si=s; si < se; i++, si +=2)
1134 desc->u.fpr[i] = hextobyte(si);
1135 for (; i < 20; i++)
1136 desc->u.fpr[i]= 0;
1137 s = se + 1;
1138 mode = KEYDB_SEARCH_MODE_FPR;
1140 break;
1142 case '&': /* Keygrip*/
1144 if (hex2bin (s+1, desc->u.grip, 20) < 0)
1145 return 0; /* Invalid. */
1146 mode = KEYDB_SEARCH_MODE_KEYGRIP;
1148 break;
1150 default:
1151 if (s[0] == '0' && s[1] == 'x')
1153 hexprefix = 1;
1154 s += 2;
1157 hexlength = strspn(s, "0123456789abcdefABCDEF");
1158 if (hexlength >= 8 && s[hexlength] =='!')
1160 *force_exact = 1;
1161 hexlength++; /* just for the following check */
1164 /* check if a hexadecimal number is terminated by EOS or blank */
1165 if (hexlength && s[hexlength] && !spacep (s+hexlength))
1167 if (hexprefix) /* a "0x" prefix without correct */
1168 return 0; /* termination is an error */
1169 /* The first chars looked like a hex number, but really is
1170 not */
1171 hexlength = 0;
1174 if (*force_exact)
1175 hexlength--; /* remove the bang */
1177 if (hexlength == 8
1178 || (!hexprefix && hexlength == 9 && *s == '0'))
1179 { /* short keyid */
1180 unsigned long kid;
1181 if (hexlength == 9)
1182 s++;
1183 kid = strtoul( s, NULL, 16 );
1184 desc->u.kid[4] = kid >> 24;
1185 desc->u.kid[5] = kid >> 16;
1186 desc->u.kid[6] = kid >> 8;
1187 desc->u.kid[7] = kid;
1188 mode = KEYDB_SEARCH_MODE_SHORT_KID;
1190 else if (hexlength == 16
1191 || (!hexprefix && hexlength == 17 && *s == '0'))
1192 { /* complete keyid */
1193 unsigned long kid0, kid1;
1194 char buf[9];
1195 if (hexlength == 17)
1196 s++;
1197 mem2str(buf, s, 9 );
1198 kid0 = strtoul (buf, NULL, 16);
1199 kid1 = strtoul (s+8, NULL, 16);
1200 desc->u.kid[0] = kid0 >> 24;
1201 desc->u.kid[1] = kid0 >> 16;
1202 desc->u.kid[2] = kid0 >> 8;
1203 desc->u.kid[3] = kid0;
1204 desc->u.kid[4] = kid1 >> 24;
1205 desc->u.kid[5] = kid1 >> 16;
1206 desc->u.kid[6] = kid1 >> 8;
1207 desc->u.kid[7] = kid1;
1208 mode = KEYDB_SEARCH_MODE_LONG_KID;
1210 else if (hexlength == 32
1211 || (!hexprefix && hexlength == 33 && *s == '0'))
1212 { /* md5 fingerprint */
1213 int i;
1214 if (hexlength == 33)
1215 s++;
1216 memset(desc->u.fpr+16, 0, 4);
1217 for (i=0; i < 16; i++, s+=2)
1219 int c = hextobyte(s);
1220 if (c == -1)
1221 return 0;
1222 desc->u.fpr[i] = c;
1224 mode = KEYDB_SEARCH_MODE_FPR16;
1226 else if (hexlength == 40
1227 || (!hexprefix && hexlength == 41 && *s == '0'))
1228 { /* sha1/rmd160 fingerprint */
1229 int i;
1230 if (hexlength == 41)
1231 s++;
1232 for (i=0; i < 20; i++, s+=2)
1234 int c = hextobyte(s);
1235 if (c == -1)
1236 return 0;
1237 desc->u.fpr[i] = c;
1239 mode = KEYDB_SEARCH_MODE_FPR20;
1241 else if (!hexprefix)
1243 /* The fingerprint in an X.509 listing is often delimited by
1244 colons, so we try to single this case out. */
1245 mode = 0;
1246 hexlength = strspn (s, ":0123456789abcdefABCDEF");
1247 if (hexlength == 59 && (!s[hexlength] || spacep (s+hexlength)))
1249 int i;
1251 for (i=0; i < 20; i++, s += 3)
1253 int c = hextobyte(s);
1254 if (c == -1 || (i < 19 && s[2] != ':'))
1255 break;
1256 desc->u.fpr[i] = c;
1258 if (i == 20)
1259 mode = KEYDB_SEARCH_MODE_FPR20;
1261 if (!mode) /* default is substring search */
1263 *force_exact = 0;
1264 desc->u.name = s;
1265 mode = KEYDB_SEARCH_MODE_SUBSTR;
1268 else
1269 { /* hex number with a prefix but a wrong length */
1270 return 0;
1274 desc->mode = mode;
1275 return mode;
1280 keydb_classify_name (const char *name, KEYDB_SEARCH_DESC *desc)
1282 int dummy;
1283 KEYDB_SEARCH_DESC dummy_desc;
1285 if (!desc)
1286 desc = &dummy_desc;
1288 if (!classify_user_id (name, desc, &dummy))
1289 return gpg_error (GPG_ERR_INV_NAME);
1290 return 0;
1294 /* Store the certificate in the key DB but make sure that it does not
1295 already exists. We do this simply by comparing the fingerprint.
1296 If EXISTED is not NULL it will be set to true if the certificate
1297 was already in the DB. */
1299 keydb_store_cert (ksba_cert_t cert, int ephemeral, int *existed)
1301 KEYDB_HANDLE kh;
1302 int rc;
1303 unsigned char fpr[20];
1305 if (existed)
1306 *existed = 0;
1308 if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL))
1310 log_error (_("failed to get the fingerprint\n"));
1311 return gpg_error (GPG_ERR_GENERAL);
1314 kh = keydb_new (0);
1315 if (!kh)
1317 log_error (_("failed to allocate keyDB handle\n"));
1318 return gpg_error (GPG_ERR_ENOMEM);;
1321 if (ephemeral)
1322 keydb_set_ephemeral (kh, 1);
1324 rc = lock_all (kh);
1325 if (rc)
1326 return rc;
1328 rc = keydb_search_fpr (kh, fpr);
1329 if (rc != -1)
1331 keydb_release (kh);
1332 if (!rc)
1334 if (existed)
1335 *existed = 1;
1336 return 0; /* okay */
1338 log_error (_("problem looking for existing certificate: %s\n"),
1339 gpg_strerror (rc));
1340 return rc;
1343 rc = keydb_locate_writable (kh, 0);
1344 if (rc)
1346 log_error (_("error finding writable keyDB: %s\n"), gpg_strerror (rc));
1347 keydb_release (kh);
1348 return rc;
1351 rc = keydb_insert_cert (kh, cert);
1352 if (rc)
1354 log_error (_("error storing certificate: %s\n"), gpg_strerror (rc));
1355 keydb_release (kh);
1356 return rc;
1358 keydb_release (kh);
1359 return 0;
1363 /* This is basically keydb_set_flags but it implements a complete
1364 transaction by locating the certificate in the DB and updating the
1365 flags. */
1366 gpg_error_t
1367 keydb_set_cert_flags (ksba_cert_t cert, int ephemeral,
1368 int which, int idx,
1369 unsigned int mask, unsigned int value)
1371 KEYDB_HANDLE kh;
1372 gpg_error_t err;
1373 unsigned char fpr[20];
1374 unsigned int old_value;
1376 if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL))
1378 log_error (_("failed to get the fingerprint\n"));
1379 return gpg_error (GPG_ERR_GENERAL);
1382 kh = keydb_new (0);
1383 if (!kh)
1385 log_error (_("failed to allocate keyDB handle\n"));
1386 return gpg_error (GPG_ERR_ENOMEM);;
1389 if (ephemeral)
1390 keydb_set_ephemeral (kh, 1);
1392 err = keydb_lock (kh);
1393 if (err)
1395 log_error (_("error locking keybox: %s\n"), gpg_strerror (err));
1396 keydb_release (kh);
1397 return err;
1400 err = keydb_search_fpr (kh, fpr);
1401 if (err)
1403 if (err == -1)
1404 err = gpg_error (GPG_ERR_NOT_FOUND);
1405 else
1406 log_error (_("problem re-searching certificate: %s\n"),
1407 gpg_strerror (err));
1408 keydb_release (kh);
1409 return err;
1412 err = keydb_get_flags (kh, which, idx, &old_value);
1413 if (err)
1415 log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
1416 keydb_release (kh);
1417 return err;
1420 value = ((old_value & ~mask) | (value & mask));
1422 if (value != old_value)
1424 err = keydb_set_flags (kh, which, idx, value);
1425 if (err)
1427 log_error (_("error storing flags: %s\n"), gpg_strerror (err));
1428 keydb_release (kh);
1429 return err;
1433 keydb_release (kh);
1434 return 0;
1438 /* Reset all the certificate flags we have stored with the certificates
1439 for performance reasons. */
1440 void
1441 keydb_clear_some_cert_flags (ctrl_t ctrl, strlist_t names)
1443 gpg_error_t err;
1444 KEYDB_HANDLE hd = NULL;
1445 KEYDB_SEARCH_DESC *desc = NULL;
1446 int ndesc;
1447 strlist_t sl;
1448 int rc=0;
1449 unsigned int old_value, value;
1451 hd = keydb_new (0);
1452 if (!hd)
1454 log_error ("keydb_new failed\n");
1455 goto leave;
1458 if (!names)
1459 ndesc = 1;
1460 else
1462 for (sl=names, ndesc=0; sl; sl = sl->next, ndesc++)
1466 desc = xtrycalloc (ndesc, sizeof *desc);
1467 if (!ndesc)
1469 log_error ("allocating memory failed: %s\n",
1470 gpg_strerror (out_of_core ()));
1471 goto leave;
1474 if (!names)
1475 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1476 else
1478 for (ndesc=0, sl=names; sl; sl = sl->next)
1480 rc = keydb_classify_name (sl->d, desc+ndesc);
1481 if (rc)
1483 log_error ("key `%s' not found: %s\n",
1484 sl->d, gpg_strerror (rc));
1485 rc = 0;
1487 else
1488 ndesc++;
1492 err = keydb_lock (hd);
1493 if (err)
1495 log_error (_("error locking keybox: %s\n"), gpg_strerror (err));
1496 goto leave;
1499 while (!(rc = keydb_search (hd, desc, ndesc)))
1501 if (!names)
1502 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1504 err = keydb_get_flags (hd, KEYBOX_FLAG_VALIDITY, 0, &old_value);
1505 if (err)
1507 log_error (_("error getting stored flags: %s\n"),
1508 gpg_strerror (err));
1509 goto leave;
1512 value = (old_value & ~VALIDITY_REVOKED);
1513 if (value != old_value)
1515 err = keydb_set_flags (hd, KEYBOX_FLAG_VALIDITY, 0, value);
1516 if (err)
1518 log_error (_("error storing flags: %s\n"), gpg_strerror (err));
1519 goto leave;
1523 if (rc && rc != -1)
1524 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
1526 leave:
1527 xfree (desc);
1528 keydb_release (hd);