crlcache.c 71 KB
Newer Older
Werner Koch's avatar
Werner Koch committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* crlcache.c - LDAP access
 * Copyright (C) 2002 Klarälvdalens Datakonsult AB
 * Copyright (C) 2003, 2004, 2005, 2008 g10 Code GmbH
 *
 * This file is part of DirMngr.
 *
 * DirMngr is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * DirMngr 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
Werner Koch's avatar
Werner Koch committed
19 20
 */

21
/*
Werner Koch's avatar
Werner Koch committed
22 23 24 25 26

   1. To keep track of the CRLs actually cached and to store the meta
      information of the CRLs a simple record oriented text file is
      used.  Fields in the file are colon (':') separated and values
      containing colons or linefeeds are percent escaped (e.g. a colon
27
      itself is represented as "%3A").
Werner Koch's avatar
Werner Koch committed
28 29

      The first field is a record type identifier, so that the file is
30
      useful to keep track of other meta data too.
Werner Koch's avatar
Werner Koch committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

      The name of the file is "DIR.txt".


   1.1. Comment record

        Field 1: Constant beginning with "#".

        Other fields are not defined and such a record is simply
        skipped during processing.

   1.2. Version record

        Field 1: Constant "v"
        Field 2: Version number of this file.  Must be 1.

        This record must be the first non-comment record record and
        there shall only exist one record of this type.

   1.3. CRL cache record

        Field 1: Constant "c", "u" or "i".
                 A "c" or "u" indicate a valid cache entry, however
                 "u" requires that a user root certificate check needs
                 to be done.
56
                 An "i" indicates an invalid cache entry which should
Werner Koch's avatar
Werner Koch committed
57
                 not be used but still exists so that it can be
58
                 updated at NEXT_UPDATE.
Werner Koch's avatar
Werner Koch committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        Field 2: Hexadecimal encoded SHA-1 hash of the issuer DN using
                 uppercase letters.
        Field 3: Issuer DN in RFC-2253 notation.
        Field 4: URL used to retrieve the corresponding CRL.
        Field 5: 15 character ISO timestamp with THIS_UPDATE.
        Field 6: 15 character ISO timestamp with NEXT_UPDATE.
        Field 7: Hexadecimal encoded MD-5 hash of the DB file to detect
                 accidental modified (i.e. deleted and created) cache files.
        Field 8: optional CRL number as a hex string.
        Field 9:  AuthorityKeyID.issuer, each Name separated by 0x01
        Field 10: AuthorityKeyID.serial
        Field 11: Hex fingerprint of trust anchor if field 1 is 'u'.

   2. Layout of the standard CRL Cache DB file:

      We use records of variable length with this structure

      n  bytes  Serialnumber (binary) used as key
                thus there is no need to store the length explicitly with DB2.
78
      1  byte   Reason for revocation
Werner Koch's avatar
Werner Koch committed
79 80 81 82 83 84 85
                (currently the KSBA reason flags are used)
      15 bytes  ISO date of revocation (e.g. 19980815T142000)
                Note that there is no terminating 0 stored.

      The filename used is the hexadecimal (using uppercase letters)
      SHA-1 hash value of the issuer DN prefixed with a "crl-" and
      suffixed with a ".db".  Thus the length of the filename is 47.
86

Werner Koch's avatar
Werner Koch committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

*/

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <assert.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#ifndef HAVE_W32_SYSTEM
#include <sys/utsname.h>
#endif
#ifdef MKDIR_TAKES_ONE_ARG
#undef mkdir
#define mkdir(a,b) mkdir(a)
#endif

#include "dirmngr.h"
#include "validate.h"
#include "certcache.h"
#include "crlcache.h"
#include "crlfetch.h"
#include "misc.h"
#include "cdb.h"

/* Change this whenever the format changes */
118
#define DBDIR_D "crls.d"
Werner Koch's avatar
Werner Koch committed
119 120 121 122 123 124 125 126 127 128 129
#define DBDIRFILE "DIR.txt"
#define DBDIRVERSION 1

/* The number of DB files we may have open at one time.  We need to
   limit this because there is no guarantee that the number of issuers
   has a upper limit.  We are currently using mmap, so it is a good
   idea anyway to limit the number of opened cache files. */
#define MAX_OPEN_DB_FILES 5


static const char oidstr_crlNumber[] = "2.5.29.20";
130
/* static const char oidstr_issuingDistributionPoint[] = "2.5.29.28"; */
Werner Koch's avatar
Werner Koch committed
131 132 133 134
static const char oidstr_authorityKeyIdentifier[] = "2.5.29.35";


/* Definition of one cached item. */
135
struct crl_cache_entry_s
Werner Koch's avatar
Werner Koch committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
{
  struct crl_cache_entry_s *next;
  int deleted;        /* True if marked for deletion. */
  int mark;           /* Internally used by update_dir. */
  unsigned int lineno;/* A 0 indicates a new entry. */
  char *release_ptr;  /* The actual allocated memory. */
  char *url;          /* Points into RELEASE_PTR. */
  char *issuer;       /* Ditto. */
  char *issuer_hash;  /* Ditto. */
  char *dbfile_hash;  /* MD5 sum of the cache file, points into RELEASE_PTR.*/
  int invalid;        /* Can't use this CRL. */
  int user_trust_req; /* User supplied root certificate required.  */
  char *check_trust_anchor;  /* Malloced fingerprint.  */
  ksba_isotime_t this_update;
  ksba_isotime_t next_update;
  ksba_isotime_t last_refresh; /* Use for the force_crl_refresh feature. */
  char *crl_number;
  char *authority_issuer;
  char *authority_serialno;

  struct cdb *cdb;             /* The cache file handle or NULL if not open. */

  unsigned int cdb_use_count;  /* Current use count. */
  unsigned int cdb_lru_count;  /* Used for LRU purposes. */
  int dbfile_checked;          /* Set to true if the dbfile_hash value has
                                  been checked one. */
};


/* Definition of the entire cache object. */
166
struct crl_cache_s
Werner Koch's avatar
Werner Koch committed
167 168 169 170 171 172 173 174 175 176 177 178 179
{
  crl_cache_entry_t entries;
};

typedef struct crl_cache_s *crl_cache_t;


/* Prototypes.  */
static crl_cache_entry_t find_entry (crl_cache_entry_t first,
                                     const char *issuer_hash);



Werner Koch's avatar
Werner Koch committed
180
/* The currently loaded cache object.  This is usually initialized
Werner Koch's avatar
Werner Koch committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
   right at startup.  */
static crl_cache_t current_cache;





/* Return the current cache object or bail out if it is has not yet
   been initialized.  */
static crl_cache_t
get_current_cache (void)
{
  if (!current_cache)
    log_fatal ("CRL cache has not yet been initialized\n");
  return current_cache;
}


199
/*
Werner Koch's avatar
Werner Koch committed
200 201 202 203 204 205 206 207 208 209 210 211 212
   Create ae directory if it does not yet exists.  Returns on
   success, or -1 on error.
 */
static int
create_directory_if_needed (const char *name)
{
  DIR *dir;
  char *fname;

  fname = make_filename (opt.homedir_cache, name, NULL);
  dir = opendir (fname);
  if (!dir)
    {
213
      log_info (_("creating directory '%s'\n"), fname);
Werner Koch's avatar
Werner Koch committed
214 215 216
      if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR) )
        {
          int save_errno = errno;
217
          log_error (_("error creating directory '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
218 219
                     fname, strerror (errno));
          xfree (fname);
220
          gpg_err_set_errno (save_errno);
Werner Koch's avatar
Werner Koch committed
221 222
          return -1;
        }
223
    }
Werner Koch's avatar
Werner Koch committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  else
    closedir (dir);
  xfree (fname);
  return 0;
}

/* Remove all files from the cache directory.  If FORCE is not true,
   some sanity checks on the filenames are done. Return 0 if
   everything went fine. */
