summaryrefslogtreecommitdiff
path: root/src/sbearssl/sbearssl_ta_readdir.c
blob: de39eca3b972a94f2b9053543fc25e54f1347414 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
56
57
58
59
60
61
62
63
64
/* ISC license. */

#include <sys/types.h>
#include <errno.h>
#include <skalibs/bytestr.h>
#include <skalibs/stralloc.h>
#include <skalibs/genalloc.h>
#include <skalibs/direntry.h>
#include <skalibs/djbunix.h>
#include <s6-networking/sbearssl.h>

int sbearssl_ta_readdir (char const *dirfn, genalloc *taga, stralloc *tasa)
{
  size_t tasabase = tasa->len ;
  size_t tagabase = genalloc_len(sbearssl_ta, taga) ;
  size_t dirfnlen = str_len(dirfn) ;
  int tasawasnull = !tasa->s ;
  int tagawasnull = !genalloc_s(sbearssl_ta, taga) ;
  stralloc certsa = STRALLOC_ZERO ;
  genalloc certga = GENALLOC_ZERO ;
  DIR *dir = opendir(dirfn) ;
  if (!dir) return -1 ;

  for (;;)
  {
    direntry *d ;
    errno = 0 ;
    d = readdir(dir) ;
    if (!d) break ;
    if (d->d_name[0] == '.') continue ;
    {
      size_t dlen = str_len(d->d_name) ;
      char fn[dirfnlen + dlen + 2] ;
      byte_copy(fn, dirfnlen, dirfn) ;
      fn[dirfnlen] = '/' ;
      byte_copy(fn + dirfnlen + 1, dlen, d->d_name) ;
      fn[dirfnlen + 1 + dlen] = 0 ;
      genalloc_setlen(sbearssl_cert, &certga, 0) ;
      certsa.len = 0 ;
      if (sbearssl_cert_readfile(fn, &certga, &certsa)) continue ;
    }
    sbearssl_ta_certs(taga, tasa, genalloc_s(sbearssl_cert, &certga), genalloc_len(sbearssl_cert, &certga), certsa.s) ;
  }
  if (errno) goto fail ;

  dir_close(dir) ;
  genalloc_free(sbearssl_cert, &certga) ;
  stralloc_free(&certsa) ;
  return 0 ;

 fail:
  {
    int e = errno ;
    dir_close(dir) ;
    genalloc_free(sbearssl_cert, &certga) ;
    stralloc_free(&certsa) ;
    if (tagawasnull) genalloc_free(sbearssl_ta, taga) ;
    else genalloc_setlen(sbearssl_ta, taga, tagabase) ;
    if (tasawasnull) stralloc_free(tasa) ;
    else tasa->len = tasabase ;
    errno = e ;
  }
  return -1 ;
}