xref: /plan9/sys/src/cmd/unix/drawterm/libsec/readcert.c (revision 8ccd4a6360d974db7bd7bbd4f37e7018419ea908)
1 #include <u.h>
2 #include <libc.h>
3 #include <mp.h>
4 #include <libsec.h>
5 
6 static char*
readfile(char * name)7 readfile(char *name)
8 {
9 	int fd;
10 	char *s;
11 	Dir *d;
12 
13 	fd = open(name, OREAD);
14 	if(fd < 0)
15 		return nil;
16 	if((d = dirfstat(fd)) == nil)
17 		return nil;
18 	s = malloc(d->length + 1);
19 	if(s == nil || readn(fd, s, d->length) != d->length){
20 		free(s);
21 		free(d);
22 		close(fd);
23 		return nil;
24 	}
25 	close(fd);
26 	s[d->length] = '\0';
27 	free(d);
28 	return s;
29 }
30 
31 uchar*
readcert(char * filename,int * pcertlen)32 readcert(char *filename, int *pcertlen)
33 {
34 	char *pem;
35 	uchar *binary;
36 
37 	pem = readfile(filename);
38 	if(pem == nil){
39 		werrstr("can't read %s", filename);
40 		return nil;
41 	}
42 	binary = decodepem(pem, "CERTIFICATE", pcertlen);
43 	free(pem);
44 	if(binary == nil){
45 		werrstr("can't parse %s", filename);
46 		return nil;
47 	}
48 	return binary;
49 }
50 
51