Update date in copyrights
[src/app-framework-main.git] / src / wgtpkg-certs.c
1 /*
2  Copyright (C) 2015-2019 IoT.bzh
3
4  author: José Bollo <jose.bollo@iot.bzh>
5
6  Licensed under the Apache License, Version 2.0 (the "License");
7  you may not use this file except in compliance with the License.
8  You may obtain a copy of the License at
9
10      http://www.apache.org/licenses/LICENSE-2.0
11
12  Unless required by applicable law or agreed to in writing, software
13  distributed under the License is distributed on an "AS IS" BASIS,
14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  See the License for the specific language governing permissions and
16  limitations under the License.
17 */
18
19
20 #include <openssl/x509.h>
21
22 #include "verbose.h"
23 #include "wgtpkg-certs.h"
24 #include "wgtpkg-base64.h"
25
26 struct x509l {
27         unsigned count;
28         X509 **certs;
29 };
30
31 static struct x509l certificates = { .count = 0, .certs = NULL };
32
33 static int add_certificate_x509(X509 *x)
34 {
35         X509 **p = realloc(certificates.certs,
36                         (certificates.count + 1) * sizeof(X509*));
37         if (!p) {
38                 ERROR("reallocation failed for certificate");
39                 return -1;
40         }
41         certificates.certs = p;
42         p[certificates.count++] = x;
43         return 0;
44 }
45
46 static int add_certificate_bin(const char *bin, size_t len)
47 {
48         int rc;
49         const char *b, *e;
50         b = bin;
51         e = bin + len;
52         while (b < e) {
53                 X509 *x =  d2i_X509(NULL, (const unsigned char **)&b, e-b);
54                 if (x == NULL) {
55                         ERROR("d2i_X509 failed");
56                         return -1;
57                 }
58                 rc = add_certificate_x509(x);
59                 if (rc) {
60                         X509_free(x);
61                         return rc;
62                 }
63         }
64         return 0;
65 }
66
67 int add_certificate_b64(const char *b64)
68 {
69         char *d;
70         ssize_t l = base64dec(b64, &d);
71         int rc;
72         if (l < 0)
73                 rc = -1;
74         else {
75                 rc = add_certificate_bin(d, (size_t)l);
76                 free(d);
77         }
78         return rc;
79 }
80
81 void clear_certificates()
82 {
83         while(certificates.count)
84                 X509_free(certificates.certs[--certificates.count]);
85 }
86
87