2009-05-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / keydb.c
blob398be19d624f64580ca2b5883bbc56e8716f624b
1 /* keydb.c - key database dispatcher
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2008, 2009 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.
213 * Flag 8 - Open as read-only.
216 keydb_add_resource (const char *url, int flags, int secret)
218 static int any_secret, any_public;
219 const char *resname = url;
220 char *filename = NULL;
221 int force = (flags&1);
222 int readonly = !!(flags&8);
223 int rc = 0;
224 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
225 void *token;
227 if (readonly)
228 force = 0;
230 /* Do we have an URL?
231 * gnupg-ring:filename := this is a plain keyring
232 * filename := See what is is, but create as plain keyring.
234 if (strlen (resname) > 11) {
235 if (!strncmp( resname, "gnupg-ring:", 11) ) {
236 rt = KEYDB_RESOURCE_TYPE_KEYRING;
237 resname += 11;
239 #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
240 else if (strchr (resname, ':')) {
241 log_error ("invalid key resource URL `%s'\n", url );
242 rc = G10ERR_GENERAL;
243 goto leave;
245 #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
248 if (*resname != DIRSEP_C ) { /* do tilde expansion etc */
249 if (strchr(resname, DIRSEP_C) )
250 filename = make_filename (resname, NULL);
251 else
252 filename = make_filename (opt.homedir, resname, NULL);
254 else
255 filename = xstrdup (resname);
257 if (!force && !readonly)
258 force = secret? !any_secret : !any_public;
260 /* See whether we can determine the filetype. */
261 if (rt == KEYDB_RESOURCE_TYPE_NONE) {
262 FILE *fp = fopen( filename, "rb" );
264 if (fp) {
265 u32 magic;
267 if (fread( &magic, 4, 1, fp) == 1 ) {
268 if (magic == 0x13579ace || magic == 0xce9a5713)
269 ; /* GDBM magic - no more support */
270 else
271 rt = KEYDB_RESOURCE_TYPE_KEYRING;
273 else /* maybe empty: assume ring */
274 rt = KEYDB_RESOURCE_TYPE_KEYRING;
275 fclose( fp );
277 else /* no file yet: create ring */
278 rt = KEYDB_RESOURCE_TYPE_KEYRING;
281 switch (rt) {
282 case KEYDB_RESOURCE_TYPE_NONE:
283 log_error ("unknown type of key resource `%s'\n", url );
284 rc = G10ERR_GENERAL;
285 goto leave;
287 case KEYDB_RESOURCE_TYPE_KEYRING:
288 rc = maybe_create_keyring (filename, force);
289 if (rc)
290 goto leave;
292 if(keyring_register_filename (filename, secret, readonly, &token))
294 if (used_resources >= MAX_KEYDB_RESOURCES)
295 rc = G10ERR_RESOURCE_LIMIT;
296 else
298 if(flags&2)
299 primary_keyring=token;
300 all_resources[used_resources].type = rt;
301 all_resources[used_resources].u.kr = NULL; /* Not used here */
302 all_resources[used_resources].token = token;
303 all_resources[used_resources].secret = secret;
304 used_resources++;
307 else
309 /* This keyring was already registered, so ignore it.
310 However, we can still mark it as primary even if it was
311 already registered. */
312 if(flags&2)
313 primary_keyring=token;
315 break;
317 default:
318 log_error ("resource type of `%s' not supported\n", url);
319 rc = G10ERR_GENERAL;
320 goto leave;
323 /* fixme: check directory permissions and print a warning */
325 leave:
326 if (rc)
328 /* Secret keyrings are not required in all cases. To avoid
329 having gpg return failure we use log_info here if the
330 rewsource is a secret one and marked as default
331 resource. */
332 if ((flags&4) && secret)
333 log_info (_("keyblock resource `%s': %s\n"),
334 filename, g10_errstr(rc));
335 else
336 log_error (_("keyblock resource `%s': %s\n"),
337 filename, g10_errstr(rc));
339 else if (secret)
340 any_secret = 1;
341 else
342 any_public = 1;
343 xfree (filename);
344 return rc;
350 KEYDB_HANDLE
351 keydb_new (int secret)
353 KEYDB_HANDLE hd;
354 int i, j;
356 hd = xmalloc_clear (sizeof *hd);
357 hd->found = -1;
359 assert (used_resources <= MAX_KEYDB_RESOURCES);
360 for (i=j=0; i < used_resources; i++)
362 if (!all_resources[i].secret != !secret)
363 continue;
364 switch (all_resources[i].type)
366 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
367 break;
368 case KEYDB_RESOURCE_TYPE_KEYRING:
369 hd->active[j].type = all_resources[i].type;
370 hd->active[j].token = all_resources[i].token;
371 hd->active[j].secret = all_resources[i].secret;
372 hd->active[j].u.kr = keyring_new (all_resources[i].token, secret);
373 if (!hd->active[j].u.kr) {
374 xfree (hd);
375 return NULL; /* fixme: release all previously allocated handles*/
377 j++;
378 break;
381 hd->used = j;
383 active_handles++;
384 return hd;
387 void
388 keydb_release (KEYDB_HANDLE hd)
390 int i;
392 if (!hd)
393 return;
394 assert (active_handles > 0);
395 active_handles--;
397 unlock_all (hd);
398 for (i=0; i < hd->used; i++) {
399 switch (hd->active[i].type) {
400 case KEYDB_RESOURCE_TYPE_NONE:
401 break;
402 case KEYDB_RESOURCE_TYPE_KEYRING:
403 keyring_release (hd->active[i].u.kr);
404 break;
408 xfree (hd);
413 * Return the name of the current resource. This is function first
414 * looks for the last found found, then for the current search
415 * position, and last returns the first available resource. The
416 * returned string is only valid as long as the handle exists. This
417 * function does only return NULL if no handle is specified, in all
418 * other error cases an empty string is returned.
420 const char *
421 keydb_get_resource_name (KEYDB_HANDLE hd)
423 int idx;
424 const char *s = NULL;
426 if (!hd)
427 return NULL;
429 if ( hd->found >= 0 && hd->found < hd->used)
430 idx = hd->found;
431 else if ( hd->current >= 0 && hd->current < hd->used)
432 idx = hd->current;
433 else
434 idx = 0;
436 switch (hd->active[idx].type) {
437 case KEYDB_RESOURCE_TYPE_NONE:
438 s = NULL;
439 break;
440 case KEYDB_RESOURCE_TYPE_KEYRING:
441 s = keyring_get_resource_name (hd->active[idx].u.kr);
442 break;
445 return s? s: "";
450 static int
451 lock_all (KEYDB_HANDLE hd)
453 int i, rc = 0;
455 for (i=0; !rc && i < hd->used; i++) {
456 switch (hd->active[i].type) {
457 case KEYDB_RESOURCE_TYPE_NONE:
458 break;
459 case KEYDB_RESOURCE_TYPE_KEYRING:
460 rc = keyring_lock (hd->active[i].u.kr, 1);
461 break;
465 if (rc) {
466 /* revert the already set locks */
467 for (i--; i >= 0; i--) {
468 switch (hd->active[i].type) {
469 case KEYDB_RESOURCE_TYPE_NONE:
470 break;
471 case KEYDB_RESOURCE_TYPE_KEYRING:
472 keyring_lock (hd->active[i].u.kr, 0);
473 break;
477 else
478 hd->locked = 1;
480 return rc;
483 static void
484 unlock_all (KEYDB_HANDLE hd)
486 int i;
488 if (!hd->locked)
489 return;
491 for (i=hd->used-1; i >= 0; i--) {
492 switch (hd->active[i].type) {
493 case KEYDB_RESOURCE_TYPE_NONE:
494 break;
495 case KEYDB_RESOURCE_TYPE_KEYRING:
496 keyring_lock (hd->active[i].u.kr, 0);
497 break;
500 hd->locked = 0;
505 * Return the last found keyring. Caller must free it.
506 * The returned keyblock has the kbode flag bit 0 set for the node with
507 * the public key used to locate the keyblock or flag bit 1 set for
508 * the user ID node.
511 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
513 int rc = 0;
515 if (!hd)
516 return G10ERR_INV_ARG;
518 if ( hd->found < 0 || hd->found >= hd->used)
519 return -1; /* nothing found */
521 switch (hd->active[hd->found].type) {
522 case KEYDB_RESOURCE_TYPE_NONE:
523 rc = G10ERR_GENERAL; /* oops */
524 break;
525 case KEYDB_RESOURCE_TYPE_KEYRING:
526 rc = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
527 break;
530 return rc;
534 * update the current keyblock with KB
537 keydb_update_keyblock (KEYDB_HANDLE hd, KBNODE kb)
539 int rc = 0;
541 if (!hd)
542 return G10ERR_INV_ARG;
544 if ( hd->found < 0 || hd->found >= hd->used)
545 return -1; /* nothing found */
547 if( opt.dry_run )
548 return 0;
550 rc = lock_all (hd);
551 if (rc)
552 return rc;
554 switch (hd->active[hd->found].type) {
555 case KEYDB_RESOURCE_TYPE_NONE:
556 rc = G10ERR_GENERAL; /* oops */
557 break;
558 case KEYDB_RESOURCE_TYPE_KEYRING:
559 rc = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
560 break;
563 unlock_all (hd);
564 return rc;
569 * Insert a new KB into one of the resources.
572 keydb_insert_keyblock (KEYDB_HANDLE hd, KBNODE kb)
574 int rc = -1;
575 int idx;
577 if (!hd)
578 return G10ERR_INV_ARG;
580 if( opt.dry_run )
581 return 0;
583 if ( hd->found >= 0 && hd->found < hd->used)
584 idx = hd->found;
585 else if ( hd->current >= 0 && hd->current < hd->used)
586 idx = hd->current;
587 else
588 return G10ERR_GENERAL;
590 rc = lock_all (hd);
591 if (rc)
592 return rc;
594 switch (hd->active[idx].type) {
595 case KEYDB_RESOURCE_TYPE_NONE:
596 rc = G10ERR_GENERAL; /* oops */
597 break;
598 case KEYDB_RESOURCE_TYPE_KEYRING:
599 rc = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
600 break;
603 unlock_all (hd);
604 return rc;
609 * The current keyblock will be deleted.
612 keydb_delete_keyblock (KEYDB_HANDLE hd)
614 int rc = -1;
616 if (!hd)
617 return G10ERR_INV_ARG;
619 if ( hd->found < 0 || hd->found >= hd->used)
620 return -1; /* nothing found */
622 if( opt.dry_run )
623 return 0;
625 rc = lock_all (hd);
626 if (rc)
627 return rc;
629 switch (hd->active[hd->found].type) {
630 case KEYDB_RESOURCE_TYPE_NONE:
631 rc = G10ERR_GENERAL; /* oops */
632 break;
633 case KEYDB_RESOURCE_TYPE_KEYRING:
634 rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
635 break;
638 unlock_all (hd);
639 return rc;
644 * Locate the default writable key resource, so that the next
645 * operation (which is only relevant for inserts) will be done on this
646 * resource.
649 keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
651 int rc;
653 (void)reserved;
655 if (!hd)
656 return G10ERR_INV_ARG;
658 rc = keydb_search_reset (hd); /* this does reset hd->current */
659 if (rc)
660 return rc;
662 /* If we have a primary set, try that one first */
663 if(primary_keyring)
665 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
667 if(hd->active[hd->current].token==primary_keyring)
669 if(keyring_is_writable (hd->active[hd->current].token))
670 return 0;
671 else
672 break;
676 rc = keydb_search_reset (hd); /* this does reset hd->current */
677 if (rc)
678 return rc;
681 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
683 switch (hd->active[hd->current].type)
685 case KEYDB_RESOURCE_TYPE_NONE:
686 BUG();
687 break;
688 case KEYDB_RESOURCE_TYPE_KEYRING:
689 if (keyring_is_writable (hd->active[hd->current].token))
690 return 0; /* found (hd->current is set to it) */
691 break;
695 return -1;
699 * Rebuild the caches of all key resources.
701 void
702 keydb_rebuild_caches (int noisy)
704 int i, rc;
706 for (i=0; i < used_resources; i++)
708 if (all_resources[i].secret)
709 continue;
710 if (!keyring_is_writable (all_resources[i].token))
711 continue;
712 switch (all_resources[i].type)
714 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
715 break;
716 case KEYDB_RESOURCE_TYPE_KEYRING:
717 rc = keyring_rebuild_cache (all_resources[i].token,noisy);
718 if (rc)
719 log_error (_("failed to rebuild keyring cache: %s\n"),
720 g10_errstr (rc));
721 break;
729 * Start the next search on this handle right at the beginning
731 int
732 keydb_search_reset (KEYDB_HANDLE hd)
734 int i, rc = 0;
736 if (!hd)
737 return G10ERR_INV_ARG;
739 hd->current = 0;
740 hd->found = -1;
741 /* and reset all resources */
742 for (i=0; !rc && i < hd->used; i++) {
743 switch (hd->active[i].type) {
744 case KEYDB_RESOURCE_TYPE_NONE:
745 break;
746 case KEYDB_RESOURCE_TYPE_KEYRING:
747 rc = keyring_search_reset (hd->active[i].u.kr);
748 break;
751 return rc;
756 * Search through all keydb resources, starting at the current position,
757 * for a keyblock which contains one of the keys described in the DESC array.
759 int
760 keydb_search2 (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
761 size_t ndesc, size_t *descindex)
763 int rc = -1;
765 if (!hd)
766 return G10ERR_INV_ARG;
768 while (rc == -1 && hd->current >= 0 && hd->current < hd->used) {
769 switch (hd->active[hd->current].type) {
770 case KEYDB_RESOURCE_TYPE_NONE:
771 BUG(); /* we should never see it here */
772 break;
773 case KEYDB_RESOURCE_TYPE_KEYRING:
774 rc = keyring_search (hd->active[hd->current].u.kr, desc,
775 ndesc, descindex);
776 break;
778 if (rc == -1) /* EOF -> switch to next resource */
779 hd->current++;
780 else if (!rc)
781 hd->found = hd->current;
784 return rc;
788 keydb_search_first (KEYDB_HANDLE hd)
790 KEYDB_SEARCH_DESC desc;
792 memset (&desc, 0, sizeof desc);
793 desc.mode = KEYDB_SEARCH_MODE_FIRST;
794 return keydb_search (hd, &desc, 1);
798 keydb_search_next (KEYDB_HANDLE hd)
800 KEYDB_SEARCH_DESC desc;
802 memset (&desc, 0, sizeof desc);
803 desc.mode = KEYDB_SEARCH_MODE_NEXT;
804 return keydb_search (hd, &desc, 1);
808 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
810 KEYDB_SEARCH_DESC desc;
812 memset (&desc, 0, sizeof desc);
813 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
814 desc.u.kid[0] = kid[0];
815 desc.u.kid[1] = kid[1];
816 return keydb_search (hd, &desc, 1);
820 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
822 KEYDB_SEARCH_DESC desc;
824 memset (&desc, 0, sizeof desc);
825 desc.mode = KEYDB_SEARCH_MODE_FPR;
826 memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
827 return keydb_search (hd, &desc, 1);