+static bool read_pem(FILE *fp, const char *type, void *vbuf, size_t size) {
+ char line[1024];
+ bool data = false;
+ size_t typelen = strlen(type);
+ char *buf = vbuf;
+
+ while(fgets(line, sizeof(line), fp)) {
+ if(!data) {
+ if(strncmp(line, "-----BEGIN ", 11)) {
+ continue;
+ }
+
+ if(strncmp(line + 11, type, typelen)) {
+ continue;
+ }
+
+ data = true;
+ continue;
+ }
+
+ if(!strncmp(line, "-----END ", 9)) {
+ break;
+ }
+
+ size_t linelen = strcspn(line, "\r\n");
+ size_t len = b64decode_tinc(line, line, linelen);
+
+ if(!len) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Invalid base64 data in PEM file\n");
+ errno = EINVAL;
+ return false;
+ }
+
+ if(len > size) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Too much base64 data in PEM file\n");
+ errno = EINVAL;
+ return false;
+ }
+
+ memcpy(buf, line, len);
+ buf += len;
+ size -= len;
+ }
+
+ if(size) {
+ if(data) {
+ errno = EINVAL;
+ logger(DEBUG_ALWAYS, LOG_ERR, "Too little base64 data in PEM file\n");
+ } else {
+ errno = ENOENT;
+ }
+
+ return false;
+ }
+
+ return true;
+}
+