Rearrange the file tree.
[u/mdw/catacomb] / key / key-io.c
diff --git a/key/key-io.c b/key/key-io.c
new file mode 100644 (file)
index 0000000..df7cd53
--- /dev/null
@@ -0,0 +1,569 @@
+/* -*-c-*-
+ *
+ * Adding new keys to a key file
+ *
+ * (c) 1999 Straylight/Edgeware
+ */
+
+/*----- Licensing notice --------------------------------------------------*
+ *
+ * This file is part of Catacomb.
+ *
+ * Catacomb is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * Catacomb is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with Catacomb; if not, write to the Free
+ * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
+ * MA 02111-1307, USA.
+ */
+
+/*----- Header files ------------------------------------------------------*/
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <mLib/bits.h>
+#include <mLib/crc32.h>
+#include <mLib/dstr.h>
+#include <mLib/hash.h>
+#include <mLib/str.h>
+#include <mLib/sub.h>
+#include <mLib/sym.h>
+#include <mLib/url.h>
+
+#include "key.h"
+
+/*----- Tweakable macros --------------------------------------------------*/
+
+#define KEY_INITSZ 16
+
+/*----- Low-level functions -----------------------------------------------*/
+
+/* --- @insert@ --- *
+ *
+ * Arguments:  @key_file *f@ = pointer to file structure
+ *             @key *k@ = pointer to key block to insert
+ *
+ * Returns:    Error code (one of the @KERR@ code).
+ *
+ * Use:                Links a new key block into the complicated data structure
+ *             which is a keyring file.
+ */
+
+static int insert(key_file *f, key *k)
+{
+  key_ref *kr = 0;
+  unsigned found;
+
+  /* --- Sanity preservatives --- */
+
+  if (key_chkident(k->type))
+    return (KERR_BADTYPE);
+  else if (k->tag && key_chkident(k->tag))
+    return (KERR_BADTAG);
+
+  /* --- Insert into the tag table --- */
+
+  if (k->tag) {
+    kr = sym_find(&f->bytag, k->tag, -1, sizeof(*kr), &found);
+    if (found)
+      return (KERR_DUPTAG);
+    kr->k = k;
+  }
+
+  /* --- Insert into the id table --- */
+
+  {
+    hash_base **bin, *b;
+
+    bin = HASH_BIN(&f->byid, k->id);
+    for (b = *bin; b; b = b->next) {
+      if (b->hash == k->id) {
+       if (kr)
+         sym_remove(&f->bytag, kr);
+       return (KERR_DUPID);
+      }
+    }
+
+    k->_b.next = *bin;
+    *bin = &k->_b;
+    k->_b.hash = k->id;
+  }
+
+  /* --- Extend the table --- */
+
+  if (f->idload > 0)
+    f->idload--;
+  else if (hash_extend(&f->byid))
+    f->idload = SYM_LIMIT(f->byid.mask / 2);
+
+  /* --- Insert into the type table --- */
+
+  kr = sym_find(&f->bytype, k->type, -1, sizeof(*kr), &found);
+  if (!found) {
+    kr->k = k;
+    k->next = 0;
+  } else {
+    key **p = &kr->k;
+    if (k->exp != KEXP_FOREVER) {
+      while (*p && (*p)->exp != KEXP_EXPIRE && (*p)->exp > k->exp)
+       p = &(*p)->next;
+    }
+    k->next = *p;
+    *p = k;
+  }
+
+  return (KERR_OK);
+}
+
+/*----- Reading and writing keys ------------------------------------------*/
+
+/* --- @exptime@ --- *
+ *
+ * Arguments:  @const char *p@ = pointer to string
+ *
+ * Returns:    Time value.
+ *
+ * Use:                Translates an expiry or deletion time.
+ */
+
+time_t exptime(const char *p)
+{
+  size_t sz = strlen(p);
+  if (strncmp(p, "expired", sz) == 0)
+    return (KEXP_EXPIRE);
+  else if (strncmp(p, "forever", sz) == 0)
+    return (KEXP_FOREVER);
+  else
+    return (atol(p));
+}
+
+/* --- @key_merge@ --- *
+ *
+ * Arguments:  @key_file *f@ = pointer to file structure
+ *             @const char *file@ = name of file (for error messages)
+ *             @FILE *fp@ = file handle to read from
+ *             @key_reporter *rep@ = error reporting function
+ *             @void *arg@ = argument for function
+ *
+ * Returns:    Error code (one of the @KERR@ constants).
+ *
+ * Use:                Reads keys from a file, and inserts them into the file.
+ */
+
+int key_merge(key_file *f, const char *file, FILE *fp,
+             key_reporter *rep, void *arg)
+{
+  int line = 0;
+  dstr l = DSTR_INIT;
+  dstr n = DSTR_INIT, v = DSTR_INIT;
+
+  if (!(f->f & KF_WRITE))
+    return (KERR_READONLY);
+
+  for (; dstr_putline(&l, fp) != EOF; DRESET(&l)) {
+    char *vf[6];
+    char *p = l.buf;
+    key *k;
+
+    /* --- Skip blank lines and comments --- *
+     *
+     * Quite what they're doing in what ought to be an automatically-
+     * maintained file I don't know.
+     */
+
+    line++;
+    while (isspace((unsigned char)*p))
+      p++;
+    if (!*p || *p == '#')
+      continue;
+
+    /* --- Break the line into fields --- *
+     *
+     * There are currently six fields of interest:
+     *
+     *  * The key's identification (id, tag and type).
+     *  * The actual key data itself.
+     *  * The key expiry time.
+     *  * The key deletion time.
+     *  * The attributes field.
+     *  * Any further comments.
+     *
+     * All but the last field can contain no spaces.
+     */
+
+    {
+      int n = str_split(p, vf, 5, &vf[5]);
+      if (n < 4) {
+       if (rep)
+         rep(file, line, "too few fields", arg);
+       goto skip_0;
+      }
+    }
+
+    /* --- Allocate a new key block --- */
+
+    k = CREATE(key);
+
+    /* --- Extract the key data into the block --- */
+
+    if ((k->k = key_read(vf[1], 0)) == 0) {
+      if (rep)
+       rep(file, line, "bad key data", arg);
+      goto skip_1;
+    }
+
+    /* --- Decode the identification field --- *
+     *
+     * For compatibility, derive a keyid from the key data.  This can only be
+     * done if the key encoding is binary (and presumably old-encoding binary
+     * at that).
+     */
+
+    {
+      char *q = strchr(vf[0], ':');
+      char *qq;
+
+      if (!q) {
+       if (k->k->e != KENC_BINARY) {
+         if (rep)
+           rep(file, line, "new-style key encoding but no keyid", arg);
+         goto skip_2;
+       }
+       k->id = crc32(0, k->k->u.k.k, k->k->u.k.sz);
+       k->type = xstrdup(vf[0]);
+       k->tag = 0;
+      } else {
+       *q++ = 0;
+       k->id = strtoul(p, 0, 16);
+       if ((qq = strchr(q, ':')) == 0 || !qq[1]) {
+         if (qq)
+           *qq = 0;
+         k->tag = 0;
+       } else {
+         *qq++ = 0;
+         k->tag = xstrdup(qq);
+       }
+       k->type = xstrdup(q);
+      }
+    }
+
+    /* --- Get a key block for the new key --- */
+
+    k->exp = exptime(vf[2]);
+    k->del = exptime(vf[3]);
+
+    /* --- Insert the key block into the table --- */
+
+    {
+      int err;
+
+    again:
+      if ((err = insert(f, k)) < 0) {
+       if (err == KERR_DUPTAG) {
+         if (rep)
+           rep(file, line, "duplicate key tag stripped", arg);
+         xfree(k->tag);
+         k->tag = 0;
+         goto again;
+       }
+       if (rep)
+         rep(file, line, key_strerror(err), arg);
+       goto skip_3;
+      }
+    }
+
+    /* --- Parse up the attributes, if specified --- */
+
+    sym_create(&k->a);
+    if (vf[4] && strcmp(vf[4], "-") != 0) {
+      url_dctx uc;
+      for (url_initdec(&uc, vf[4]); url_dec(&uc, &n, &v); ) {
+       key_putattr(f, k, n.buf, v.buf);
+       DRESET(&n); DRESET(&v);
+      }
+    }
+
+    /* --- Insert the comment --- */
+
+    if (vf[5])
+      k->c = xstrdup(vf[5]);
+    else
+      k->c = 0;
+    continue;
+
+    /* --- Tidy up after something going wrong --- */
+
+  skip_3:
+    if (k->tag)
+      xfree(k->tag);
+    xfree(k->type);
+  skip_2:
+    key_drop(k->k);
+  skip_1:
+    DESTROY(k);
+  skip_0:;
+  }
+
+  /* --- Extensive tidying up now required --- */
+
+  dstr_destroy(&l);
+  dstr_destroy(&n);
+  dstr_destroy(&v);
+  f->f |= KF_MODIFIED;
+  return (0);
+}
+
+/* --- @key_extract@ --- *
+ *
+ * Arguments:  @key_file *f@ = pointer to file structure
+ *             @key *k@ = key to extract
+ *             @FILE *fp@ = file to write on
+ *             @const key_filter *kf@ = pointer to key selection block
+ *
+ * Returns:    Zero if OK, EOF on error.
+ *
+ * Use:                Extracts a key to an ouptut file.
+ */
+
+int key_extract(key_file *f, key *k, FILE *fp, const key_filter *kf)
+{
+  dstr d = DSTR_INIT;
+  time_t t = time(0);
+
+  /* --- Skip the key if it's deleted or unselected--- */
+
+  if (KEY_EXPIRED(t, k->del) || !key_match(k->k, kf))
+    return (0);
+
+  /* --- Encode the key and write the easy stuff --- */
+
+  key_fulltag(k, &d);
+  DPUTC(&d, ' ');
+  key_write(k->k, &d, kf);
+  DPUTC(&d, ' ');
+  dstr_write(&d, fp);
+  DRESET(&d);
+
+  /* --- Write out the expiry and deletion times --- */
+
+  if (KEY_EXPIRED(t, k->exp))
+    fputs("expired ", fp);
+  else if (k->exp == KEXP_FOREVER)
+    fputs("forever ", fp);
+  else
+    fprintf(fp, "%li ", (long)k->exp);
+
+  if (k->del == KEXP_FOREVER)
+    fputs("forever ", fp);
+  else
+    fprintf(fp, "%li ", (long)k->del);
+
+  /* --- Output the attributes --- */
+
+  {
+    int none = 1;
+    sym_iter i;
+    key_attr *a;
+    url_ectx uc;
+
+    url_initenc(&uc);
+    for (sym_mkiter(&i, &k->a); (a = sym_next(&i)) != 0; ) {
+      none = 0;
+      url_enc(&uc, &d, SYM_NAME(a), a->p);
+    }
+    if (none)
+      DPUTS(&d, "-");
+    DWRITE(&d, fp);
+  }
+
+  dstr_destroy(&d);
+  if (k->c) {
+    putc(' ', fp);
+    fputs(k->c, fp);
+  }
+  putc('\n', fp);
+  return (ferror(fp) ? EOF : 0);
+}
+
+/*----- Opening and closing files -----------------------------------------*/
+
+/* --- @key_open@ --- *
+ *
+ * Arguments:  @key_file *f@ = pointer to file structure to initialize
+ *             @const char *file@ = pointer to the file name
+ *             @unsigned how@ = opening options (@KOPEN_*@).
+ *             @key_reporter *rep@ = error reporting function
+ *             @void *arg@ = argument for function
+ *
+ * Returns:    Zero if it worked, nonzero otherwise.
+ *
+ * Use:                Opens a key file, reads its contents, and stores them in a
+ *             structure.  The file is locked appropriately until closed
+ *             using @key_close@.  On an error, everything is cleared away
+ *             tidily.  If the file is opened with @KOPEN_WRITE@, it's
+ *             created if necessary, with read and write permissions for its
+ *             owner only.
+ */
+
+int key_open(key_file *f, const char *file, unsigned how,
+            key_reporter *rep, void *arg)
+{
+  if (key_lockfile(f, file, how)) {
+    rep(file, 0, strerror(errno), arg);
+    return (-1);
+  }
+  f->f = 0;
+  f->name = xstrdup(file);
+
+  hash_create(&f->byid, KEY_INITSZ);
+  f->idload = SYM_LIMIT(KEY_INITSZ);
+  sym_create(&f->bytype);
+  sym_create(&f->bytag);
+  f->f |= KF_WRITE;
+  if (f->fp)
+    key_merge(f, file, f->fp, rep, arg);
+  f->f &= ~KF_MODIFIED;
+
+  if ((how & KOPEN_MASK) == KOPEN_READ) {
+    f->f &= ~KF_WRITE;
+    fclose(f->fp);
+    f->fp = 0;
+  }
+
+  return (0);
+}
+
+/* --- @key_discard@ --- *
+ *
+ * Arguments:  @key_file *f@ = pointer to key file block
+ *
+ * Returns:    ---
+ *
+ * Use:                Frees all the key data, without writing changes.
+ */
+
+void key_discard(key_file *f)
+{
+  hash_base *b;
+  hash_iter i;
+
+  /* --- Free all the individual keys --- */
+
+  for (hash_mkiter(&i, &f->byid); (b = hash_next(&i)) != 0; ) {
+    sym_iter j;
+    key_attr *a;
+    key *k = (key *)b;
+
+    if (k->k) key_drop(k->k);
+    xfree(k->type);
+    xfree(k->tag);
+    if (k->c)
+      xfree(k->c);
+    for (sym_mkiter(&j, &k->a); (a = sym_next(&j)) != 0; )
+      xfree(a->p);
+    sym_destroy(&k->a);
+    DESTROY(k);
+  }
+  hash_destroy(&f->byid);
+  sym_destroy(&f->bytype);
+  sym_destroy(&f->bytag);
+
+  if (f->fp)
+    fclose(f->fp);
+  xfree(f->name);
+}
+
+/* --- @key_close@ --- *
+ *
+ * Arguments:  @key_file *f@ = pointer to key file block
+ *
+ * Returns:    A @KWRITE_@ code indicating how it went.
+ *
+ * Use:                Frees all the key data, writes any changes.  Make sure that
+ *             all hell breaks loose if this returns @KWRITE_BROKEN@.
+ */
+
+int key_close(key_file *f)
+{
+  int e;
+
+  if (f->fp && (e = key_save(f)) != KWRITE_OK)
+    return (e);
+  key_discard(f);
+  return (KWRITE_OK);
+}
+
+/* --- @key_new@ ---
+ *
+ * Arguments:  @key_file *f@ = pointer to key file
+ *             @uint32 id@ = keyid to set
+ *             @const char *type@ = the type of this key
+ *             @time_t exp@ = when the key expires
+ *             @key *kk@ = where to put the key pointer
+ *
+ * Returns:    Error code (one of the @KERR@ constants).
+ *
+ * Use:                Attaches a new key to a key file.  You must have a writable
+ *             key file for this to work.
+ *
+ *             The type is a key type string.  This interface doesn't care
+ *             about how type strings are formatted: it just treats them as
+ *             opaque gobs of text.  Clients are advised to choose some
+ *             standard for representing key types, though.
+ *
+ *             The expiry time should either be a time in the future, or the
+ *             magic value @KEXP_FOREVER@ which means `never expire this
+ *             key'.  Be careful with `forever' keys.  If I were you, I'd
+ *             use a more sophisticated key management system than this for
+ *             them.
+ */
+
+int key_new(key_file *f, uint32 id, const char *type, time_t exp, key **kk)
+{
+  key *k = 0;
+  time_t t = time(0);
+  int e = KERR_OK;
+
+  /* --- Make sure the file is writable --- */
+
+  if (!(f->f & KF_WRITE))
+    e = KERR_READONLY;
+  else if (KEY_EXPIRED(t, exp))
+    e = KERR_EXPIRED;
+  else if (key_chkident(type))
+    e = KERR_BADTYPE;
+  else {
+    k = CREATE(key);
+    k->id = id;
+    k->tag = 0;
+    k->exp = k->del = exp;
+    k->c = 0;
+    k->type = (char *)type; /* temporarily */
+    sym_create(&k->a);
+    if ((e = insert(f, k)) != 0)
+      DESTROY(k);
+    else {
+      k->k = key_newstring(KCAT_SHARE, "<unset>");
+      k->type = xstrdup(type);
+      *kk = k;
+      f->f |= KF_MODIFIED;
+    }
+  }
+
+  return (e);
+}
+
+/*----- That's all, folks -------------------------------------------------*/