chiark / gitweb /
Report errors if key files don't exist!
[catacomb] / key-io.c
1 /* -*-c-*-
2  *
3  * $Id: key-io.c,v 1.5 2003/10/17 16:30:46 mdw Exp $
4  *
5  * Adding new keys to a key file
6  *
7  * (c) 1999 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Catacomb.
13  *
14  * Catacomb is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  * 
19  * Catacomb is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  * 
24  * You should have received a copy of the GNU Library General Public
25  * License along with Catacomb; if not, write to the Free
26  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27  * MA 02111-1307, USA.
28  */
29
30 /*----- Revision history --------------------------------------------------* 
31  *
32  * $Log: key-io.c,v $
33  * Revision 1.5  2003/10/17 16:30:46  mdw
34  * Report errors if key files don't exist!
35  *
36  * Revision 1.4  2001/02/03 11:57:38  mdw
37  * Allow creating keyfiles with no file attached.
38  *
39  * Revision 1.3  2001/01/20 11:56:48  mdw
40  * Use mLib exported tuning parameters for hashtable.
41  *
42  * Revision 1.2  2000/02/12 18:21:02  mdw
43  * Overhaul of key management (again).
44  *
45  * Revision 1.1  1999/12/22 15:47:48  mdw
46  * Major key-management revision.
47  *
48  */
49
50 /*----- Header files ------------------------------------------------------*/
51
52 #include <ctype.h>
53 #include <errno.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58
59 #include <mLib/bits.h>
60 #include <mLib/crc32.h>
61 #include <mLib/dstr.h>
62 #include <mLib/hash.h>
63 #include <mLib/str.h>
64 #include <mLib/sub.h>
65 #include <mLib/sym.h>
66 #include <mLib/url.h>
67
68 #include "key.h"
69
70 /*----- Tweakable macros --------------------------------------------------*/
71
72 #define KEY_INITSZ 16
73
74 /*----- Low-level functions -----------------------------------------------*/
75
76 /* --- @insert@ --- *
77  *
78  * Arguments:   @key_file *f@ = pointer to file structure
79  *              @key *k@ = pointer to key block to insert
80  *
81  * Returns:     Error code (one of the @KERR@ code).
82  *
83  * Use:         Links a new key block into the complicated data structure
84  *              which is a keyring file.
85  */
86
87 static int insert(key_file *f, key *k)
88 {
89   key_ref *kr = 0;
90   unsigned found;
91
92   /* --- Sanity preservatives --- */
93
94   if (key_chkident(k->type))
95     return (KERR_BADTYPE);
96   else if (k->tag && key_chkident(k->tag))
97     return (KERR_BADTAG);
98
99   /* --- Insert into the tag table --- */
100
101   if (k->tag) {
102     kr = sym_find(&f->bytag, k->tag, -1, sizeof(*kr), &found);
103     if (found)
104       return (KERR_DUPTAG);
105     kr->k = k;
106   }
107
108   /* --- Insert into the id table --- */
109
110   {
111     hash_base **bin, *b;
112
113     bin = HASH_BIN(&f->byid, k->id);
114     for (b = *bin; b; b = b->next) {
115       if (b->hash == k->id) {
116         if (kr)
117           sym_remove(&f->bytag, kr);
118         return (KERR_DUPID);
119       }
120     }
121
122     k->_b.next = *bin;
123     *bin = &k->_b;
124     k->_b.hash = k->id;
125   }
126
127   /* --- Extend the table --- */
128
129   if (f->idload > 0)
130     f->idload--;
131   else if (hash_extend(&f->byid))
132     f->idload = SYM_LIMIT(f->byid.mask / 2);
133
134   /* --- Insert into the type table --- */
135
136   kr = sym_find(&f->bytype, k->type, -1, sizeof(*kr), &found);
137   if (!found) {
138     kr->k = k;
139     k->next = 0;
140   } else {
141     key **p = &kr->k;
142     if (k->exp != KEXP_FOREVER) {
143       while (*p && (*p)->exp != KEXP_EXPIRE && (*p)->exp > k->exp)
144         p = &(*p)->next;
145     }
146     k->next = *p;
147     *p = k;
148   }
149
150   return (KERR_OK);
151 }
152
153 /*----- Reading and writing keys ------------------------------------------*/
154
155 /* --- @exptime@ --- *
156  *
157  * Arguments:   @const char *p@ = pointer to string
158  *
159  * Returns:     Time value.
160  *
161  * Use:         Translates an expiry or deletion time.
162  */
163
164 time_t exptime(const char *p)
165 {
166   size_t sz = strlen(p);
167   if (strncmp(p, "expired", sz) == 0)
168     return (KEXP_EXPIRE);
169   else if (strncmp(p, "forever", sz) == 0)
170     return (KEXP_FOREVER);
171   else
172     return (atol(p));
173 }
174
175 /* --- @key_merge@ --- *
176  *
177  * Arguments:   @key_file *f@ = pointer to file structure
178  *              @const char *file@ = name of file (for error messages)
179  *              @FILE *fp@ = file handle to read from
180  *              @key_reporter *rep@ = error reporting function
181  *              @void *arg@ = argument for function
182  *
183  * Returns:     Error code (one of the @KERR@ constants).
184  *
185  * Use:         Reads keys from a file, and inserts them into the file.
186  */
187
188 int key_merge(key_file *f, const char *file, FILE *fp,
189               key_reporter *rep, void *arg)
190 {
191   int line = 0;
192   dstr l = DSTR_INIT;
193   dstr n = DSTR_INIT, v = DSTR_INIT;
194
195   if (!(f->f & KF_WRITE))
196     return (KERR_READONLY);
197
198   for (; dstr_putline(&l, fp) != EOF; DRESET(&l)) {
199     char *vf[6];
200     char *p = l.buf;
201     key *k;
202
203     /* --- Skip blank lines and comments --- *
204      *
205      * Quite what they're doing in what ought to be an automatically-
206      * maintained file I don't know.
207      */
208
209     line++;
210     while (isspace((unsigned char)*p))
211       p++;
212     if (!*p || *p == '#')
213       continue;
214
215     /* --- Break the line into fields --- *
216      *
217      * There are currently six fields of interest:
218      *
219      *   * The key's identification (id, tag and type).
220      *   * The actual key data itself.
221      *   * The key expiry time.
222      *   * The key deletion time.
223      *   * The attributes field.
224      *   * Any further comments.
225      *
226      * All but the last field can contain no spaces.
227      */
228
229     {
230       int n = str_split(p, vf, 5, &vf[5]);
231       if (n < 4) {
232         if (rep)
233           rep(file, line, "too few fields", arg);
234         goto skip_0;
235       }
236     }
237
238     /* --- Allocate a new key block --- */
239
240     k = CREATE(key);
241
242     /* --- Extract the key data into the block --- */
243
244     if (key_read(vf[1], &k->k, 0)) {
245       if (rep)
246         rep(file, line, "bad key data", arg);
247       goto skip_1;
248     }
249
250     /* --- Decode the identification field --- *
251      *
252      * For compatibility, derive a keyid from the key data.  This can only be
253      * done if the key encoding is binary (and presumably old-encoding binary
254      * at that).
255      */
256
257     {
258       char *q = strchr(vf[0], ':');
259       char *qq;
260
261       if (!q) {
262         if (k->k.e != KENC_BINARY) {
263           if (rep)
264             rep(file, line, "new-style key encoding but no keyid", arg);
265           goto skip_2;
266         }
267         k->id = crc32(0, k->k.u.k.k, k->k.u.k.sz);
268         k->type = xstrdup(vf[0]);
269         k->tag = 0;
270       } else {
271         *q++ = 0;
272         k->id = strtoul(p, 0, 16);
273         if ((qq = strchr(q, ':')) == 0 || !qq[1]) {
274           if (qq)
275             *qq = 0;
276           k->tag = 0;
277         } else {
278           *qq++ = 0;
279           k->tag = xstrdup(qq);
280         }
281         k->type = xstrdup(q);
282       }
283     }
284
285     /* --- Get a key block for the new key --- */
286
287     k->exp = exptime(vf[2]);
288     k->del = exptime(vf[3]);
289
290     /* --- Insert the key block into the table --- */
291
292     {
293       int err;
294
295     again:
296       if ((err = insert(f, k)) < 0) {
297         if (err == KERR_DUPTAG) {
298           if (rep)
299             rep(file, line, "duplicate key tag stripped", arg);
300           free(k->tag);
301           k->tag = 0;
302           goto again;
303         }
304         if (rep)
305           rep(file, line, key_strerror(err), arg);
306         goto skip_3;
307       }
308     }
309  
310     /* --- Parse up the attributes, if specified --- */
311
312     sym_create(&k->a);
313     if (vf[4] && strcmp(vf[4], "-") != 0) {
314       url_dctx uc;
315       for (url_initdec(&uc, vf[4]); url_dec(&uc, &n, &v); ) {
316         key_putattr(f, k, n.buf, v.buf);
317         DRESET(&n); DRESET(&v);
318       }
319     }
320
321     /* --- Insert the comment --- */
322
323     if (vf[5])
324       k->c = xstrdup(vf[5]);
325     else
326       k->c = 0;
327     continue;
328
329     /* --- Tidy up after something going wrong --- */
330
331   skip_3:
332     if (k->tag)
333       free(k->tag);
334     free(k->type);
335   skip_2:
336     key_destroy(&k->k);
337   skip_1:
338     DESTROY(k);
339   skip_0:;
340   }
341
342   /* --- Extensive tidying up now required --- */
343
344   dstr_destroy(&l);
345   dstr_destroy(&n);
346   dstr_destroy(&v);
347   f->f |= KF_MODIFIED;
348   return (0);
349 }
350
351 /* --- @key_extract@ --- *
352  *
353  * Arguments:   @key_file *f@ = pointer to file structure
354  *              @key *k@ = key to extract
355  *              @FILE *fp@ = file to write on
356  *              @const key_filter *kf@ = pointer to key selection block
357  *
358  * Returns:     Zero if OK, EOF on error.
359  *
360  * Use:         Extracts a key to an ouptut file.
361  */
362
363 int key_extract(key_file *f, key *k, FILE *fp, const key_filter *kf)
364 {
365   dstr d = DSTR_INIT;
366   time_t t = time(0);
367
368   /* --- Skip the key if it's deleted or unselected--- */
369
370   if (KEY_EXPIRED(t, k->del) || !key_match(&k->k, kf))
371     return (0);
372
373   /* --- Encode the key and write the easy stuff --- */
374
375   key_fulltag(k, &d);
376   DPUTC(&d, ' ');
377   key_write(&k->k, &d, kf);
378   DPUTC(&d, ' ');
379   dstr_write(&d, fp);
380   DRESET(&d);
381
382   /* --- Write out the expiry and deletion times --- */
383
384   if (KEY_EXPIRED(t, k->exp))
385     fputs("expired ", fp);
386   else if (k->exp == KEXP_FOREVER)
387     fputs("forever ", fp);
388   else
389     fprintf(fp, "%li ", (long)k->exp);
390
391   if (k->del == KEXP_FOREVER)
392     fputs("forever ", fp);
393   else
394     fprintf(fp, "%li ", (long)k->del);
395
396   /* --- Output the attributes --- */
397
398   {
399     int none = 1;
400     sym_iter i;
401     key_attr *a;
402     url_ectx uc;
403
404     url_initenc(&uc);
405     for (sym_mkiter(&i, &k->a); (a = sym_next(&i)) != 0; ) {
406       none = 0;
407       url_enc(&uc, &d, SYM_NAME(a), a->p);
408     }
409     if (none)
410       DPUTS(&d, "-");
411     DWRITE(&d, fp);
412   }
413
414   dstr_destroy(&d);
415   if (k->c) {
416     putc(' ', fp);
417     fputs(k->c, fp);
418   }
419   putc('\n', fp);
420   return (ferror(fp) ? EOF : 0);
421 }
422
423 /*----- Opening and closing files -----------------------------------------*/
424
425 /* --- @key_open@ --- *
426  *
427  * Arguments:   @key_file *f@ = pointer to file structure to initialize
428  *              @const char *file@ = pointer to the file name
429  *              @unsigned how@ = opening options (@KOPEN_*@).
430  *              @key_reporter *rep@ = error reporting function
431  *              @void *arg@ = argument for function
432  *
433  * Returns:     Zero if it worked, nonzero otherwise.
434  *
435  * Use:         Opens a key file, reads its contents, and stores them in a
436  *              structure.  The file is locked appropriately until closed
437  *              using @key_close@.  On an error, everything is cleared away
438  *              tidily.  If the file is opened with @KOPEN_WRITE@, it's
439  *              created if necessary, with read and write permissions for its
440  *              owner only.
441  */
442
443 int key_open(key_file *f, const char *file, unsigned how,
444              key_reporter *rep, void *arg)
445 {
446   if (key_lockfile(f, file, how)) {
447     rep(file, 0, strerror(errno), arg);
448     return (-1);
449   }
450   f->f = 0;
451   f->name = xstrdup(file);
452
453   hash_create(&f->byid, KEY_INITSZ);
454   f->idload = SYM_LIMIT(KEY_INITSZ);
455   sym_create(&f->bytype);
456   sym_create(&f->bytag);
457   f->f |= KF_WRITE;
458   if (f->fp)
459     key_merge(f, file, f->fp, rep, arg);
460   f->f &= ~KF_MODIFIED;
461
462   if ((how & KOPEN_MASK) == KOPEN_READ) {
463     f->f &= ~KF_WRITE;
464     fclose(f->fp);
465     f->fp = 0;
466   }
467
468   return (0);
469 }
470
471 /* --- @key_close@ --- *
472  *
473  * Arguments:   @key_file *f@ = pointer to key file block
474  *
475  * Returns:     A @KWRITE_@ code indicating how it went.
476  *
477  * Use:         Frees all the key data, writes any changes.  Make sure that
478  *              all hell breaks loose if this returns @KWRITE_BROKEN@.
479  */
480
481 int key_close(key_file *f)
482 {
483   int e;
484   hash_base *b;
485   hash_iter i;
486
487   if (f->fp && (e = key_save(f)) != KWRITE_OK)
488     return (e);
489
490   /* --- Free all the individual keys --- */
491
492   for (hash_mkiter(&i, &f->byid); (b = hash_next(&i)) != 0; ) {
493     sym_iter j;
494     key_attr *a;
495     key *k = (key *)b;
496
497     key_destroy(&k->k);
498     free(k->type);
499     free(k->tag);
500     if (k->c)
501       free(k->c);
502     for (sym_mkiter(&j, &k->a); (a = sym_next(&j)) != 0; )
503       free(a->p);
504     sym_destroy(&k->a);
505     DESTROY(k);
506   }
507   hash_destroy(&f->byid);
508   sym_destroy(&f->bytype);
509   sym_destroy(&f->bytag);
510
511   if (f->fp)
512     fclose(f->fp);
513   free(f->name);
514   return (KWRITE_OK);
515 }
516
517 /* --- @key_new@ ---
518  *
519  * Arguments:   @key_file *f@ = pointer to key file
520  *              @uint32 id@ = keyid to set
521  *              @const char *type@ = the type of this key
522  *              @time_t exp@ = when the key expires
523  *              @int *err@ = where to store the error condition
524  *
525  * Returns:     Key block containing new data, or null if it couldn't be
526  *              done.
527  *
528  * Use:         Attaches a new key to a key file.  You must have a writable
529  *              key file for this to work.
530  *
531  *              The type is a key type string.  This interface doesn't care
532  *              about how type strings are formatted: it just treats them as
533  *              opaque gobs of text.  Clients are advised to choose some
534  *              standard for representing key types, though.
535  *
536  *              The expiry time should either be a time in the future, or the
537  *              magic value @KEXP_FOREVER@ which means `never expire this
538  *              key'.  Be careful with `forever' keys.  If I were you, I'd
539  *              use a more sophisticated key management system than this for
540  *              them.
541  *
542  *              You have to set the actual key yourself.
543  */
544
545 key *key_new(key_file *f, uint32 id, const char *type, time_t exp, int *err)
546 {
547   key *k = 0;
548   time_t t = time(0);
549   int e = KERR_OK;
550
551   /* --- Make sure the file is writable --- */
552
553   if (!(f->f & KF_WRITE))
554     e = KERR_READONLY;
555   else if (KEY_EXPIRED(t, exp))
556     e = KERR_EXPIRED;
557   else if (key_chkident(type))
558     e = KERR_BADTYPE;
559   else {
560     k = CREATE(key);
561     k->id = id;
562     k->tag = 0;
563     k->type = xstrdup(type);
564     k->exp = k->del = exp;
565     k->c = 0;
566     k->k.e = 0;
567     sym_create(&k->a);
568     if ((e = insert(f, k)) == 0)
569       f->f |= KF_MODIFIED;
570     else {
571       free(k->type);
572       DESTROY(k);
573       k = 0;
574     }
575   }
576   return (k);
577 }
578
579 /*----- That's all, folks -------------------------------------------------*/