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