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