agent/
[gnupg.git] / sm / keydb.c
bloba1f0e9c183ec08322c249c4de6a925621df4b517
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_t 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 operation; it is optional
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 (void)reserved;
809 if (!hd)
810 return gpg_error (GPG_ERR_INV_VALUE);
812 rc = keydb_search_reset (hd); /* this does reset hd->current */
813 if (rc)
814 return rc;
816 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
818 switch (hd->active[hd->current].type)
820 case KEYDB_RESOURCE_TYPE_NONE:
821 BUG();
822 break;
823 case KEYDB_RESOURCE_TYPE_KEYBOX:
824 if (keybox_is_writable (hd->active[hd->current].token))
825 return 0; /* found (hd->current is set to it) */
826 break;
830 return -1;
834 * Rebuild the caches of all key resources.
836 void
837 keydb_rebuild_caches (void)
839 int i;
841 for (i=0; i < used_resources; i++)
843 if (all_resources[i].secret)
844 continue;
845 switch (all_resources[i].type)
847 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
848 break;
849 case KEYDB_RESOURCE_TYPE_KEYBOX:
850 /* rc = keybox_rebuild_cache (all_resources[i].token); */
851 /* if (rc) */
852 /* log_error (_("failed to rebuild keybox cache: %s\n"), */
853 /* g10_errstr (rc)); */
854 break;
862 * Start the next search on this handle right at the beginning
864 int
865 keydb_search_reset (KEYDB_HANDLE hd)
867 int i, rc = 0;
869 if (!hd)
870 return gpg_error (GPG_ERR_INV_VALUE);
872 hd->current = 0;
873 hd->found = -1;
874 /* and reset all resources */
875 for (i=0; !rc && i < hd->used; i++)
877 switch (hd->active[i].type)
879 case KEYDB_RESOURCE_TYPE_NONE:
880 break;
881 case KEYDB_RESOURCE_TYPE_KEYBOX:
882 rc = keybox_search_reset (hd->active[i].u.kr);
883 break;
886 return rc; /* fixme: we need to map error codes or share them with
887 all modules*/
891 * Search through all keydb resources, starting at the current position,
892 * for a keyblock which contains one of the keys described in the DESC array.
894 int
895 keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc)
897 int rc = -1;
899 if (!hd)
900 return gpg_error (GPG_ERR_INV_VALUE);
902 while (rc == -1 && hd->current >= 0 && hd->current < hd->used)
904 switch (hd->active[hd->current].type)
906 case KEYDB_RESOURCE_TYPE_NONE:
907 BUG(); /* we should never see it here */
908 break;
909 case KEYDB_RESOURCE_TYPE_KEYBOX:
910 rc = keybox_search (hd->active[hd->current].u.kr, desc, ndesc);
911 break;
913 if (rc == -1) /* EOF -> switch to next resource */
914 hd->current++;
915 else if (!rc)
916 hd->found = hd->current;
919 return rc;
924 keydb_search_first (KEYDB_HANDLE hd)
926 KEYDB_SEARCH_DESC desc;
928 memset (&desc, 0, sizeof desc);
929 desc.mode = KEYDB_SEARCH_MODE_FIRST;
930 return keydb_search (hd, &desc, 1);
934 keydb_search_next (KEYDB_HANDLE hd)
936 KEYDB_SEARCH_DESC desc;
938 memset (&desc, 0, sizeof desc);
939 desc.mode = KEYDB_SEARCH_MODE_NEXT;
940 return keydb_search (hd, &desc, 1);
944 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
946 KEYDB_SEARCH_DESC desc;
948 (void)kid;
950 memset (&desc, 0, sizeof desc);
951 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
952 /* desc.u.kid[0] = kid[0]; */
953 /* desc.u.kid[1] = kid[1]; */
954 return keydb_search (hd, &desc, 1);
958 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
960 KEYDB_SEARCH_DESC desc;
962 memset (&desc, 0, sizeof desc);
963 desc.mode = KEYDB_SEARCH_MODE_FPR;
964 memcpy (desc.u.fpr, fpr, 20);
965 return keydb_search (hd, &desc, 1);
969 keydb_search_issuer (KEYDB_HANDLE hd, const char *issuer)
971 KEYDB_SEARCH_DESC desc;
972 int rc;
974 memset (&desc, 0, sizeof desc);
975 desc.mode = KEYDB_SEARCH_MODE_ISSUER;
976 desc.u.name = issuer;
977 rc = keydb_search (hd, &desc, 1);
978 return rc;
982 keydb_search_issuer_sn (KEYDB_HANDLE hd,
983 const char *issuer, ksba_const_sexp_t serial)
985 KEYDB_SEARCH_DESC desc;
986 int rc;
987 const unsigned char *s;
989 memset (&desc, 0, sizeof desc);
990 desc.mode = KEYDB_SEARCH_MODE_ISSUER_SN;
991 s = serial;
992 if (*s !='(')
993 return gpg_error (GPG_ERR_INV_VALUE);
994 s++;
995 for (desc.snlen = 0; digitp (s); s++)
996 desc.snlen = 10*desc.snlen + atoi_1 (s);
997 if (*s !=':')
998 return gpg_error (GPG_ERR_INV_VALUE);
999 desc.sn = s+1;
1000 desc.u.name = issuer;
1001 rc = keydb_search (hd, &desc, 1);
1002 return rc;
1006 keydb_search_subject (KEYDB_HANDLE hd, const char *name)
1008 KEYDB_SEARCH_DESC desc;
1009 int rc;
1011 memset (&desc, 0, sizeof desc);
1012 desc.mode = KEYDB_SEARCH_MODE_SUBJECT;
1013 desc.u.name = name;
1014 rc = keydb_search (hd, &desc, 1);
1015 return rc;
1019 static int
1020 classify_user_id (const char *name,
1021 KEYDB_SEARCH_DESC *desc,
1022 int *force_exact )
1024 const char *s;
1025 int hexprefix = 0;
1026 int hexlength;
1027 int mode = 0;
1029 /* clear the structure so that the mode field is set to zero unless
1030 * we set it to the correct value right at the end of this function */
1031 memset (desc, 0, sizeof *desc);
1032 *force_exact = 0;
1033 /* Skip leading spaces. Fixme: what about trailing white space? */
1034 for(s = name; *s && spacep (s); s++ )
1037 switch (*s)
1039 case 0: /* empty string is an error */
1040 return 0;
1042 case '.': /* an email address, compare from end */
1043 mode = KEYDB_SEARCH_MODE_MAILEND;
1044 s++;
1045 desc->u.name = s;
1046 break;
1048 case '<': /* an email address */
1049 mode = KEYDB_SEARCH_MODE_MAIL;
1050 s++;
1051 desc->u.name = s;
1052 break;
1054 case '@': /* part of an email address */
1055 mode = KEYDB_SEARCH_MODE_MAILSUB;
1056 s++;
1057 desc->u.name = s;
1058 break;
1060 case '=': /* exact compare */
1061 mode = KEYDB_SEARCH_MODE_EXACT;
1062 s++;
1063 desc->u.name = s;
1064 break;
1066 case '*': /* case insensitive substring search */
1067 mode = KEYDB_SEARCH_MODE_SUBSTR;
1068 s++;
1069 desc->u.name = s;
1070 break;
1072 case '+': /* compare individual words */
1073 mode = KEYDB_SEARCH_MODE_WORDS;
1074 s++;
1075 desc->u.name = s;
1076 break;
1078 case '/': /* subject's DN */
1079 s++;
1080 if (!*s || spacep (s))
1081 return 0; /* no DN or prefixed with a space */
1082 desc->u.name = s;
1083 mode = KEYDB_SEARCH_MODE_SUBJECT;
1084 break;
1086 case '#':
1088 const char *si;
1090 s++;
1091 if ( *s == '/')
1092 { /* "#/" indicates an issuer's DN */
1093 s++;
1094 if (!*s || spacep (s))
1095 return 0; /* no DN or prefixed with a space */
1096 desc->u.name = s;
1097 mode = KEYDB_SEARCH_MODE_ISSUER;
1099 else
1100 { /* serialnumber + optional issuer ID */
1101 for (si=s; *si && *si != '/'; si++)
1103 if (!strchr("01234567890abcdefABCDEF", *si))
1104 return 0; /* invalid digit in serial number*/
1106 desc->sn = (const unsigned char*)s;
1107 desc->snlen = -1;
1108 if (!*si)
1109 mode = KEYDB_SEARCH_MODE_SN;
1110 else
1112 s = si+1;
1113 if (!*s || spacep (s))
1114 return 0; /* no DN or prefixed with a space */
1115 desc->u.name = s;
1116 mode = KEYDB_SEARCH_MODE_ISSUER_SN;
1120 break;
1122 case ':': /*Unified fingerprint */
1124 const char *se, *si;
1125 int i;
1127 se = strchr (++s,':');
1128 if (!se)
1129 return 0;
1130 for (i=0,si=s; si < se; si++, i++ )
1132 if (!strchr("01234567890abcdefABCDEF", *si))
1133 return 0; /* invalid digit */
1135 if (i != 32 && i != 40)
1136 return 0; /* invalid length of fpr*/
1137 for (i=0,si=s; si < se; i++, si +=2)
1138 desc->u.fpr[i] = hextobyte(si);
1139 for (; i < 20; i++)
1140 desc->u.fpr[i]= 0;
1141 s = se + 1;
1142 mode = KEYDB_SEARCH_MODE_FPR;
1144 break;
1146 case '&': /* Keygrip*/
1148 if (hex2bin (s+1, desc->u.grip, 20) < 0)
1149 return 0; /* Invalid. */
1150 mode = KEYDB_SEARCH_MODE_KEYGRIP;
1152 break;
1154 default:
1155 if (s[0] == '0' && s[1] == 'x')
1157 hexprefix = 1;
1158 s += 2;
1161 hexlength = strspn(s, "0123456789abcdefABCDEF");
1162 if (hexlength >= 8 && s[hexlength] =='!')
1164 *force_exact = 1;
1165 hexlength++; /* just for the following check */
1168 /* check if a hexadecimal number is terminated by EOS or blank */
1169 if (hexlength && s[hexlength] && !spacep (s+hexlength))
1171 if (hexprefix) /* a "0x" prefix without correct */
1172 return 0; /* termination is an error */
1173 /* The first chars looked like a hex number, but really is
1174 not */
1175 hexlength = 0;
1178 if (*force_exact)
1179 hexlength--; /* remove the bang */
1181 if (hexlength == 8
1182 || (!hexprefix && hexlength == 9 && *s == '0'))
1183 { /* short keyid */
1184 unsigned long kid;
1185 if (hexlength == 9)
1186 s++;
1187 kid = strtoul( s, NULL, 16 );
1188 desc->u.kid[4] = kid >> 24;
1189 desc->u.kid[5] = kid >> 16;
1190 desc->u.kid[6] = kid >> 8;
1191 desc->u.kid[7] = kid;
1192 mode = KEYDB_SEARCH_MODE_SHORT_KID;
1194 else if (hexlength == 16
1195 || (!hexprefix && hexlength == 17 && *s == '0'))
1196 { /* complete keyid */
1197 unsigned long kid0, kid1;
1198 char buf[9];
1199 if (hexlength == 17)
1200 s++;
1201 mem2str(buf, s, 9 );
1202 kid0 = strtoul (buf, NULL, 16);
1203 kid1 = strtoul (s+8, NULL, 16);
1204 desc->u.kid[0] = kid0 >> 24;
1205 desc->u.kid[1] = kid0 >> 16;
1206 desc->u.kid[2] = kid0 >> 8;
1207 desc->u.kid[3] = kid0;
1208 desc->u.kid[4] = kid1 >> 24;
1209 desc->u.kid[5] = kid1 >> 16;
1210 desc->u.kid[6] = kid1 >> 8;
1211 desc->u.kid[7] = kid1;
1212 mode = KEYDB_SEARCH_MODE_LONG_KID;
1214 else if (hexlength == 32
1215 || (!hexprefix && hexlength == 33 && *s == '0'))
1216 { /* md5 fingerprint */
1217 int i;
1218 if (hexlength == 33)
1219 s++;
1220 memset(desc->u.fpr+16, 0, 4);
1221 for (i=0; i < 16; i++, s+=2)
1223 int c = hextobyte(s);
1224 if (c == -1)
1225 return 0;
1226 desc->u.fpr[i] = c;
1228 mode = KEYDB_SEARCH_MODE_FPR16;
1230 else if (hexlength == 40
1231 || (!hexprefix && hexlength == 41 && *s == '0'))
1232 { /* sha1/rmd160 fingerprint */
1233 int i;
1234 if (hexlength == 41)
1235 s++;
1236 for (i=0; i < 20; i++, s+=2)
1238 int c = hextobyte(s);
1239 if (c == -1)
1240 return 0;
1241 desc->u.fpr[i] = c;
1243 mode = KEYDB_SEARCH_MODE_FPR20;
1245 else if (!hexprefix)
1247 /* The fingerprint in an X.509 listing is often delimited by
1248 colons, so we try to single this case out. */
1249 mode = 0;
1250 hexlength = strspn (s, ":0123456789abcdefABCDEF");
1251 if (hexlength == 59 && (!s[hexlength] || spacep (s+hexlength)))
1253 int i;
1255 for (i=0; i < 20; i++, s += 3)
1257 int c = hextobyte(s);
1258 if (c == -1 || (i < 19 && s[2] != ':'))
1259 break;
1260 desc->u.fpr[i] = c;
1262 if (i == 20)
1263 mode = KEYDB_SEARCH_MODE_FPR20;
1265 if (!mode) /* default is substring search */
1267 *force_exact = 0;
1268 desc->u.name = s;
1269 mode = KEYDB_SEARCH_MODE_SUBSTR;
1272 else
1273 { /* hex number with a prefix but a wrong length */
1274 return 0;
1278 desc->mode = mode;
1279 return mode;
1284 keydb_classify_name (const char *name, KEYDB_SEARCH_DESC *desc)
1286 int dummy;
1287 KEYDB_SEARCH_DESC dummy_desc;
1289 if (!desc)
1290 desc = &dummy_desc;
1292 if (!classify_user_id (name, desc, &dummy))
1293 return gpg_error (GPG_ERR_INV_NAME);
1294 return 0;
1298 /* Store the certificate in the key DB but make sure that it does not
1299 already exists. We do this simply by comparing the fingerprint.
1300 If EXISTED is not NULL it will be set to true if the certificate
1301 was already in the DB. */
1303 keydb_store_cert (ksba_cert_t cert, int ephemeral, int *existed)
1305 KEYDB_HANDLE kh;
1306 int rc;
1307 unsigned char fpr[20];
1309 if (existed)
1310 *existed = 0;
1312 if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL))
1314 log_error (_("failed to get the fingerprint\n"));
1315 return gpg_error (GPG_ERR_GENERAL);
1318 kh = keydb_new (0);
1319 if (!kh)
1321 log_error (_("failed to allocate keyDB handle\n"));
1322 return gpg_error (GPG_ERR_ENOMEM);;
1325 if (ephemeral)
1326 keydb_set_ephemeral (kh, 1);
1328 rc = lock_all (kh);
1329 if (rc)
1330 return rc;
1332 rc = keydb_search_fpr (kh, fpr);
1333 if (rc != -1)
1335 keydb_release (kh);
1336 if (!rc)
1338 if (existed)
1339 *existed = 1;
1340 return 0; /* okay */
1342 log_error (_("problem looking for existing certificate: %s\n"),
1343 gpg_strerror (rc));
1344 return rc;
1347 rc = keydb_locate_writable (kh, 0);
1348 if (rc)
1350 log_error (_("error finding writable keyDB: %s\n"), gpg_strerror (rc));
1351 keydb_release (kh);
1352 return rc;
1355 rc = keydb_insert_cert (kh, cert);
1356 if (rc)
1358 log_error (_("error storing certificate: %s\n"), gpg_strerror (rc));
1359 keydb_release (kh);
1360 return rc;
1362 keydb_release (kh);
1363 return 0;
1367 /* This is basically keydb_set_flags but it implements a complete
1368 transaction by locating the certificate in the DB and updating the
1369 flags. */
1370 gpg_error_t
1371 keydb_set_cert_flags (ksba_cert_t cert, int ephemeral,
1372 int which, int idx,
1373 unsigned int mask, unsigned int value)
1375 KEYDB_HANDLE kh;
1376 gpg_error_t err;
1377 unsigned char fpr[20];
1378 unsigned int old_value;
1380 if (!gpgsm_get_fingerprint (cert, 0, fpr, NULL))
1382 log_error (_("failed to get the fingerprint\n"));
1383 return gpg_error (GPG_ERR_GENERAL);
1386 kh = keydb_new (0);
1387 if (!kh)
1389 log_error (_("failed to allocate keyDB handle\n"));
1390 return gpg_error (GPG_ERR_ENOMEM);;
1393 if (ephemeral)
1394 keydb_set_ephemeral (kh, 1);
1396 err = keydb_lock (kh);
1397 if (err)
1399 log_error (_("error locking keybox: %s\n"), gpg_strerror (err));
1400 keydb_release (kh);
1401 return err;
1404 err = keydb_search_fpr (kh, fpr);
1405 if (err)
1407 if (err == -1)
1408 err = gpg_error (GPG_ERR_NOT_FOUND);
1409 else
1410 log_error (_("problem re-searching certificate: %s\n"),
1411 gpg_strerror (err));
1412 keydb_release (kh);
1413 return err;
1416 err = keydb_get_flags (kh, which, idx, &old_value);
1417 if (err)
1419 log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
1420 keydb_release (kh);
1421 return err;
1424 value = ((old_value & ~mask) | (value & mask));
1426 if (value != old_value)
1428 err = keydb_set_flags (kh, which, idx, value);
1429 if (err)
1431 log_error (_("error storing flags: %s\n"), gpg_strerror (err));
1432 keydb_release (kh);
1433 return err;
1437 keydb_release (kh);
1438 return 0;
1442 /* Reset all the certificate flags we have stored with the certificates
1443 for performance reasons. */
1444 void
1445 keydb_clear_some_cert_flags (ctrl_t ctrl, strlist_t names)
1447 gpg_error_t err;
1448 KEYDB_HANDLE hd = NULL;
1449 KEYDB_SEARCH_DESC *desc = NULL;
1450 int ndesc;
1451 strlist_t sl;
1452 int rc=0;
1453 unsigned int old_value, value;
1455 (void)ctrl;
1457 hd = keydb_new (0);
1458 if (!hd)
1460 log_error ("keydb_new failed\n");
1461 goto leave;
1464 if (!names)
1465 ndesc = 1;
1466 else
1468 for (sl=names, ndesc=0; sl; sl = sl->next, ndesc++)
1472 desc = xtrycalloc (ndesc, sizeof *desc);
1473 if (!ndesc)
1475 log_error ("allocating memory failed: %s\n",
1476 gpg_strerror (out_of_core ()));
1477 goto leave;
1480 if (!names)
1481 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1482 else
1484 for (ndesc=0, sl=names; sl; sl = sl->next)
1486 rc = keydb_classify_name (sl->d, desc+ndesc);
1487 if (rc)
1489 log_error ("key `%s' not found: %s\n",
1490 sl->d, gpg_strerror (rc));
1491 rc = 0;
1493 else
1494 ndesc++;
1498 err = keydb_lock (hd);
1499 if (err)
1501 log_error (_("error locking keybox: %s\n"), gpg_strerror (err));
1502 goto leave;
1505 while (!(rc = keydb_search (hd, desc, ndesc)))
1507 if (!names)
1508 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1510 err = keydb_get_flags (hd, KEYBOX_FLAG_VALIDITY, 0, &old_value);
1511 if (err)
1513 log_error (_("error getting stored flags: %s\n"),
1514 gpg_strerror (err));
1515 goto leave;
1518 value = (old_value & ~VALIDITY_REVOKED);
1519 if (value != old_value)
1521 err = keydb_set_flags (hd, KEYBOX_FLAG_VALIDITY, 0, value);
1522 if (err)
1524 log_error (_("error storing flags: %s\n"), gpg_strerror (err));
1525 goto leave;
1529 if (rc && rc != -1)
1530 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
1532 leave:
1533 xfree (desc);
1534 keydb_release (hd);