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