static int
cleanup_cache_dir (int force)
{
  char *dname = make_filename (opt.homedir_cache, DBDIR_D, NULL);
  DIR *dir;
  struct dirent *de;
  int problem = 0;

  if (!force)
    { /* Very minor sanity checks. */
      if (!strcmp (dname, "~/") || !strcmp (dname, "/" ))
        {
245
          log_error (_("ignoring database dir '%s'\n"), dname);
Werner Koch's avatar
Werner Koch committed
246 247 248 249 250 251 252 253
          xfree (dname);
          return -1;
        }
    }

  dir = opendir (dname);
  if (!dir)
    {
254
      log_error (_("error reading directory '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
255 256 257 258 259 260 261 262 263 264 265 266
                 dname, strerror (errno));
      xfree (dname);
      return -1;
    }

  while ((de = readdir (dir)))
    {
      if (strcmp (de->d_name, "." ) && strcmp (de->d_name, ".."))
        {
          char *cdbname = make_filename (dname, de->d_name, NULL);
          int okay;
          struct stat sbuf;
267

Werner Koch's avatar
Werner Koch committed
268 269 270 271 272 273 274
          if (force)
            okay = 1;
          else
            okay = (!stat (cdbname, &sbuf) && S_ISREG (sbuf.st_mode));

          if (okay)
            {
275
              log_info (_("removing cache file '%s'\n"), cdbname);
276
              if (gnupg_remove (cdbname))
Werner Koch's avatar
Werner Koch committed
277
                {
278
                  log_error ("failed to remove '%s': %s\n",
Werner Koch's avatar
Werner Koch committed
279 280 281 282 283
                             cdbname, strerror (errno));
                  problem = -1;
                }
            }
          else
284
            log_info (_("not removing file '%s'\n"), cdbname);
Werner Koch's avatar
Werner Koch committed
285 286
          xfree (cdbname);
        }
287
    }
Werner Koch's avatar
Werner Koch committed
288 289 290 291 292 293 294 295 296 297 298 299
  xfree (dname);
  closedir (dir);
  return problem;
}


/* Read the next line from the file FP and return the line in an
   malloced buffer.  Return NULL on error or EOF.  There is no
   limitation os the line length.  The trailing linefeed has been
   removed, the function will read the last line of a file, even if
   that is not terminated by a LF. */
static char *
300
next_line_from_file (estream_t fp, gpg_error_t *r_err)
Werner Koch's avatar
Werner Koch committed
301 302 303 304 305 306 307 308 309 310 311 312
{
  char buf[300];
  char *largebuf = NULL;
  size_t buflen;
  size_t len = 0;
  unsigned char *p;
  int c;
  char *tmpbuf;

  *r_err = 0;
  p = buf;
  buflen = sizeof buf - 1;
313
  while ((c=es_getc (fp)) != EOF && c != '\n')
Werner Koch's avatar
Werner Koch committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    {
      if (len >= buflen)
        {
          if (!largebuf)
            {
              buflen += 1024;
              largebuf = xtrymalloc ( buflen + 1 );
              if (!largebuf)
                {
                  *r_err = gpg_error_from_syserror ();
                  return NULL;
                }
              memcpy (largebuf, buf, len);
            }
          else
            {
              buflen += 1024;
              tmpbuf = xtryrealloc (largebuf, buflen + 1);
              if (!tmpbuf)
                {
                  *r_err = gpg_error_from_syserror ();
                  xfree (largebuf);
                  return NULL;
                }
              largebuf = tmpbuf;
            }
          p = largebuf;
        }
      p[len++] = c;
    }
  if (c == EOF && !len)
    return NULL;
  p[len] = 0;
347

Werner Koch's avatar
Werner Koch committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  if (largebuf)
    tmpbuf = xtryrealloc (largebuf, len+1);
  else
    tmpbuf = xtrystrdup (buf);
  if (!tmpbuf)
    {
      *r_err = gpg_error_from_syserror ();
      xfree (largebuf);
    }
  return tmpbuf;
}


/* Release one cache entry.  */
static void
release_one_cache_entry (crl_cache_entry_t entry)
{
  if (entry)
    {
      if (entry->cdb)
        {
          int fd = cdb_fileno (entry->cdb);
          cdb_free (entry->cdb);
          xfree (entry->cdb);
          if (close (fd))
            log_error (_("error closing cache file: %s\n"), strerror(errno));
        }
      xfree (entry->release_ptr);
      xfree (entry->check_trust_anchor);
      xfree (entry);
    }
}


/* Release the CACHE object. */
static void
release_cache (crl_cache_t cache)
{
  crl_cache_entry_t entry, entry2;

  if (!cache)
    return;

  for (entry = cache->entries; entry; entry = entry2)
    {
      entry2 = entry->next;
      release_one_cache_entry (entry);
Werner Koch's avatar
Werner Koch committed
395
    }
Werner Koch's avatar
Werner Koch committed
396 397 398 399 400 401 402
  cache->entries = NULL;
  xfree (cache);
}


/* Open the dir file FNAME or create a new one if it does not yet
   exist. */
403
static estream_t
Werner Koch's avatar
Werner Koch committed
404 405
open_dir_file (const char *fname)
{
406
  estream_t fp;
Werner Koch's avatar
Werner Koch committed
407

408
  fp = es_fopen (fname, "r");
Werner Koch's avatar
Werner Koch committed
409 410
  if (!fp)
    {
411
      log_error (_("failed to open cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
412 413 414
                 fname, strerror (errno));

      /* Make sure that the directory exists, try to create if otherwise. */
415 416
      if (create_directory_if_needed (NULL)
          || create_directory_if_needed (DBDIR_D))
Werner Koch's avatar
Werner Koch committed
417
        return NULL;
418
      fp = es_fopen (fname, "w");
Werner Koch's avatar
Werner Koch committed
419 420
      if (!fp)
        {
421
          log_error (_("error creating new cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
422 423 424
                     fname, strerror (errno));
          return NULL;
        }
425 426
      es_fprintf (fp, "v:%d:\n", DBDIRVERSION);
      if (es_ferror (fp))
Werner Koch's avatar
Werner Koch committed
427
        {
428
          log_error (_("error writing new cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
429
                     fname, strerror (errno));
430
          es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
431 432
          return NULL;
        }
433
      if (es_fclose (fp))
Werner Koch's avatar
Werner Koch committed
434
        {
435
          log_error (_("error closing new cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
436 437 438 439
                     fname, strerror (errno));
          return NULL;
        }

440
      log_info (_("new cache dir file '%s' created\n"), fname);
Werner Koch's avatar
Werner Koch committed
441

442
      fp = es_fopen (fname, "r");
Werner Koch's avatar
Werner Koch committed
443 444
      if (!fp)
        {
445
          log_error (_("failed to re-open cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
446 447 448 449 450 451 452 453 454 455
                     fname, strerror (errno));
          return NULL;
        }
    }

  return fp;
}

/* Helper for open_dir. */
static gpg_error_t
456
check_dir_version (estream_t *fpadr, const char *fname,
Werner Koch's avatar
Werner Koch committed
457 458 459 460 461
                         unsigned int *lineno,
                         int cleanup_on_mismatch)
{
  char *line;
  gpg_error_t lineerr = 0;
462
  estream_t fp = *fpadr;
Werner Koch's avatar
Werner Koch committed
463 464 465 466 467 468 469 470 471 472
  int created = 0;

 retry:
  while ((line = next_line_from_file (fp, &lineerr)))
    {
      ++*lineno;
      if (*line == 'v' && line[1] == ':')
        break;
      else if (*line != '#')
        {
473
          log_error (_("first record of '%s' is not the version\n"), fname);
Werner Koch's avatar
Werner Koch committed
474 475 476 477 478 479 480 481
          xfree (line);
          return gpg_error (GPG_ERR_CONFIGURATION);
        }
      xfree (line);
    }
  if (lineerr)
    return lineerr;

482 483 484
  /* The !line catches the case of an empty DIR file.  We handle this
     the same as a non-matching version.  */
  if (!line || strtol (line+2, NULL, 10) != DBDIRVERSION)
Werner Koch's avatar
Werner Koch committed
485 486 487 488
    {
      if (!created && cleanup_on_mismatch)
        {
          log_error (_("old version of cache directory - cleaning up\n"));
489
          es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
          *fpadr = NULL;
          if (!cleanup_cache_dir (1))
            {
              *lineno = 0;
              fp = *fpadr = open_dir_file (fname);
              if (!fp)
                {
                  xfree (line);
                  return gpg_error (GPG_ERR_CONFIGURATION);
                }
              created = 1;
              goto retry;
            }
        }
      log_error (_("old version of cache directory - giving up\n"));
      xfree (line);
      return gpg_error (GPG_ERR_CONFIGURATION);
    }
  xfree (line);
  return 0;
}


/* Open the dir file and read in all available information.  Store
   that in a newly allocated cache object and return that if
   everything worked out fine.  Create the cache directory and the dir
   if it does not yet exist.  Remove all files in that directory if
   the version does not match. */
static gpg_error_t
open_dir (crl_cache_t *r_cache)
{
  crl_cache_t cache;
522
  char *fname;
Werner Koch's avatar
Werner Koch committed
523 524
  char *line = NULL;
  gpg_error_t lineerr = 0;
525
  estream_t fp;
Werner Koch's avatar
Werner Koch committed
526 527 528 529 530
  crl_cache_entry_t entry, *entrytail;
  unsigned int lineno;
  gpg_error_t err = 0;
  int anyerr = 0;

531
  cache = xtrycalloc (1, sizeof *cache);
Werner Koch's avatar
Werner Koch committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  if (!cache)
    return gpg_error_from_syserror ();

  fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);

  lineno = 0;
  fp = open_dir_file (fname);
  if (!fp)
    {
      err = gpg_error (GPG_ERR_CONFIGURATION);
      goto leave;
    }

  err = check_dir_version (&fp, fname, &lineno, 1);
  if (err)
    goto leave;


  /* Read in all supported entries from the dir file. */
  cache->entries = NULL;
  entrytail = &cache->entries;
  xfree (line);
  while ((line = next_line_from_file (fp, &lineerr)))
    {
      int fieldno;
      char *p, *endp;

      lineno++;
      if ( *line == 'c' || *line == 'u' || *line == 'i' )
        {
          entry = xtrycalloc (1, sizeof *entry);
          if (!entry)
            {
              err = gpg_error_from_syserror ();
              goto leave;
            }
          entry->lineno = lineno;
          entry->release_ptr = line;
          if (*line == 'i')
            {
              entry->invalid = atoi (line+1);
              if (entry->invalid < 1)
                entry->invalid = 1;
            }
          else if (*line == 'u')
            entry->user_trust_req = 1;

          for (fieldno=1, p = line; p; p = endp, fieldno++)
            {
              endp = strchr (p, ':');
              if (endp)
                *endp++ = '\0';

              switch (fieldno)
                {
                case 1: /* record type */ break;
                case 2: entry->issuer_hash = p; break;
                case 3: entry->issuer = unpercent_string (p); break;
                case 4: entry->url = unpercent_string (p); break;
591 592 593 594 595 596 597 598
                case 5:
		  strncpy (entry->this_update, p, 15);
		  entry->this_update[15] = 0;
		  break;
                case 6:
		  strncpy (entry->next_update, p, 15);
		  entry->next_update[15] = 0;
		  break;
Werner Koch's avatar
Werner Koch committed
599 600
                case 7: entry->dbfile_hash = p; break;
                case 8: if (*p) entry->crl_number = p; break;
601
                case 9:
Werner Koch's avatar
Werner Koch committed
602 603 604
                  if (*p)
                    entry->authority_issuer = unpercent_string (p);
                  break;
605
                case 10:
Werner Koch's avatar
Werner Koch committed
606 607 608
                  if (*p)
                    entry->authority_serialno = unpercent_string (p);
                  break;
609
                case 11:
Werner Koch's avatar
Werner Koch committed
610 611 612 613 614 615
                  if (*p)
                    entry->check_trust_anchor = xtrystrdup (p);
                  break;
                default:
                  if (*p)
                    log_info (_("extra field detected in crl record of "
616
                                "'%s' line %u\n"), fname, lineno);
Werner Koch's avatar
Werner Koch committed
617 618 619 620 621 622
                  break;
                }
            }

          if (!entry->issuer_hash)
            {
623
              log_info (_("invalid line detected in '%s' line %u\n"),
Werner Koch's avatar
Werner Koch committed
624 625 626 627 628 629 630 631
                        fname, lineno);
              xfree (entry);
              entry = NULL;
            }
          else if (find_entry (cache->entries, entry->issuer_hash))
            {
              /* Fixme: The duplicate checking used is not very
                 effective for large numbers of issuers. */
632
              log_info (_("duplicate entry detected in '%s' line %u\n"),
Werner Koch's avatar
Werner Koch committed
633 634 635 636 637 638
                        fname, lineno);
              xfree (entry);
              entry = NULL;
            }
          else
            {
639
              line = NULL;
Werner Koch's avatar
Werner Koch committed
640 641 642 643 644 645 646
              *entrytail = entry;
              entrytail = &entry->next;
            }
        }
      else if (*line == '#')
        ;
      else
647
        log_info (_("unsupported record type in '%s' line %u skipped\n"),
Werner Koch's avatar
Werner Koch committed
648 649 650 651 652 653 654 655
                  fname, lineno);

      if (line)
        xfree (line);
    }
  if (lineerr)
    {
      err = lineerr;
656
      log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
Werner Koch's avatar
Werner Koch committed
657 658
      goto leave;
    }
659
  if (es_ferror (fp))
Werner Koch's avatar
Werner Koch committed
660
    {
661
      log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
Werner Koch's avatar
Werner Koch committed
662 663 664 665 666 667 668 669 670 671 672
      err = gpg_error (GPG_ERR_CONFIGURATION);
      goto leave;
    }

  /* Now do some basic checks on the data. */
  for (entry = cache->entries; entry; entry = entry->next)
    {
      assert (entry->lineno);
      if (strlen (entry->issuer_hash) != 40)
        {
          anyerr++;
673
          log_error (_("invalid issuer hash in '%s' line %u\n"),
Werner Koch's avatar
Werner Koch committed
674 675 676 677 678
                     fname, entry->lineno);
        }
      else if ( !*entry->issuer )
        {
          anyerr++;
679
          log_error (_("no issuer DN in '%s' line %u\n"),
Werner Koch's avatar
Werner Koch committed
680 681 682 683 684 685
                     fname, entry->lineno);
        }
      else if ( check_isotime (entry->this_update)
                || check_isotime (entry->next_update))
        {
          anyerr++;
686
          log_error (_("invalid timestamp in '%s' line %u\n"),
Werner Koch's avatar
Werner Koch committed
687 688 689 690 691
                     fname, entry->lineno);
        }

      /* Checks not leading to an immediate fail. */
      if (strlen (entry->dbfile_hash) != 32)
692
        log_info (_("WARNING: invalid cache file hash in '%s' line %u\n"),
693
                  fname, entry->lineno);
Werner Koch's avatar
Werner Koch committed
694
    }
695

Werner Koch's avatar
Werner Koch committed
696 697 698 699 700 701 702 703 704
  if (anyerr)
    {
      log_error (_("detected errors in cache dir file\n"));
      log_info (_("please check the reason and manually delete that file\n"));
      err = gpg_error (GPG_ERR_CONFIGURATION);
    }


 leave:
705
  es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
706 707 708 709 710 711 712 713 714 715 716 717
  xfree (line);
  xfree (fname);
  if (err)
    {
      release_cache (cache);
      cache = NULL;
    }
  *r_cache = cache;
  return err;
}

static void
718
write_percented_string (const char *s, estream_t fp)
Werner Koch's avatar
Werner Koch committed
719 720 721
{
  for (; *s; s++)
    if (*s == ':')
722
      es_fputs ("%3A", fp);
Werner Koch's avatar
Werner Koch committed
723
    else if (*s == '\n')
724
      es_fputs ("%0A", fp);
Werner Koch's avatar
Werner Koch committed
725
    else if (*s == '\r')
726
      es_fputs ("%0D", fp);
Werner Koch's avatar
Werner Koch committed
727
    else
728
      es_putc (*s, fp);
Werner Koch's avatar
Werner Koch committed
729 730 731 732
}


static void
733
write_dir_line_crl (estream_t fp, crl_cache_entry_t e)
Werner Koch's avatar
Werner Koch committed
734 735
{
  if (e->invalid)
736
    es_fprintf (fp, "i%d", e->invalid);
Werner Koch's avatar
Werner Koch committed
737
  else if (e->user_trust_req)
738
    es_putc ('u', fp);
Werner Koch's avatar
Werner Koch committed
739
  else
740 741 742 743
    es_putc ('c', fp);
  es_putc (':', fp);
  es_fputs (e->issuer_hash, fp);
  es_putc (':', fp);
Werner Koch's avatar
Werner Koch committed
744
  write_percented_string (e->issuer, fp);
745
  es_putc (':', fp);
Werner Koch's avatar
Werner Koch committed
746
  write_percented_string (e->url, fp);
747
  es_putc (':', fp);
748
  es_fwrite (e->this_update, 15, 1, fp);
749
  es_putc (':', fp);
750
  es_fwrite (e->next_update, 15, 1, fp);
751 752 753
  es_putc (':', fp);
  es_fputs (e->dbfile_hash, fp);
  es_putc (':', fp);
Werner Koch's avatar
Werner Koch committed
754
  if (e->crl_number)
755 756
    es_fputs (e->crl_number, fp);
  es_putc (':', fp);
Werner Koch's avatar
Werner Koch committed
757 758
  if (e->authority_issuer)
    write_percented_string (e->authority_issuer, fp);
759
  es_putc (':', fp);
Werner Koch's avatar
Werner Koch committed
760
  if (e->authority_serialno)
761 762
    es_fputs (e->authority_serialno, fp);
  es_putc (':', fp);
Werner Koch's avatar
Werner Koch committed
763
  if (e->check_trust_anchor && e->user_trust_req)
764 765
    es_fputs (e->check_trust_anchor, fp);
  es_putc ('\n', fp);
Werner Koch's avatar
Werner Koch committed
766 767 768 769 770 771 772 773 774 775 776
}


/* Update the current dir file using the cache. */
static gpg_error_t
update_dir (crl_cache_t cache)
{
  char *fname = NULL;
  char *tmpfname = NULL;
  char *line = NULL;
  gpg_error_t lineerr = 0;
777 778
  estream_t fp;
  estream_t fpout = NULL;
Werner Koch's avatar
Werner Koch committed
779 780 781 782 783 784 785 786 787 788 789 790
  crl_cache_entry_t e;
  unsigned int lineno;
  gpg_error_t err = 0;

  fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);

  /* Fixme: Take an update file lock here. */

  for (e= cache->entries; e; e = e->next)
    e->mark = 1;

  lineno = 0;
791
  fp = es_fopen (fname, "r");
Werner Koch's avatar
Werner Koch committed
792 793 794
  if (!fp)
    {
      err = gpg_error_from_errno (errno);
795
      log_error (_("failed to open cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
796 797 798 799 800 801
                 fname, strerror (errno));
      goto leave;
    }
  err = check_dir_version (&fp, fname, &lineno, 0);
  if (err)
    goto leave;
802
  es_rewind (fp);
Werner Koch's avatar
Werner Koch committed
803 804 805 806 807 808 809 810 811
  lineno = 0;

  /* Create a temporary DIR file. */
  {
    char *tmpbuf, *p;
    const char *nodename;
#ifndef HAVE_W32_SYSTEM
    struct utsname utsbuf;
#endif
812

Werner Koch's avatar
Werner Koch committed
813 814 815 816 817 818 819 820 821
#ifdef HAVE_W32_SYSTEM
    nodename = "unknown";
#else
    if (uname (&utsbuf))
      nodename = "unknown";
    else
      nodename = utsbuf.nodename;
#endif

822 823
    gpgrt_asprintf (&tmpbuf, "DIR-tmp-%s-%u-%p.txt.tmp",
                    nodename, (unsigned int)getpid (), &tmpbuf);
Werner Koch's avatar
Werner Koch committed
824 825 826
    if (!tmpbuf)
      {
        err = gpg_error_from_errno (errno);
827
        log_error (_("failed to create temporary cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
828 829 830 831 832 833 834 835 836
                   tmpfname, strerror (errno));
        goto leave;
      }
    for (p=tmpbuf; *p; p++)
      if (*p == '/')
        *p = '.';
    tmpfname = make_filename (opt.homedir_cache, DBDIR_D, tmpbuf, NULL);
    xfree (tmpbuf);
  }
837
  fpout = es_fopen (tmpfname, "w");
Werner Koch's avatar
Werner Koch committed
838 839 840
  if (!fpout)
    {
      err = gpg_error_from_errno (errno);
841
      log_error (_("failed to create temporary cache dir file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
                 tmpfname, strerror (errno));
      goto leave;
    }

  while ((line = next_line_from_file (fp, &lineerr)))
    {
      lineno++;
      if (*line == 'c' || *line == 'u' || *line == 'i')
        {
          /* Extract the issuer hash field. */
          char *fieldp, *endp;

          fieldp = strchr (line, ':');
          endp = fieldp? strchr (++fieldp, ':') : NULL;
          if (endp)
            {
              /* There should be no percent within the issuer hash
                 field, thus we can compare it pretty easily. */
              *endp = 0;
              e = find_entry ( cache->entries, fieldp);
862
              *endp = ':'; /* Restore original line. */
863
              if (e && e->deleted)
Werner Koch's avatar
Werner Koch committed
864 865
                {
                  /* Marked for deletion, so don't write it. */
866
                  e->mark = 0;
Werner Koch's avatar
Werner Koch committed
867 868 869 870 871 872 873 874 875 876 877
                }
              else if (e)
                {
                  /* Yep, this is valid entry we know about; write it out */
                  write_dir_line_crl (fpout, e);
                  e->mark = 0;
                }
              else
                { /* We ignore entries we don't have in our cache
                     because they may have been added in the meantime
                     by other instances of dirmngr. */
878
                  es_fprintf (fpout, "# Next line added by "
879
                              "another process; our pid is %lu\n",
880 881 882
                              (unsigned long)getpid ());
                  es_fputs (line, fpout);
                  es_putc ('\n', fpout);
Werner Koch's avatar
Werner Koch committed
883 884 885 886
                }
            }
          else
            {
887 888 889
              es_fputs ("# Invalid line detected: ", fpout);
              es_fputs (line, fpout);
              es_putc ('\n', fpout);
Werner Koch's avatar
Werner Koch committed
890 891
            }
        }
892
      else
Werner Koch's avatar
Werner Koch committed
893 894
        {
          /* Write out all non CRL lines as they are. */
895 896
          es_fputs (line, fpout);
          es_putc ('\n', fpout);
Werner Koch's avatar
Werner Koch committed
897 898 899 900
        }

      xfree (line);
    }
Werner Koch's avatar
Werner Koch committed
901
  if (!es_ferror (fp) && !es_ferror (fpout) && !lineerr)
Werner Koch's avatar
Werner Koch committed
902 903 904 905 906 907 908 909 910 911 912 913 914
    {
      /* Write out the remaining entries. */
      for (e= cache->entries; e; e = e->next)
        if (e->mark)
          {
            if (!e->deleted)
              write_dir_line_crl (fpout, e);
            e->mark = 0;
          }
    }
  if (lineerr)
    {
      err = lineerr;
915
      log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
Werner Koch's avatar
Werner Koch committed
916 917
      goto leave;
    }
918
  if (es_ferror (fp))
Werner Koch's avatar
Werner Koch committed
919 920
    {
      err = gpg_error_from_errno (errno);
921
      log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
Werner Koch's avatar
Werner Koch committed
922
    }
923
  if (es_ferror (fpout))
Werner Koch's avatar
Werner Koch committed
924 925
    {
      err = gpg_error_from_errno (errno);
926
      log_error (_("error writing '%s': %s\n"), tmpfname, strerror (errno));
Werner Koch's avatar
Werner Koch committed
927 928 929 930 931
    }
  if (err)
    goto leave;

  /* Rename the files. */
932
  es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
933
  fp = NULL;
934
  if (es_fclose (fpout))
Werner Koch's avatar
Werner Koch committed
935 936
    {
      err = gpg_error_from_errno (errno);
937
      log_error (_("error closing '%s': %s\n"), tmpfname, strerror (errno));
Werner Koch's avatar
Werner Koch committed
938 939 940 941 942 943
      goto leave;
    }
  fpout = NULL;

#ifdef HAVE_W32_SYSTEM
  /* No atomic mv on W32 systems.  */
944
  gnupg_remove (fname);
Werner Koch's avatar
Werner Koch committed
945 946 947 948
#endif
  if (rename (tmpfname, fname))
    {
      err = gpg_error_from_errno (errno);
949
      log_error (_("error renaming '%s' to '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
950 951 952 953 954 955 956
                 tmpfname, fname, strerror (errno));
      goto leave;
    }

 leave:
  /* Fixme: Relinquish update lock. */
  xfree (line);
957
  es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
958 959 960
  xfree (fname);
  if (fpout)
    {
961
      es_fclose (fpout);
Werner Koch's avatar
Werner Koch committed
962
      if (err && tmpfname)
963
        gnupg_remove (tmpfname);
Werner Koch's avatar
Werner Koch committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
    }
  xfree (tmpfname);
  return err;
}




/* Create the filename for the cache file from the 40 byte ISSUER_HASH
   string. Caller must release the return string. */
static char *
make_db_file_name (const char *issuer_hash)
{
  char bname[50];

  assert (strlen (issuer_hash) == 40);
  memcpy (bname, "crl-", 4);
  memcpy (bname + 4, issuer_hash, 40);
  strcpy (bname + 44, ".db");
  return make_filename (opt.homedir_cache, DBDIR_D, bname, NULL);
}


/* Hash the file FNAME and return the MD5 digest in MD5BUFFER. The
   caller must allocate MD%buffer wityh at least 16 bytes. Returns 0
   on success. */
static int
hash_dbfile (const char *fname, unsigned char *md5buffer)
{
993
  estream_t fp;
Werner Koch's avatar
Werner Koch committed
994 995 996
  char *buffer;
  size_t n;
  gcry_md_hd_t md5;
997
  gpg_error_t err;
Werner Koch's avatar
Werner Koch committed
998 999

  buffer = xtrymalloc (65536);
1000
  fp = buffer? es_fopen (fname, "rb") : NULL;
Werner Koch's avatar
Werner Koch committed
1001 1002
  if (!fp)
    {
1003
      log_error (_("can't hash '%s': %s\n"), fname, strerror (errno));
Werner Koch's avatar
Werner Koch committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
      xfree (buffer);
      return -1;
    }

  err = gcry_md_open (&md5, GCRY_MD_MD5, 0);
  if (err)
    {
      log_error (_("error setting up MD5 hash context: %s\n"),
                 gpg_strerror (err));
      xfree (buffer);
1014
      es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
1015 1016 1017 1018 1019 1020
      return -1;
    }

  /* We better hash some information about the cache file layout in. */
  sprintf (buffer, "%.100s/%.100s:%d", DBDIR_D, DBDIRFILE, DBDIRVERSION);
  gcry_md_write (md5, buffer, strlen (buffer));
1021

Werner Koch's avatar
Werner Koch committed
1022 1023
  for (;;)
    {
1024 1025
      n = es_fread (buffer, 1, 65536, fp);
      if (n < 65536 && es_ferror (fp))
Werner Koch's avatar
Werner Koch committed
1026
        {
1027
          log_error (_("error hashing '%s': %s\n"), fname, strerror (errno));
Werner Koch's avatar
Werner Koch committed
1028
          xfree (buffer);
1029
          es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
1030 1031 1032 1033 1034 1035 1036
          gcry_md_close (md5);
          return -1;
        }
      if (!n)
        break;
      gcry_md_write (md5, buffer, n);
    }
1037
  es_fclose (fp);
Werner Koch's avatar
Werner Koch committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
  xfree (buffer);
  gcry_md_final (md5);

  memcpy (md5buffer, gcry_md_read (md5, GCRY_MD_MD5), 16);
  gcry_md_close (md5);
  return 0;
}

/* Compare the file FNAME against the dexified MD5 hash MD5HASH and
   return 0 if they match. */
static int
check_dbfile (const char *fname, const char *md5hexvalue)
{
  unsigned char buffer1[16], buffer2[16];

  if (strlen (md5hexvalue) != 32)
    {
1055
      log_error (_("invalid formatted checksum for '%s'\n"), fname);
Werner Koch's avatar
Werner Koch committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
      return -1;
    }
  unhexify (buffer1, md5hexvalue);

  if (hash_dbfile (fname, buffer2))
    return -1;

  return memcmp (buffer1, buffer2, 16);
}


/* Open the cache file for ENTRY.  This function implements a caching
   strategy and might close unused cache files. It is required to use
1069
   unlock_db_file after using the file. */
Werner Koch's avatar
Werner Koch committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
static struct cdb *
lock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
{
  char *fname;
  int fd;
  int open_count;
  crl_cache_entry_t e;

  if (entry->cdb)
    {
      entry->cdb_use_count++;
      return entry->cdb;
    }

  for (open_count = 0, e = cache->entries; e; e = e->next)
    {
      if (e->cdb)
        open_count++;
/*       log_debug ("CACHE: cdb=%p use_count=%u lru_count=%u\n", */
/*                  e->cdb,e->cdb_use_count,e->cdb_lru_count); */
    }

  /* If there are too many file open, find the least recent used DB
     file and close it.  Note that for Pth thread safeness we need to
     use a loop here. */
  while (open_count >= MAX_OPEN_DB_FILES )
    {
      crl_cache_entry_t last_e = NULL;
      unsigned int last_lru = (unsigned int)(-1);

      for (e = cache->entries; e; e = e->next)
        if (e->cdb && !e->cdb_use_count && e->cdb_lru_count < last_lru)
          {
            last_lru = e->cdb_lru_count;
            last_e = e;
          }
      if (!last_e)
        {
          log_error (_("too many open cache files; can't open anymore\n"));
          return NULL;
        }

/*       log_debug ("CACHE: closing file at cdb=%p\n", last_e->cdb); */

      fd = cdb_fileno (last_e->cdb);
      cdb_free (last_e->cdb);
      xfree (last_e->cdb);
      last_e->cdb = NULL;
      if (close (fd))
        log_error (_("error closing cache file: %s\n"), strerror(errno));
      open_count--;
    }


  fname = make_db_file_name (entry->issuer_hash);
  if (opt.verbose)
1126
    log_info (_("opening cache file '%s'\n"), fname );
Werner Koch's avatar
Werner Koch committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

  if (!entry->dbfile_checked)
    {
      if (!check_dbfile (fname, entry->dbfile_hash))
        entry->dbfile_checked = 1;
      /* Note, in case of an error we don't print an error here but
         let require the caller to do that check. */
    }

  entry->cdb = xtrycalloc (1, sizeof *entry->cdb);
  if (!entry->cdb)
    {
      xfree (fname);
      return NULL;
    }
  fd = open (fname, O_RDONLY);
  if (fd == -1)
    {
1145
      log_error (_("error opening cache file '%s': %s\n"),
Werner Koch's avatar
Werner Koch committed
1146 1147 1148 1149 1150 1151 1152 1153
                 fname, strerror (errno));
      xfree (entry->cdb);
      entry->cdb = NULL;
      xfree (fname);
      return NULL;
    }
  if (cdb_init (entry->cdb, fd))
    {
1154
      log_error (_("error initializing cache file '%s' for reading: %s\n"),
Werner Koch's avatar
Werner Koch committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
                 fname, strerror (errno));
      xfree (entry->cdb);
      entry->cdb = NULL;
      close (fd);
      xfree (fname);
      return NULL;
    }
  xfree (fname);

  entry->cdb_use_count = 1;
  entry->cdb_lru_count = 0;

  return entry->cdb;
}

/* Unlock a cache file, so that it can be reused. */
static void
unlock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
{
  if (!entry->cdb)
    log_error (_("calling unlock_db_file on a closed file\n"));
  else if (!entry->cdb_use_count)
    log_error (_("calling unlock_db_file on an unlocked file\n"));
1178
  else
Werner Koch's avatar
Werner Koch committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    {
      entry->cdb_use_count--;
      entry->cdb_lru_count++;
    }

  /* If the entry was marked for deletion in the meantime do it now.
     We do this for the sake of Pth thread safeness. */
  if (!entry->cdb_use_count && entry->deleted)
    {
      crl_cache_entry_t eprev, enext;

      enext = entry->next;
      for (eprev = cache->entries;
           eprev && eprev->next != entry; eprev = eprev->next)
        ;
      assert (eprev);
      if (eprev == cache->entries)
        cache->entries = enext;
      else
        eprev->next = enext;
Werner Koch's avatar
Werner Koch committed
1199
      /* FIXME: Do we leak ENTRY? */
Werner Koch's avatar
Werner Koch committed
1200 1201 1202 1203 1204 1205
    }
}


/* Find ISSUER_HASH in our cache FIRST. This may be used to enumerate
   the linked list we use to keep the CRLs of an issuer. */
1206
static crl_cache_entry_t
Werner Koch's avatar
Werner Koch committed
1207 1208 1209 1210
find_entry (crl_cache_entry_t first, const char *issuer_hash)
{
  while (first && (first->deleted || strcmp (issuer_hash, first->issuer_hash)))
    first = first->next;
1211
  return first;
Werner Koch's avatar
Werner Koch committed
1212 1213 1214
}


1215
/* Create a new CRL cache. This function is usually called only once.
Werner Koch's avatar
Werner Koch committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
   never fail. */
void
crl_cache_init(void)
{
  crl_cache_t cache = NULL;
  gpg_error_t err;

  if (current_cache)
    {
      log_error ("crl cache has already been initialized - not doing twice\n");
      return;
    }

  err = open_dir (&cache);
1230
  if (err)
Werner Koch's avatar
Werner Koch committed
1231 1232 1233 1234 1235 1236 1237 1238
    log_fatal (_("failed to create a new cache object: %s\n"),
               gpg_strerror (err));
  current_cache = cache;
}


/* Remove the cache information and all its resources.  Note that we
   still keep the cache on disk. */
1239
void
Werner Koch's avatar
Werner Koch committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
crl_cache_deinit (void)
{
  if (current_cache)
    {
      release_cache (current_cache);
      current_cache = NULL;
    }
}


/* Delete the cache from disk. Return 0 on success.*/
1251
int
Werner Koch's avatar
Werner Koch committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
crl_cache_flush (void)
{
  int rc;

  rc = cleanup_cache_dir (0)? -1 : 0;

  return rc;
}


/* Check whether the certificate identified by ISSUER_HASH and
   SN/SNLEN is valid; i.e. not listed in our cache.  With
   FORCE_REFRESH set to true, a new CRL will be retrieved even if the
   cache has not yet expired.  We use a 30 minutes threshold here so
   that invoking this function several times won't load the CRL over
   and over.  */
1268
static crl_cache_result_t
Werner Koch's avatar
Werner Koch committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
cache_isvalid (ctrl_t ctrl, const char *issuer_hash,
               const unsigned char *sn, size_t snlen,
               int force_refresh)
{
  crl_cache_t cache = get_current_cache ();
  crl_cache_result_t retval;
  struct cdb *cdb;
  int rc;
  crl_cache_entry_t entry;
  gnupg_isotime_t current_time;
  size_t n;

  (void)ctrl;

  entry = find_entry (cache->entries, issuer_hash);
  if (!entry)
    {
      log_info (_("no CRL available for issuer id %s\n"), issuer_hash );
      return CRL_CACHE_DONTKNOW;
    }

  gnupg_get_isotime (current_time);
  if (strcmp (entry->next_update, current_time) < 0 )
    {
      log_info (_("cached CRL for issuer id %s too old; update required\n"),
                issuer_hash);
      return CRL_CACHE_DONTKNOW;
    }
  if (force_refresh)
    {
      gnupg_isotime_t tmptime;
1300

Werner Koch's avatar
Werner Koch committed
1301 1302 1303 1304 1305 1306 1307
      if (*entry->last_refresh)
        {
          gnupg_copy_time (tmptime, entry->last_refresh);
          add_seconds_to_isotime (tmptime, 30 * 60);
          if (strcmp (tmptime, current_time) < 0 )
            {
              log_info (_("force-crl-refresh active and %d minutes passed for"
1308
                          " issuer id %s; update required\n"),
Werner Koch's avatar
Werner Koch committed
1309 1310 1311 1312 1313 1314 1315
                        30, issuer_hash);
              return CRL_CACHE_DONTKNOW;
            }
        }
      else
        {
          log_info (_("force-crl-refresh active for"
1316
                      " issuer id %s; update required\n"),
Werner Koch's avatar
Werner Koch committed
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
                    issuer_hash);
          return CRL_CACHE_DONTKNOW;
        }
    }

  if (entry->invalid)
    {
      log_info (_("available CRL for issuer ID %s can't be used\n"),
                issuer_hash);
      return CRL_CACHE_CANTUSE;
    }

  cdb = lock_db_file (cache, entry);
  if (!cdb)
    return CRL_CACHE_DONTKNOW; /* Hmmm, not the best error code. */
1332

Werner Koch's avatar
Werner Koch committed
1333 1334 1335 1336 1337 1338 1339 1340 1341
  if (!entry->dbfile_checked)
    {
      log_error (_("cached CRL for issuer id %s tampered; we need to update\n")
                 , issuer_hash);
      unlock_db_file (cache, entry);
      return CRL_CACHE_DONTKNOW;
    }

  rc = cdb_find (cdb, sn, snlen);
1342
  if (rc == 1)
Werner Koch's avatar
Werner Koch committed
1343 1344 1345 1346 1347
    {
      n = cdb_datalen (cdb);
      if (n != 16)
        {
          log_error (_("WARNING: invalid cache record length for S/N "));
1348
          log_printf ("0x");
Werner Koch's avatar
Werner Koch committed
1349 1350 1351 1352 1353
          log_printhex ("", sn, snlen);
        }
      else if (opt.verbose)
        {
          unsigned char record[16];
1354
          char *tmp = hexify_data (sn, snlen, 1);
Werner Koch's avatar
Werner Koch committed
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

          if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
            log_error (_("problem reading cache record for S/N %s: %s\n"),
                       tmp, strerror (errno));
          else
            log_info (_("S/N %s is not valid; reason=%02X  date=%.15s\n"),
                      tmp, *record, record+1);
          xfree (tmp);
        }
      retval = CRL_CACHE_INVALID;
    }
  else if (!rc)
    {
      if (opt.verbose)
        {
1370
          char *serialno = hexify_data (sn, snlen, 1);
Werner Koch's avatar
Werner Koch committed
1371 1372 1373 1374 1375 1376
          log_info (_("S/N %s is valid, it is not listed in the CRL\n"),
                    serialno );
          xfree (serialno);
        }
      retval = CRL_CACHE_VALID;
    }
1377
  else
Werner Koch's avatar
Werner Koch committed
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    {
      log_error (_("error getting data from cache file: %s\n"),
                 strerror (errno));
      retval = CRL_CACHE_DONTKNOW;
    }


  if (entry->user_trust_req
      && (retval == CRL_CACHE_VALID || retval == CRL_CACHE_INVALID))
    {
      if (!entry->check_trust_anchor)
        {
          log_error ("inconsistent data on user trust check\n");
          retval = CRL_CACHE_CANTUSE;
        }
      else if (get_istrusted_from_client (ctrl, entry->check_trust_anchor))
        {
          if (opt.verbose)
            log_info ("no system trust and client does not trust either\n");
          retval = CRL_CACHE_CANTUSE;
        }
      else
        {
          /* Okay, the CRL is considered valid by the client and thus
             we can return the result as is.  */
        }
    }

  unlock_db_file (cache, entry);

  return retval;
}


/* Check whether the certificate identified by ISSUER_HASH and
   SERIALNO is valid; i.e. not listed in our cache.  With
   FORCE_REFRESH set to true, a new CRL will be retrieved even if the
   cache has not yet expired.  We use a 30 minutes threshold here so
   that invoking this function several times won't load the CRL over
   and over.  */
1418
crl_cache_result_t
Werner Koch's avatar
Werner Koch committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
crl_cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const char *serialno,
                   int force_refresh)
{
  crl_cache_result_t result;
  unsigned char snbuf_buffer[50];
  unsigned char *snbuf;
  size_t n;

  n = strlen (serialno)/2+1;
  if (n < sizeof snbuf_buffer - 1)
    snbuf = snbuf_buffer;
  else
    {
      snbuf = xtrymalloc (n);
      if (!snbuf)
        return CRL_CACHE_DONTKNOW;
    }

  n = unhexify (snbuf, serialno);

  result = cache_isvalid (ctrl, issuer_hash, snbuf, n, force_refresh);

  if (snbuf != snbuf_buffer)
    xfree (snbuf);

  return result;
1445
}
Werner Koch's avatar
Werner Koch committed
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477


/* Check whether the certificate CERT is valid; i.e. not listed in our
   cache.  With FORCE_REFRESH set to true, a new CRL will be retrieved
   even if the cache has not yet expired.  We use a 30 minutes
   threshold here so that invoking this function several times won't
   load the CRL over and over.  */
gpg_error_t
crl_cache_cert_isvalid (ctrl_t ctrl, ksba_cert_t cert,
                        int force_refresh)
{
  gpg_error_t err;
  crl_cache_result_t result;
  unsigned char issuerhash[20];
  char issuerhash_hex[41];
  ksba_sexp_t serial;
  unsigned char *sn;
  size_t snlen;
  char *endp, *tmp;
  int i;

  /* Compute the hash value of the issuer name.  */
  tmp = ksba_cert_get_issuer (cert, 0);
  if (!tmp)
    {
      log_error ("oops: issuer missing in certificate\n");
      return gpg_error (GPG_ERR_INV_CERT_OBJ);
    }
  gcry_md_hash_buffer (GCRY_MD_SHA1, issuerhash, tmp, strlen (tmp));
  xfree (tmp);
  for (i=0,tmp=issuerhash_hex; i < 20; i++, tmp += 2)
    sprintf (tmp, "%02X", issuerhash[i]);
1478

Werner Koch's avatar
Werner Koch committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
  /* Get the serial number.  */
  serial = ksba_cert_get_serial (cert);
  if (!serial)
    {
      log_error ("oops: S/N missing in certificate\n");
      return gpg_error (GPG_ERR_INV_CERT_OBJ);
    }
  sn = serial;
  if (*sn != '(')
    {
      log_error ("oops: invalid S/N\n");
      xfree (serial);
      return gpg_error (GPG_ERR_INV_CERT_OBJ);
    }
  sn++;
  snlen = strtoul (sn, &endp, 10);
  sn = endp;
  if (*sn != ':')
    {
      log_error ("oops: invalid S/N\n");
      xfree (serial);
      return gpg_error (GPG_ERR_INV_CERT_OBJ);
    }
  sn++;

  /* Check the cache.  */
  result = cache_isvalid (ctrl, issuerhash_hex, sn, snlen, force_refresh);
  switch (result)
    {
    case CRL_CACHE_VALID:
      err = 0;
      break;
    case CRL_CACHE_INVALID:
      err = gpg_error (GPG_ERR_CERT_REVOKED);
      break;
1514
    case CRL_CACHE_DONTKNOW:
Werner Koch's avatar
Werner Koch committed
1515
      err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1516
      break;
1517
    case CRL_CACHE_CANTUSE:
Werner Koch's avatar
Werner Koch committed
1518 1519 1520 1521 1522 1523 1524 1525
      err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
      break;
    default:
      log_fatal ("cache_isvalid returned invalid status code %d\n", result);
    }

  xfree (serial);
  return err;
1526
}
Werner Koch's avatar
Werner Koch committed
1527 1528 1529 1530 1531 1532


/* Prepare a hash context for the signature verification.  Input is
   the CRL and the output is the hash context MD as well as the uses
   algorithm identifier ALGO. */
static gpg_error_t
1533
start_sig_check (ksba_crl_t crl, gcry_md_hd_t *md, int *algo)
Werner Koch's avatar
Werner Koch committed
1534 1535 1536 1537 1538 1539
{
  gpg_error_t err;
  const char *algoid;

  algoid = ksba_crl_get_digest_algo (crl);
  *algo = gcry_md_map_name (algoid);
1540
  if (!*algo)
Werner Koch's avatar
Werner Koch committed
1541
    {
1542
      log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
Werner Koch's avatar
Werner Koch committed
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
      return gpg_error (GPG_ERR_DIGEST_ALGO);
    }

  err = gcry_md_open (md, *algo, 0);
  if (err)
    {
      log_error (_("gcry_md_open for algorithm %d failed: %s\n"),
                 *algo, gcry_strerror (err));
      return err;
    }
  if (DBG_HASHING)
    gcry_md_debug (*md, "hash.cert");

1556
  ksba_crl_set_hash_function (crl, HASH_FNC, *md);
Werner Koch's avatar
Werner Koch committed
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
  return 0;
}


/* Finish a hash context and verify the signature.  This function
   should return 0 on a good signature, GPG_ERR_BAD_SIGNATURE if the
   signature does not verify or any other error code. CRL is the CRL
   object we are working on, MD the hash context and ISSUER_CERT the
   certificate of the CRL issuer.  This function closes MD.  */
static gpg_error_t
finish_sig_check (ksba_crl_t crl, gcry_md_hd_t md, int algo,
                  ksba_cert_t issuer_cert)
{
  gpg_error_t err;
  ksba_sexp_t sigval = NULL, pubkey = NULL;
  const char *s;
  char algoname[50];
  size_t n;
  gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
  unsigned int i;

  /* This also stops debugging on the MD.  */
  gcry_md_final (md);

  /* Get and convert the signature value. */
  sigval = ksba_crl_get_sig_val (crl);
  n = gcry_sexp_canon_len (sigval, 0, NULL, NULL);
1584
  if (!n)
Werner Koch's avatar
Werner Koch committed
1585 1586 1587 1588 1589 1590
    {
      log_error (_("got an invalid S-expression from libksba\n"));
      err = gpg_error (GPG_ERR_INV_SEXP);
      goto leave;
    }
  err = gcry_sexp_sscan (&s_sig, NULL, sigval, n);
1591
  if (err)
Werner Koch's avatar
Werner Koch committed
1592 1593 1594 1595 1596
    {
      log_error (_("converting S-expression failed: %s\n"),
                 gcry_strerror (err));
      goto leave;
    }
1597

Werner Koch's avatar
Werner Koch committed
1598 1599 1600 1601 1602
  /* Get and convert the public key for the issuer certificate. */
  if (DBG_X509)
    dump_cert ("crl_issuer_cert", issuer_cert);
  pubkey = ksba_cert_get_public_key (issuer_cert);
  n = gcry_sexp_canon_len (pubkey, 0, NULL, NULL);
1603
  if (!n)
Werner Koch's avatar
Werner Koch committed
1604 1605 1606 1607 1608 1609
    {
      log_error (_("got an invalid S-expression from libksba\n"));
      err = gpg_error (GPG_ERR_INV_SEXP);
      goto leave;
    }
  err = gcry_sexp_sscan (&s_pkey, NULL, pubkey, n);
1610
  if (err)
Werner Koch's avatar
Werner Koch committed
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    {
      log_error (_("converting S-expression failed: %s\n"),
                 gcry_strerror (err));
      goto leave;
    }

  /* Create an S-expression with the actual hash value. */
  s = gcry_md_algo_name (algo);
  for (i = 0; *s && i < sizeof(algoname) - 1; s++, i++)
    algoname[i] = ascii_tolower (*s);
  algoname[i] = 0;
1622
  err = gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))",
Werner Koch's avatar
Werner Koch committed
1623 1624
                         algoname,
                         gcry_md_get_algo_dlen (algo), gcry_md_read (md, algo));
1625
  if (err)
Werner Koch's avatar
Werner Koch committed
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    {
      log_error (_("creating S-expression failed: %s\n"), gcry_strerror (err));
      goto leave;
    }

  /* Pass this on to the signature verification. */
  err = gcry_pk_verify (s_sig, s_hash, s_pkey);
  if (DBG_X509)
    log_debug ("gcry_pk_verify: %s\n", gpg_strerror (err));

 leave:
  xfree (sigval);
  xfree (pubkey);
  gcry_sexp_release (s_sig);
  gcry_sexp_release (s_hash);
  gcry_sexp_release (s_pkey);
  gcry_md_close (md);

  return err;
}


/* Call this to match a start_sig_check that can not be completed
   normally.  */
static void
abort_sig_check (ksba_crl_t crl, gcry_md_hd_t md)
{
  (void)crl;
  gcry_md_close (md);
}


/* Workhorse of the CRL loading machinery.  The CRL is read using the
   CRL object and stored in the data base file DB with the name FNAME
   (only used for printing error messages).  That DB should be a
   temporary one and not the actual one.  If the function fails the
   caller should delete this temporary database file.  CTRL is
   required to retrieve certificates using the general dirmngr
   callback service.  R_CRLISSUER returns an allocated string with the
   crl-issuer DN, THIS_UPDATE and NEXT_UPDATE are filled with the
   corresponding data from the CRL.  Note that these values might get
   set even if the CRL processing fails at a later step; thus the
   caller should free *R_ISSUER even if the function returns with an
   error.  R_TRUST_ANCHOR is set on exit to NULL or a string with the
   hexified fingerprint of the root certificate, if checking this
   certificate for trustiness is required.
1672 1673
*/
static int
Werner Koch's avatar
Werner Koch committed
1674 1675 1676 1677 1678
crl_parse_insert (ctrl_t ctrl, ksba_crl_t crl,
                  struct cdb_make *cdb, const char *fname,
                  char **r_crlissuer,
                  ksba_isotime_t thisupdate, ksba_isotime_t nextupdate,
                  char **r_trust_anchor)
1679
{
Werner Koch's avatar
Werner Koch committed
1680 1681 1682 1683 1684 1685
  gpg_error_t err;
  ksba_stop_reason_t stopreason;
  ksba_cert_t crlissuer_cert = NULL;
  gcry_md_hd_t md = NULL;
  int algo = 0;
  size_t n;
1686

Werner Koch's avatar
Werner Koch committed
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
  (void)fname;

  *r_crlissuer = NULL;
  *thisupdate = *nextupdate = 0;
  *r_trust_anchor = NULL;

  /* Start of the KSBA parser loop. */
  do
    {
      err = ksba_crl_parse (crl, &stopreason);
      if (err)
        {
          log_error (_("ksba_crl_parse failed: %s\n"), gpg_strerror (err) );
          goto failure;
        }

      switch (stopreason)
        {
        case KSBA_SR_BEGIN_ITEMS:
          {
1707 1708
            err = start_sig_check (crl, &md, &algo);
            if (err)
Werner Koch's avatar
Werner Koch committed
1709
              goto failure;
1710

Werner Koch's avatar
Werner Koch committed
1711 1712 1713 1714
            err = ksba_crl_get_update_times (crl, thisupdate, nextupdate);
            if (err)
              {
                log_error (_("error getting update times of CRL: %s\n"),
1715
                           gpg_strerror (err));
Werner Koch's avatar
Werner Koch committed
1716 1717 1718 1719 1720
                err = gpg_error (GPG_ERR_INV_CRL);
                goto failure;
              }

            if (opt.verbose || !*nextupdate)
1721 1722
              log_info (_("update times of this CRL: this=%s next=%s\n"),
                        thisupdate, nextupdate);
Werner Koch's avatar
Werner Koch committed
1723 1724 1725 1726 1727 1728 1729 1730 1731
            if (!*nextupdate)
              {
                log_info (_("nextUpdate not given; "
                            "assuming a validity period of one day\n"));
                gnupg_copy_time (nextupdate, thisupdate);
                add_seconds_to_isotime (nextupdate, 86400);
              }
          }
          break;
1732

Werner Koch's avatar
Werner Koch committed
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
        case KSBA_SR_GOT_ITEM:
          {
            ksba_sexp_t serial;
            const unsigned char *p;
            ksba_isotime_t rdate;
            ksba_crl_reason_t reason;
            int rc;
            unsigned char record[1+15];

            err = ksba_crl_get_item (crl, &serial, rdate, &reason);
            if (err)
              {
                log_error (_("error getting CRL item: %s\n"),
                           gpg_strerror (err));
                err = gpg_error (GPG_ERR_INV_CRL);
                ksba_free (serial);
                goto failure;
              }
            p = serial_to_buffer (serial, &n);
            if (!p)
              BUG ();
            record[0] = (reason & 0xff);
1755
            memcpy (record+1, rdate, 15);
Werner Koch's avatar
Werner Koch committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
            rc = cdb_make_add (cdb, p, n, record, 1+15);
            if (rc)
              {
                err = gpg_error_from_errno (errno);
                log_error (_("error inserting item into "
                             "temporary cache file: %s\n"),
                           strerror (errno));
                goto failure;
              }

            ksba_free (serial);
          }
          break;
1769

Werner Koch's avatar
Werner Koch committed
1770 1771
        case KSBA_SR_END_ITEMS:
          break;
1772

Werner Koch's avatar
Werner Koch committed
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
        case KSBA_SR_READY:
          {
            char *crlissuer;
            ksba_name_t authid;
            ksba_sexp_t authidsn;
            ksba_sexp_t keyid;

            /* We need to look for the issuer only after having read
               all items.  The issuer itselfs comes before the items
               but the optional authorityKeyIdentifier comes after the
               items. */
            err = ksba_crl_get_issuer (crl, &crlissuer);
            if( err )
              {
                log_error (_("no CRL issuer found in CRL: %s\n"),
                           gpg_strerror (err) );
                err = gpg_error (GPG_ERR_INV_CRL);
                goto failure;
              }
	    /* Note: This should be released by ksba_free, not xfree.
	       May need a memory reallocation dance.  */
            *r_crlissuer = crlissuer; /* (Do it here so we don't need
                                         to free it later) */

            if (!ksba_crl_get_auth_key_id (crl, &keyid, &authid, &authidsn))
              {
                const char *s;

                if (opt.verbose)
                  log_info (_("locating CRL issuer certificate by "
                              "authorityKeyIdentifier\n"));
1804

Werner Koch's avatar
Werner Koch committed
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
                s = ksba_name_enum (authid, 0);
                if (s && *authidsn)
                  crlissuer_cert = find_cert_bysn (ctrl, s, authidsn);
                if (!crlissuer_cert && keyid)
                  crlissuer_cert = find_cert_bysubject (ctrl,
                                                        crlissuer, keyid);

                if (!crlissuer_cert)
                  {
                    log_info ("CRL issuer certificate ");
                    if (keyid)
                      {
                        log_printf ("{");
                        dump_serial (keyid);
                        log_printf ("} ");
                      }
                    if (authidsn)
                      {
                        log_printf ("(#");
                        dump_serial (authidsn);
                        log_printf ("/");
                        dump_string (s);
                        log_printf (") ");
                      }
                    log_printf ("not found\n");
                  }
                ksba_name_release (authid);
                xfree (authidsn);
                xfree (keyid);
              }
            else
              crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, NULL);
            err = 0;
            if (!crlissuer_cert)
              {
                err = gpg_error (GPG_ERR_MISSING_CERT);
                goto failure;
              }
1843

Werner Koch's avatar
Werner Koch committed
1844 1845 1846
            err = finish_sig_check (crl, md, algo, crlissuer_cert);
            if (err)
              {
1847
                log_error (_("CRL signature verification failed: %s\n"),
Werner Koch's avatar
Werner Koch committed
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
                           gpg_strerror (err));
                goto failure;
              }
	    md = NULL;

            err = validate_cert_chain (ctrl, crlissuer_cert, NULL,
                                       VALIDATE_MODE_CRL_RECURSIVE,
                                       r_trust_anchor);
            if (err)
              {
                log_error (_("error checking validity of CRL "
1859
                             "issuer certificate: %s\n"),
Werner Koch's avatar
Werner Koch committed
1860 1861 1862 1863 1864 1865
                           gpg_strerror (err));
                goto failure;
              }

          }
          break;
1866

Werner Koch's avatar
Werner Koch committed
1867 1868 1869 1870 1871
        default:
          log_debug ("crl_parse_insert: unknown stop reason\n");
          err = gpg_error (GPG_ERR_BUG);
          goto failure;
        }
1872
    }
Werner Koch's avatar
Werner Koch committed
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
  while (stopreason != KSBA_SR_READY);
  assert (!err);


 failure:
  if (md)
    abort_sig_check (crl, md);
  ksba_cert_release (crlissuer_cert);
  return err;
}



/* Return the crlNumber extension as an allocated hex string or NULL
   if there is none. */
static char *
get_crl_number (ksba_crl_t crl)
{
  gpg_error_t err;
  ksba_sexp_t number;
  char *string;

  err = ksba_crl_get_crl_number (crl, &number);
  if (err)
    return NULL;
  string = serial_hex (number);
  ksba_free (number);
  return string;
}


/* Return the authorityKeyIdentifier or NULL if it is not available.
   The issuer name may consists of several parts - they are delimted by
   0x01. */
static char *
get_auth_key_id (ksba_crl_t crl, char **serialno)
{
  gpg_error_t err;
  ksba_name_t name;
  ksba_sexp_t sn;
  int idx;
  const char *s;
  char *string;
  size_t length;

  *serialno = NULL;
  err = ksba_crl_get_auth_key_id (crl, NULL, &name, &sn);
  if (err)
    return NULL;
  *serialno = serial_hex (sn);
  ksba_free (sn);

  if (!name)
    return xstrdup ("");
1927

Werner Koch's avatar
Werner Koch committed
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
  length = 0;
  for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
    {
      char *p = ksba_name_get_uri (name, idx);
      length += strlen (p?p:s) + 1;
      xfree (p);
    }
  string = xtrymalloc (length+1);
  if (string)
    {
      *string = 0;
      for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
        {
          char *p = ksba_name_get_uri (name, idx);
          if (*string)
            strcat (string, "\x01");
          strcat (string, p?p:s);
          xfree (p);
        }
    }
  ksba_name_release (name);
  return string;
}



/* Insert the CRL retrieved using URL into the cache specified by
   CACHE.  The CRL itself will be read from the stream FP and is
1956 1957 1958 1959 1960 1961 1962 1963 1964