2008-02-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / keydb.c
blob3360f63079c2be8d9672e08f37030be0aed087c2
1 /* keydb.c - key database dispatcher
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2008 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
31 #include "gpg.h"
32 #include "util.h"
33 #include "options.h"
34 #include "main.h" /*try_make_homedir ()*/
35 #include "packet.h"
36 #include "keyring.h"
37 #include "keydb.h"
38 #include "i18n.h"
40 static int active_handles;
42 typedef enum {
43 KEYDB_RESOURCE_TYPE_NONE = 0,
44 KEYDB_RESOURCE_TYPE_KEYRING
45 } KeydbResourceType;
46 #define MAX_KEYDB_RESOURCES 40
48 struct resource_item {
49 KeydbResourceType type;
50 union {
51 KEYRING_HANDLE kr;
52 } u;
53 void *token;
54 int secret;
57 static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
58 static int used_resources;
59 static void *primary_keyring=NULL;
61 struct keydb_handle {
62 int locked;
63 int found;
64 int current;
65 int used; /* items in active */
66 struct resource_item active[MAX_KEYDB_RESOURCES];
70 static int lock_all (KEYDB_HANDLE hd);
71 static void unlock_all (KEYDB_HANDLE hd);
74 /* Handle the creation of a keyring if it does not yet exist. Take
75 into acount that other processes might have the keyring already
76 locked. This lock check does not work if the directory itself is
77 not yet available. */
78 static int
79 maybe_create_keyring (char *filename, int force)
81 DOTLOCK lockhd = NULL;
82 IOBUF iobuf;
83 int rc;
84 mode_t oldmask;
85 char *last_slash_in_filename;
86 int save_slash;
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 #if HAVE_W32_SYSTEM
105 /* Windows may either have a slash or a backslash. Take care of it. */
106 char *p = strrchr (filename, '/');
107 if (!last_slash_in_filename || p > last_slash_in_filename)
108 last_slash_in_filename = p;
110 #endif /*HAVE_W32_SYSTEM*/
111 if (!last_slash_in_filename)
112 return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should
113 not happen though. */
114 save_slash = *last_slash_in_filename;
115 *last_slash_in_filename = 0;
116 if (access(filename, F_OK))
118 static int tried;
120 if (!tried)
122 tried = 1;
123 try_make_homedir (filename);
125 if (access (filename, F_OK))
127 rc = gpg_error_from_syserror ();
128 *last_slash_in_filename = save_slash;
129 goto leave;
132 *last_slash_in_filename = save_slash;
134 /* To avoid races with other instances of gpg trying to create or
135 update the keyring (it is removed during an update for a short
136 time), we do the next stuff in a locked state. */
137 lockhd = create_dotlock (filename);
138 if (!lockhd)
140 /* A reason for this to fail is that the directory is not
141 writable. However, this whole locking stuff does not make
142 sense if this is the case. An empty non-writable directory
143 with no keyring is not really useful at all. */
144 if (opt.verbose)
145 log_info ("can't allocate lock for `%s'\n", filename );
147 if (!force)
148 return gpg_error (GPG_ERR_ENOENT);
149 else
150 return gpg_error (GPG_ERR_GENERAL);
153 if ( make_dotlock (lockhd, -1) )
155 /* This is something bad. Probably a stale lockfile. */
156 log_info ("can't lock `%s'\n", filename );
157 rc = G10ERR_GENERAL;
158 goto leave;
161 /* Now the real test while we are locked. */
162 if (!access(filename, F_OK))
164 rc = 0; /* Okay, we may access the file now. */
165 goto leave;
168 /* The file does not yet exist, create it now. */
169 oldmask = umask (077);
170 if (is_secured_filename (filename))
172 iobuf = NULL;
173 errno = EPERM;
175 else
176 iobuf = iobuf_create (filename);
177 umask (oldmask);
178 if (!iobuf)
180 rc = gpg_error_from_syserror ();
181 log_error ( _("error creating keyring `%s': %s\n"),
182 filename, strerror(errno));
183 goto leave;
186 if (!opt.quiet)
187 log_info (_("keyring `%s' created\n"), filename);
189 iobuf_close (iobuf);
190 /* Must invalidate that ugly cache */
191 iobuf_ioctl (NULL, 2, 0, filename);
192 rc = 0;
194 leave:
195 if (lockhd)
197 release_dotlock (lockhd);
198 destroy_dotlock (lockhd);
200 return rc;
205 * Register a resource (which currently may only be a keyring file).
206 * The first keyring which is added by this function is
207 * created if it does not exist.
208 * Note: this function may be called before secure memory is
209 * available.
210 * Flag 1 == force
211 * Flag 2 == mark resource as primary
212 * Flag 4 == This is a default resources
215 keydb_add_resource (const char *url, int flags, int secret)
217 static int any_secret, any_public;
218 const char *resname = url;
219 char *filename = NULL;
220 int force=(flags&1);
221 int rc = 0;
222 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
223 void *token;
225 /* Do we have an URL?
226 * gnupg-ring:filename := this is a plain keyring
227 * filename := See what is is, but create as plain keyring.
229 if (strlen (resname) > 11) {
230 if (!strncmp( resname, "gnupg-ring:", 11) ) {
231 rt = KEYDB_RESOURCE_TYPE_KEYRING;
232 resname += 11;
234 #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
235 else if (strchr (resname, ':')) {
236 log_error ("invalid key resource URL `%s'\n", url );
237 rc = G10ERR_GENERAL;
238 goto leave;
240 #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
243 if (*resname != DIRSEP_C ) { /* do tilde expansion etc */
244 if (strchr(resname, DIRSEP_C) )
245 filename = make_filename (resname, NULL);
246 else
247 filename = make_filename (opt.homedir, resname, NULL);
249 else
250 filename = xstrdup (resname);
252 if (!force)
253 force = secret? !any_secret : !any_public;
255 /* see whether we can determine the filetype */
256 if (rt == KEYDB_RESOURCE_TYPE_NONE) {
257 FILE *fp = fopen( filename, "rb" );
259 if (fp) {
260 u32 magic;
262 if (fread( &magic, 4, 1, fp) == 1 ) {
263 if (magic == 0x13579ace || magic == 0xce9a5713)
264 ; /* GDBM magic - no more support */
265 else
266 rt = KEYDB_RESOURCE_TYPE_KEYRING;
268 else /* maybe empty: assume ring */
269 rt = KEYDB_RESOURCE_TYPE_KEYRING;
270 fclose( fp );
272 else /* no file yet: create ring */
273 rt = KEYDB_RESOURCE_TYPE_KEYRING;
276 switch (rt) {
277 case KEYDB_RESOURCE_TYPE_NONE:
278 log_error ("unknown type of key resource `%s'\n", url );
279 rc = G10ERR_GENERAL;
280 goto leave;
282 case KEYDB_RESOURCE_TYPE_KEYRING:
283 rc = maybe_create_keyring (filename, force);
284 if (rc)
285 goto leave;
287 if(keyring_register_filename (filename, secret, &token))
289 if (used_resources >= MAX_KEYDB_RESOURCES)
290 rc = G10ERR_RESOURCE_LIMIT;
291 else
293 if(flags&2)
294 primary_keyring=token;
295 all_resources[used_resources].type = rt;
296 all_resources[used_resources].u.kr = NULL; /* Not used here */
297 all_resources[used_resources].token = token;
298 all_resources[used_resources].secret = secret;
299 used_resources++;
302 else
304 /* This keyring was already registered, so ignore it.
305 However, we can still mark it as primary even if it was
306 already registered. */
307 if(flags&2)
308 primary_keyring=token;
310 break;
312 default:
313 log_error ("resource type of `%s' not supported\n", url);
314 rc = G10ERR_GENERAL;
315 goto leave;
318 /* fixme: check directory permissions and print a warning */
320 leave:
321 if (rc)
323 /* Secret keyrings are not required in all cases. To avoid
324 having gpg return failure we use log_info here if the
325 rewsource is a secret one and marked as default
326 resource. */
327 if ((flags&4) && secret)
328 log_info (_("keyblock resource `%s': %s\n"),
329 filename, g10_errstr(rc));
330 else
331 log_error (_("keyblock resource `%s': %s\n"),
332 filename, g10_errstr(rc));
334 else if (secret)
335 any_secret = 1;
336 else
337 any_public = 1;
338 xfree (filename);
339 return rc;
345 KEYDB_HANDLE
346 keydb_new (int secret)
348 KEYDB_HANDLE hd;
349 int i, j;
351 hd = xmalloc_clear (sizeof *hd);
352 hd->found = -1;
354 assert (used_resources <= MAX_KEYDB_RESOURCES);
355 for (i=j=0; i < used_resources; i++)
357 if (!all_resources[i].secret != !secret)
358 continue;
359 switch (all_resources[i].type)
361 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
362 break;
363 case KEYDB_RESOURCE_TYPE_KEYRING:
364 hd->active[j].type = all_resources[i].type;
365 hd->active[j].token = all_resources[i].token;
366 hd->active[j].secret = all_resources[i].secret;
367 hd->active[j].u.kr = keyring_new (all_resources[i].token, secret);
368 if (!hd->active[j].u.kr) {
369 xfree (hd);
370 return NULL; /* fixme: release all previously allocated handles*/
372 j++;
373 break;
376 hd->used = j;
378 active_handles++;
379 return hd;
382 void
383 keydb_release (KEYDB_HANDLE hd)
385 int i;
387 if (!hd)
388 return;
389 assert (active_handles > 0);
390 active_handles--;
392 unlock_all (hd);
393 for (i=0; i < hd->used; i++) {
394 switch (hd->active[i].type) {
395 case KEYDB_RESOURCE_TYPE_NONE:
396 break;
397 case KEYDB_RESOURCE_TYPE_KEYRING:
398 keyring_release (hd->active[i].u.kr);
399 break;
403 xfree (hd);
408 * Return the name of the current resource. This is function first
409 * looks for the last found found, then for the current search
410 * position, and last returns the first available resource. The
411 * returned string is only valid as long as the handle exists. This
412 * function does only return NULL if no handle is specified, in all
413 * other error cases an empty string is returned.
415 const char *
416 keydb_get_resource_name (KEYDB_HANDLE hd)
418 int idx;
419 const char *s = NULL;
421 if (!hd)
422 return NULL;
424 if ( hd->found >= 0 && hd->found < hd->used)
425 idx = hd->found;
426 else if ( hd->current >= 0 && hd->current < hd->used)
427 idx = hd->current;
428 else
429 idx = 0;
431 switch (hd->active[idx].type) {
432 case KEYDB_RESOURCE_TYPE_NONE:
433 s = NULL;
434 break;
435 case KEYDB_RESOURCE_TYPE_KEYRING:
436 s = keyring_get_resource_name (hd->active[idx].u.kr);
437 break;
440 return s? s: "";
445 static int
446 lock_all (KEYDB_HANDLE hd)
448 int i, rc = 0;
450 for (i=0; !rc && i < hd->used; i++) {
451 switch (hd->active[i].type) {
452 case KEYDB_RESOURCE_TYPE_NONE:
453 break;
454 case KEYDB_RESOURCE_TYPE_KEYRING:
455 rc = keyring_lock (hd->active[i].u.kr, 1);
456 break;
460 if (rc) {
461 /* revert the already set locks */
462 for (i--; i >= 0; i--) {
463 switch (hd->active[i].type) {
464 case KEYDB_RESOURCE_TYPE_NONE:
465 break;
466 case KEYDB_RESOURCE_TYPE_KEYRING:
467 keyring_lock (hd->active[i].u.kr, 0);
468 break;
472 else
473 hd->locked = 1;
475 return rc;
478 static void
479 unlock_all (KEYDB_HANDLE hd)
481 int i;
483 if (!hd->locked)
484 return;
486 for (i=hd->used-1; i >= 0; i--) {
487 switch (hd->active[i].type) {
488 case KEYDB_RESOURCE_TYPE_NONE:
489 break;
490 case KEYDB_RESOURCE_TYPE_KEYRING:
491 keyring_lock (hd->active[i].u.kr, 0);
492 break;
495 hd->locked = 0;
500 * Return the last found keyring. Caller must free it.
501 * The returned keyblock has the kbode flag bit 0 set for the node with
502 * the public key used to locate the keyblock or flag bit 1 set for
503 * the user ID node.
506 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
508 int rc = 0;
510 if (!hd)
511 return G10ERR_INV_ARG;
513 if ( hd->found < 0 || hd->found >= hd->used)
514 return -1; /* nothing found */
516 switch (hd->active[hd->found].type) {
517 case KEYDB_RESOURCE_TYPE_NONE:
518 rc = G10ERR_GENERAL; /* oops */
519 break;
520 case KEYDB_RESOURCE_TYPE_KEYRING:
521 rc = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
522 break;
525 return rc;
529 * update the current keyblock with KB
532 keydb_update_keyblock (KEYDB_HANDLE hd, KBNODE kb)
534 int rc = 0;
536 if (!hd)
537 return G10ERR_INV_ARG;
539 if ( hd->found < 0 || hd->found >= hd->used)
540 return -1; /* nothing found */
542 if( opt.dry_run )
543 return 0;
545 rc = lock_all (hd);
546 if (rc)
547 return rc;
549 switch (hd->active[hd->found].type) {
550 case KEYDB_RESOURCE_TYPE_NONE:
551 rc = G10ERR_GENERAL; /* oops */
552 break;
553 case KEYDB_RESOURCE_TYPE_KEYRING:
554 rc = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
555 break;
558 unlock_all (hd);
559 return rc;
564 * Insert a new KB into one of the resources.
567 keydb_insert_keyblock (KEYDB_HANDLE hd, KBNODE kb)
569 int rc = -1;
570 int idx;
572 if (!hd)
573 return G10ERR_INV_ARG;
575 if( opt.dry_run )
576 return 0;
578 if ( hd->found >= 0 && hd->found < hd->used)
579 idx = hd->found;
580 else if ( hd->current >= 0 && hd->current < hd->used)
581 idx = hd->current;
582 else
583 return G10ERR_GENERAL;
585 rc = lock_all (hd);
586 if (rc)
587 return rc;
589 switch (hd->active[idx].type) {
590 case KEYDB_RESOURCE_TYPE_NONE:
591 rc = G10ERR_GENERAL; /* oops */
592 break;
593 case KEYDB_RESOURCE_TYPE_KEYRING:
594 rc = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
595 break;
598 unlock_all (hd);
599 return rc;
604 * The current keyblock will be deleted.
607 keydb_delete_keyblock (KEYDB_HANDLE hd)
609 int rc = -1;
611 if (!hd)
612 return G10ERR_INV_ARG;
614 if ( hd->found < 0 || hd->found >= hd->used)
615 return -1; /* nothing found */
617 if( opt.dry_run )
618 return 0;
620 rc = lock_all (hd);
621 if (rc)
622 return rc;
624 switch (hd->active[hd->found].type) {
625 case KEYDB_RESOURCE_TYPE_NONE:
626 rc = G10ERR_GENERAL; /* oops */
627 break;
628 case KEYDB_RESOURCE_TYPE_KEYRING:
629 rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
630 break;
633 unlock_all (hd);
634 return rc;
639 * Locate the default writable key resource, so that the next
640 * operation (which is only relevant for inserts) will be done on this
641 * resource.
644 keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
646 int rc;
648 if (!hd)
649 return G10ERR_INV_ARG;
651 rc = keydb_search_reset (hd); /* this does reset hd->current */
652 if (rc)
653 return rc;
655 /* If we have a primary set, try that one first */
656 if(primary_keyring)
658 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
660 if(hd->active[hd->current].token==primary_keyring)
662 if(keyring_is_writable (hd->active[hd->current].token))
663 return 0;
664 else
665 break;
669 rc = keydb_search_reset (hd); /* this does reset hd->current */
670 if (rc)
671 return rc;
674 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
676 switch (hd->active[hd->current].type)
678 case KEYDB_RESOURCE_TYPE_NONE:
679 BUG();
680 break;
681 case KEYDB_RESOURCE_TYPE_KEYRING:
682 if (keyring_is_writable (hd->active[hd->current].token))
683 return 0; /* found (hd->current is set to it) */
684 break;
688 return -1;
692 * Rebuild the caches of all key resources.
694 void
695 keydb_rebuild_caches (int noisy)
697 int i, rc;
699 for (i=0; i < used_resources; i++)
701 if (all_resources[i].secret)
702 continue;
703 switch (all_resources[i].type)
705 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
706 break;
707 case KEYDB_RESOURCE_TYPE_KEYRING:
708 rc = keyring_rebuild_cache (all_resources[i].token,noisy);
709 if (rc)
710 log_error (_("failed to rebuild keyring cache: %s\n"),
711 g10_errstr (rc));
712 break;
720 * Start the next search on this handle right at the beginning
722 int
723 keydb_search_reset (KEYDB_HANDLE hd)
725 int i, rc = 0;
727 if (!hd)
728 return G10ERR_INV_ARG;
730 hd->current = 0;
731 hd->found = -1;
732 /* and reset all resources */
733 for (i=0; !rc && i < hd->used; i++) {
734 switch (hd->active[i].type) {
735 case KEYDB_RESOURCE_TYPE_NONE:
736 break;
737 case KEYDB_RESOURCE_TYPE_KEYRING:
738 rc = keyring_search_reset (hd->active[i].u.kr);
739 break;
742 return rc;
747 * Search through all keydb resources, starting at the current position,
748 * for a keyblock which contains one of the keys described in the DESC array.
750 int
751 keydb_search2 (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
752 size_t ndesc, size_t *descindex)
754 int rc = -1;
756 if (!hd)
757 return G10ERR_INV_ARG;
759 while (rc == -1 && hd->current >= 0 && hd->current < hd->used) {
760 switch (hd->active[hd->current].type) {
761 case KEYDB_RESOURCE_TYPE_NONE:
762 BUG(); /* we should never see it here */
763 break;
764 case KEYDB_RESOURCE_TYPE_KEYRING:
765 rc = keyring_search (hd->active[hd->current].u.kr, desc,
766 ndesc, descindex);
767 break;
769 if (rc == -1) /* EOF -> switch to next resource */
770 hd->current++;
771 else if (!rc)
772 hd->found = hd->current;
775 return rc;
779 keydb_search_first (KEYDB_HANDLE hd)
781 KEYDB_SEARCH_DESC desc;
783 memset (&desc, 0, sizeof desc);
784 desc.mode = KEYDB_SEARCH_MODE_FIRST;
785 return keydb_search (hd, &desc, 1);
789 keydb_search_next (KEYDB_HANDLE hd)
791 KEYDB_SEARCH_DESC desc;
793 memset (&desc, 0, sizeof desc);
794 desc.mode = KEYDB_SEARCH_MODE_NEXT;
795 return keydb_search (hd, &desc, 1);
799 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
801 KEYDB_SEARCH_DESC desc;
803 memset (&desc, 0, sizeof desc);
804 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
805 desc.u.kid[0] = kid[0];
806 desc.u.kid[1] = kid[1];
807 return keydb_search (hd, &desc, 1);
811 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
813 KEYDB_SEARCH_DESC desc;
815 memset (&desc, 0, sizeof desc);
816 desc.mode = KEYDB_SEARCH_MODE_FPR;
817 memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
818 return keydb_search (hd, &desc, 1);