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