xref: /plan9/sys/src/cmd/auth/pemdecode.c (revision 51711cb6a91a3f2a5be5c3246334b85a608f135b)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <mp.h>
5 #include <libsec.h>
6 
7 void
usage(void)8 usage(void)
9 {
10 	fprint(2, "auth/pemdecode section [file]\n");
11 	exits("usage");
12 }
13 
14 void
main(int argc,char ** argv)15 main(int argc, char **argv)
16 {
17 	char *buf;
18 	uchar *bin;
19 	int fd;
20 	long n, tot;
21 	int len;
22 	char *tag, *file;
23 
24 	ARGBEGIN{
25 	default:
26 		usage();
27 	}ARGEND
28 
29 	if(argc != 1 && argc != 2)
30 		usage();
31 
32 	tag = argv[0];
33 	if(argc == 2)
34 		file = argv[1];
35 	else
36 		file = "#d/0";
37 
38 	if((fd = open(file, OREAD)) < 0)
39 		sysfatal("open %s: %r", file);
40 	buf = nil;
41 	tot = 0;
42 	for(;;){
43 		buf = realloc(buf, tot+8192);
44 		if(buf == nil)
45 			sysfatal("realloc: %r");
46 		if((n = read(fd, buf+tot, 8192)) < 0)
47 			sysfatal("read: %r");
48 		if(n == 0)
49 			break;
50 		tot += n;
51 	}
52 	buf[tot] = 0;
53 	bin = decodePEM(buf, tag, &len, nil);
54 	if(bin == nil)
55 		sysfatal("cannot extract section '%s' from pem", tag);
56 	if((n=write(1, bin, len)) != len)
57 		sysfatal("writing %d bytes got %ld: %r", len, n);
58 	exits(0);
59 }
60