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