plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

pemdecode.c (953B)


      1 #include <u.h>
      2 #include <libc.h>
      3 #include <bio.h>
      4 #include <mp.h>
      5 #include <libsec.h>
      6 
      7 void
      8 usage(void)
      9 {
     10 	fprint(2, "auth/pemdecode section [file]\n");
     11 	exits("usage");
     12 }
     13 
     14 void
     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 = "/dev/stdin";
     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 }