• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the License); you may
5  *  not use this file except in compliance with the License.
6  *
7  *  http://www.apache.org/licenses/LICENSE-2.0
8  */
9 
10 
11 #include <stdio.h>
12 #include <errno.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <gmssl/pem.h>
16 #include <gmssl/x509.h>
17 
18 
19 static const char *options = "[-in file] [-out file]";
20 
certparse_main(int argc,char ** argv)21 int certparse_main(int argc, char **argv)
22 {
23 	int ret = 1;
24 	char *prog = argv[0];
25 	char *infile = NULL;
26 	char *outfile = NULL;
27 	FILE *infp = stdin;
28 	FILE *outfp = stdout;
29 	uint8_t cert[18192];
30 	size_t certlen;
31 
32 	argc--;
33 	argv++;
34 
35 	while (argc > 0) {
36 		if (!strcmp(*argv, "-help")) {
37 			printf("usage: %s %s\n", prog, options);
38 			goto end;
39 		} else if (!strcmp(*argv, "-in")) {
40 			if (--argc < 1) goto bad;
41 			infile = *(++argv);
42 			if (!(infp = fopen(infile, "r"))) {
43 				fprintf(stderr, "%s: open '%s' failure : %s\n", prog, infile, strerror(errno));
44 				goto end;
45 			}
46 		} else if (!strcmp(*argv, "-out")) {
47 			if (--argc < 1) goto bad;
48 			outfile = *(++argv);
49 			if (!(outfp = fopen(outfile, "w"))) {
50 				fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
51 				goto end;
52 			}
53 		} else {
54 			fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
55 			goto end;
56 bad:
57 			fprintf(stderr, "%s: '%s' option value missing\n", prog, *argv);
58 			goto end;
59 		}
60 
61 		argc--;
62 		argv++;
63 	}
64 
65 	for (;;) {
66 		int rv;
67 		if ((rv = x509_cert_from_pem(cert, &certlen, sizeof(cert), infp)) != 1) {
68 			if (rv < 0) fprintf(stderr, "%s: read certificate failure\n", prog);
69 			else ret = 0;
70 			goto end;
71 		}
72 		x509_cert_print(outfp, 0, 0, "Certificate", cert, certlen);
73 		if (x509_cert_to_pem(cert, certlen, outfp) != 1) {
74 			fprintf(stderr, "%s: output certficate failure\n", prog);
75 			goto end;
76 		}
77 	}
78 
79 end:
80 	if (infile && infp) fclose(infp);
81 	if (outfile && outfp) fclose(outfp);
82 	return ret;
83 }
84