2006-09-06 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / keydb.c
blobb3595cf36ca7ee02b2e79e06817914323c494914
1 /* keydb.c - key database dispatcher
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005 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 2 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
32 #include "gpg.h"
33 #include "util.h"
34 #include "options.h"
35 #include "main.h" /*try_make_homedir ()*/
36 #include "packet.h"
37 #include "keyring.h"
38 #include "keydb.h"
39 #include "i18n.h"
41 static int active_handles;
43 typedef enum {
44 KEYDB_RESOURCE_TYPE_NONE = 0,
45 KEYDB_RESOURCE_TYPE_KEYRING
46 } KeydbResourceType;
47 #define MAX_KEYDB_RESOURCES 40
49 struct resource_item {
50 KeydbResourceType type;
51 union {
52 KEYRING_HANDLE kr;
53 } u;
54 void *token;
55 int secret;
58 static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
59 static int used_resources;
60 static void *primary_keyring=NULL;
62 struct keydb_handle {
63 int locked;
64 int found;
65 int current;
66 int used; /* items in active */
67 struct resource_item active[MAX_KEYDB_RESOURCES];
71 static int lock_all (KEYDB_HANDLE hd);
72 static void unlock_all (KEYDB_HANDLE hd);
75 /* Handle the creation of a keyring if it does not yet exist. Take
76 into acount that other processes might have the keyring already
77 locked. This lock check does not work if the directory itself is
78 not yet available. */
79 static int
80 maybe_create_keyring (char *filename, int force)
82 DOTLOCK lockhd = NULL;
83 IOBUF iobuf;
84 int rc;
85 mode_t oldmask;
86 char *last_slash_in_filename;
88 /* A quick test whether the filename already exists. */
89 if (!access (filename, F_OK))
90 return 0;
92 /* If we don't want to create a new file at all, there is no need to
93 go any further - bail out right here. */
94 if (!force)
95 return gpg_error (GPG_ERR_ENOENT);
97 /* First of all we try to create the home directory. Note, that we
98 don't do any locking here because any sane application of gpg
99 would create the home directory by itself and not rely on gpg's
100 tricky auto-creation which is anyway only done for some home
101 directory name patterns. */
102 last_slash_in_filename = strrchr (filename, DIRSEP_C);
103 *last_slash_in_filename = 0;
104 if (access(filename, F_OK))
106 static int tried;
108 if (!tried)
110 tried = 1;
111 try_make_homedir (filename);
113 if (access (filename, F_OK))
115 rc = gpg_error_from_errno (errno);
116 *last_slash_in_filename = DIRSEP_C;
117 goto leave;
120 *last_slash_in_filename = DIRSEP_C;
123 /* To avoid races with other instances of gpg trying to create or
124 update the keyring (it is removed during an update for a short
125 time), we do the next stuff in a locked state. */
126 lockhd = create_dotlock (filename);
127 if (!lockhd)
129 /* A reason for this to fail is that the directory is not
130 writable. However, this whole locking stuff does not make
131 sense if this is the case. An empty non-writable directory
132 with no keyring is not really useful at all. */
133 if (opt.verbose)
134 log_info ("can't allocate lock for `%s'\n", filename );
136 if (!force)
137 return gpg_error (GPG_ERR_ENOENT);
138 else
139 return gpg_error (GPG_ERR_GENERAL);
142 if ( make_dotlock (lockhd, -1) )
144 /* This is something bad. Probably a stale lockfile. */
145 log_info ("can't lock `%s'\n", filename );
146 rc = G10ERR_GENERAL;
147 goto leave;
150 /* Now the real test while we are locked. */
151 if (!access(filename, F_OK))
153 rc = 0; /* Okay, we may access the file now. */
154 goto leave;
157 /* The file does not yet exist, create it now. */
158 oldmask = umask (077);
159 if (is_secured_filename (filename))
161 iobuf = NULL;
162 errno = EPERM;
164 else
165 iobuf = iobuf_create (filename);
166 umask (oldmask);
167 if (!iobuf)
169 rc = gpg_error_from_errno (errno);
170 log_error ( _("error creating keyring `%s': %s\n"),
171 filename, strerror(errno));
172 goto leave;
175 if (!opt.quiet)
176 log_info (_("keyring `%s' created\n"), filename);
178 iobuf_close (iobuf);
179 /* Must invalidate that ugly cache */
180 iobuf_ioctl (NULL, 2, 0, filename);
181 rc = 0;
183 leave:
184 if (lockhd)
186 release_dotlock (lockhd);
187 destroy_dotlock (lockhd);
189 return rc;
194 * Register a resource (which currently may only be a keyring file).
195 * The first keyring which is added by this function is
196 * created if it does not exist.
197 * Note: this function may be called before secure memory is
198 * available.
199 * Flag 1 == force
200 * Flag 2 == mark resource as primary
201 * Flag 4 == This is a default resources
204 keydb_add_resource (const char *url, int flags, int secret)
206 static int any_secret, any_public;
207 const char *resname = url;
208 char *filename = NULL;
209 int force=(flags&1);
210 int rc = 0;
211 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
212 void *token;
214 /* Do we have an URL?
215 * gnupg-ring:filename := this is a plain keyring
216 * filename := See what is is, but create as plain keyring.
218 if (strlen (resname) > 11) {
219 if (!strncmp( resname, "gnupg-ring:", 11) ) {
220 rt = KEYDB_RESOURCE_TYPE_KEYRING;
221 resname += 11;
223 #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
224 else if (strchr (resname, ':')) {
225 log_error ("invalid key resource URL `%s'\n", url );
226 rc = G10ERR_GENERAL;
227 goto leave;
229 #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
232 if (*resname != DIRSEP_C ) { /* do tilde expansion etc */
233 if (strchr(resname, DIRSEP_C) )
234 filename = make_filename (resname, NULL);
235 else
236 filename = make_filename (opt.homedir, resname, NULL);
238 else
239 filename = xstrdup (resname);
241 if (!force)
242 force = secret? !any_secret : !any_public;
244 /* see whether we can determine the filetype */
245 if (rt == KEYDB_RESOURCE_TYPE_NONE) {
246 FILE *fp = fopen( filename, "rb" );
248 if (fp) {
249 u32 magic;
251 if (fread( &magic, 4, 1, fp) == 1 ) {
252 if (magic == 0x13579ace || magic == 0xce9a5713)
253 ; /* GDBM magic - no more support */
254 else
255 rt = KEYDB_RESOURCE_TYPE_KEYRING;
257 else /* maybe empty: assume ring */
258 rt = KEYDB_RESOURCE_TYPE_KEYRING;
259 fclose( fp );
261 else /* no file yet: create ring */
262 rt = KEYDB_RESOURCE_TYPE_KEYRING;
265 switch (rt) {
266 case KEYDB_RESOURCE_TYPE_NONE:
267 log_error ("unknown type of key resource `%s'\n", url );
268 rc = G10ERR_GENERAL;
269 goto leave;
271 case KEYDB_RESOURCE_TYPE_KEYRING:
272 rc = maybe_create_keyring (filename, force);
273 if (rc)
274 goto leave;
276 if(keyring_register_filename (filename, secret, &token))
278 if (used_resources >= MAX_KEYDB_RESOURCES)
279 rc = G10ERR_RESOURCE_LIMIT;
280 else
282 if(flags&2)
283 primary_keyring=token;
284 all_resources[used_resources].type = rt;
285 all_resources[used_resources].u.kr = NULL; /* Not used here */
286 all_resources[used_resources].token = token;
287 all_resources[used_resources].secret = secret;
288 used_resources++;
291 else
293 /* This keyring was already registered, so ignore it.
294 However, we can still mark it as primary even if it was
295 already registered. */
296 if(flags&2)
297 primary_keyring=token;
299 break;
301 default:
302 log_error ("resource type of `%s' not supported\n", url);
303 rc = G10ERR_GENERAL;
304 goto leave;
307 /* fixme: check directory permissions and print a warning */
309 leave:
310 if (rc)
312 /* Secret keyrings are not required in all cases. To avoid
313 having gpg return failure we use log_info here if the
314 rewsource is a secret one and marked as default
315 resource. */
316 if ((flags&4) && secret)
317 log_info (_("keyblock resource `%s': %s\n"),
318 filename, g10_errstr(rc));
319 else
320 log_error (_("keyblock resource `%s': %s\n"),
321 filename, g10_errstr(rc));
323 else if (secret)
324 any_secret = 1;
325 else
326 any_public = 1;
327 xfree (filename);
328 return rc;
334 KEYDB_HANDLE
335 keydb_new (int secret)
337 KEYDB_HANDLE hd;
338 int i, j;
340 hd = xmalloc_clear (sizeof *hd);
341 hd->found = -1;
343 assert (used_resources <= MAX_KEYDB_RESOURCES);
344 for (i=j=0; i < used_resources; i++)
346 if (!all_resources[i].secret != !secret)
347 continue;
348 switch (all_resources[i].type)
350 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
351 break;
352 case KEYDB_RESOURCE_TYPE_KEYRING:
353 hd->active[j].type = all_resources[i].type;
354 hd->active[j].token = all_resources[i].token;
355 hd->active[j].secret = all_resources[i].secret;
356 hd->active[j].u.kr = keyring_new (all_resources[i].token, secret);
357 if (!hd->active[j].u.kr) {
358 xfree (hd);
359 return NULL; /* fixme: release all previously allocated handles*/
361 j++;
362 break;
365 hd->used = j;
367 active_handles++;
368 return hd;
371 void
372 keydb_release (KEYDB_HANDLE hd)
374 int i;
376 if (!hd)
377 return;
378 assert (active_handles > 0);
379 active_handles--;
381 unlock_all (hd);
382 for (i=0; i < hd->used; i++) {
383 switch (hd->active[i].type) {
384 case KEYDB_RESOURCE_TYPE_NONE:
385 break;
386 case KEYDB_RESOURCE_TYPE_KEYRING:
387 keyring_release (hd->active[i].u.kr);
388 break;
392 xfree (hd);
397 * Return the name of the current resource. This is function first
398 * looks for the last found found, then for the current search
399 * position, and last returns the first available resource. The
400 * returned string is only valid as long as the handle exists. This
401 * function does only return NULL if no handle is specified, in all
402 * other error cases an empty string is returned.
404 const char *
405 keydb_get_resource_name (KEYDB_HANDLE hd)
407 int idx;
408 const char *s = NULL;
410 if (!hd)
411 return NULL;
413 if ( hd->found >= 0 && hd->found < hd->used)
414 idx = hd->found;
415 else if ( hd->current >= 0 && hd->current < hd->used)
416 idx = hd->current;
417 else
418 idx = 0;
420 switch (hd->active[idx].type) {
421 case KEYDB_RESOURCE_TYPE_NONE:
422 s = NULL;
423 break;
424 case KEYDB_RESOURCE_TYPE_KEYRING:
425 s = keyring_get_resource_name (hd->active[idx].u.kr);
426 break;
429 return s? s: "";
434 static int
435 lock_all (KEYDB_HANDLE hd)
437 int i, rc = 0;
439 for (i=0; !rc && i < hd->used; i++) {
440 switch (hd->active[i].type) {
441 case KEYDB_RESOURCE_TYPE_NONE:
442 break;
443 case KEYDB_RESOURCE_TYPE_KEYRING:
444 rc = keyring_lock (hd->active[i].u.kr, 1);
445 break;
449 if (rc) {
450 /* revert the already set locks */
451 for (i--; i >= 0; i--) {
452 switch (hd->active[i].type) {
453 case KEYDB_RESOURCE_TYPE_NONE:
454 break;
455 case KEYDB_RESOURCE_TYPE_KEYRING:
456 keyring_lock (hd->active[i].u.kr, 0);
457 break;
461 else
462 hd->locked = 1;
464 return rc;
467 static void
468 unlock_all (KEYDB_HANDLE hd)
470 int i;
472 if (!hd->locked)
473 return;
475 for (i=hd->used-1; i >= 0; i--) {
476 switch (hd->active[i].type) {
477 case KEYDB_RESOURCE_TYPE_NONE:
478 break;
479 case KEYDB_RESOURCE_TYPE_KEYRING:
480 keyring_lock (hd->active[i].u.kr, 0);
481 break;
484 hd->locked = 0;
489 * Return the last found keyring. Caller must free it.
490 * The returned keyblock has the kbode flag bit 0 set for the node with
491 * the public key used to locate the keyblock or flag bit 1 set for
492 * the user ID node.
495 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
497 int rc = 0;
499 if (!hd)
500 return G10ERR_INV_ARG;
502 if ( hd->found < 0 || hd->found >= hd->used)
503 return -1; /* nothing found */
505 switch (hd->active[hd->found].type) {
506 case KEYDB_RESOURCE_TYPE_NONE:
507 rc = G10ERR_GENERAL; /* oops */
508 break;
509 case KEYDB_RESOURCE_TYPE_KEYRING:
510 rc = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
511 break;
514 return rc;
518 * update the current keyblock with KB
521 keydb_update_keyblock (KEYDB_HANDLE hd, KBNODE kb)
523 int rc = 0;
525 if (!hd)
526 return G10ERR_INV_ARG;
528 if ( hd->found < 0 || hd->found >= hd->used)
529 return -1; /* nothing found */
531 if( opt.dry_run )
532 return 0;
534 rc = lock_all (hd);
535 if (rc)
536 return rc;
538 switch (hd->active[hd->found].type) {
539 case KEYDB_RESOURCE_TYPE_NONE:
540 rc = G10ERR_GENERAL; /* oops */
541 break;
542 case KEYDB_RESOURCE_TYPE_KEYRING:
543 rc = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
544 break;
547 unlock_all (hd);
548 return rc;
553 * Insert a new KB into one of the resources.
556 keydb_insert_keyblock (KEYDB_HANDLE hd, KBNODE kb)
558 int rc = -1;
559 int idx;
561 if (!hd)
562 return G10ERR_INV_ARG;
564 if( opt.dry_run )
565 return 0;
567 if ( hd->found >= 0 && hd->found < hd->used)
568 idx = hd->found;
569 else if ( hd->current >= 0 && hd->current < hd->used)
570 idx = hd->current;
571 else
572 return G10ERR_GENERAL;
574 rc = lock_all (hd);
575 if (rc)
576 return rc;
578 switch (hd->active[idx].type) {
579 case KEYDB_RESOURCE_TYPE_NONE:
580 rc = G10ERR_GENERAL; /* oops */
581 break;
582 case KEYDB_RESOURCE_TYPE_KEYRING:
583 rc = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
584 break;
587 unlock_all (hd);
588 return rc;
593 * The current keyblock will be deleted.
596 keydb_delete_keyblock (KEYDB_HANDLE hd)
598 int rc = -1;
600 if (!hd)
601 return G10ERR_INV_ARG;
603 if ( hd->found < 0 || hd->found >= hd->used)
604 return -1; /* nothing found */
606 if( opt.dry_run )
607 return 0;
609 rc = lock_all (hd);
610 if (rc)
611 return rc;
613 switch (hd->active[hd->found].type) {
614 case KEYDB_RESOURCE_TYPE_NONE:
615 rc = G10ERR_GENERAL; /* oops */
616 break;
617 case KEYDB_RESOURCE_TYPE_KEYRING:
618 rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
619 break;
622 unlock_all (hd);
623 return rc;
628 * Locate the default writable key resource, so that the next
629 * operation (which is only relevant for inserts) will be done on this
630 * resource.
633 keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
635 int rc;
637 if (!hd)
638 return G10ERR_INV_ARG;
640 rc = keydb_search_reset (hd); /* this does reset hd->current */
641 if (rc)
642 return rc;
644 /* If we have a primary set, try that one first */
645 if(primary_keyring)
647 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
649 if(hd->active[hd->current].token==primary_keyring)
651 if(keyring_is_writable (hd->active[hd->current].token))
652 return 0;
653 else
654 break;
658 rc = keydb_search_reset (hd); /* this does reset hd->current */
659 if (rc)
660 return rc;
663 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
665 switch (hd->active[hd->current].type)
667 case KEYDB_RESOURCE_TYPE_NONE:
668 BUG();
669 break;
670 case KEYDB_RESOURCE_TYPE_KEYRING:
671 if (keyring_is_writable (hd->active[hd->current].token))
672 return 0; /* found (hd->current is set to it) */
673 break;
677 return -1;
681 * Rebuild the caches of all key resources.
683 void
684 keydb_rebuild_caches (int noisy)
686 int i, rc;
688 for (i=0; i < used_resources; i++)
690 if (all_resources[i].secret)
691 continue;
692 switch (all_resources[i].type)
694 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
695 break;
696 case KEYDB_RESOURCE_TYPE_KEYRING:
697 rc = keyring_rebuild_cache (all_resources[i].token,noisy);
698 if (rc)
699 log_error (_("failed to rebuild keyring cache: %s\n"),
700 g10_errstr (rc));
701 break;
709 * Start the next search on this handle right at the beginning
711 int
712 keydb_search_reset (KEYDB_HANDLE hd)
714 int i, rc = 0;
716 if (!hd)
717 return G10ERR_INV_ARG;
719 hd->current = 0;
720 hd->found = -1;
721 /* and reset all resources */
722 for (i=0; !rc && i < hd->used; i++) {
723 switch (hd->active[i].type) {
724 case KEYDB_RESOURCE_TYPE_NONE:
725 break;
726 case KEYDB_RESOURCE_TYPE_KEYRING:
727 rc = keyring_search_reset (hd->active[i].u.kr);
728 break;
731 return rc;
736 * Search through all keydb resources, starting at the current position,
737 * for a keyblock which contains one of the keys described in the DESC array.
739 int
740 keydb_search2 (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
741 size_t ndesc, size_t *descindex)
743 int rc = -1;
745 if (!hd)
746 return G10ERR_INV_ARG;
748 while (rc == -1 && hd->current >= 0 && hd->current < hd->used) {
749 switch (hd->active[hd->current].type) {
750 case KEYDB_RESOURCE_TYPE_NONE:
751 BUG(); /* we should never see it here */
752 break;
753 case KEYDB_RESOURCE_TYPE_KEYRING:
754 rc = keyring_search (hd->active[hd->current].u.kr, desc,
755 ndesc, descindex);
756 break;
758 if (rc == -1) /* EOF -> switch to next resource */
759 hd->current++;
760 else if (!rc)
761 hd->found = hd->current;
764 return rc;
768 keydb_search_first (KEYDB_HANDLE hd)
770 KEYDB_SEARCH_DESC desc;
772 memset (&desc, 0, sizeof desc);
773 desc.mode = KEYDB_SEARCH_MODE_FIRST;
774 return keydb_search (hd, &desc, 1);
778 keydb_search_next (KEYDB_HANDLE hd)
780 KEYDB_SEARCH_DESC desc;
782 memset (&desc, 0, sizeof desc);
783 desc.mode = KEYDB_SEARCH_MODE_NEXT;
784 return keydb_search (hd, &desc, 1);
788 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
790 KEYDB_SEARCH_DESC desc;
792 memset (&desc, 0, sizeof desc);
793 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
794 desc.u.kid[0] = kid[0];
795 desc.u.kid[1] = kid[1];
796 return keydb_search (hd, &desc, 1);
800 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
802 KEYDB_SEARCH_DESC desc;
804 memset (&desc, 0, sizeof desc);
805 desc.mode = KEYDB_SEARCH_MODE_FPR;
806 memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
807 return keydb_search (hd, &desc, 1);