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