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