• 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/x509.h>
16 #include <gmssl/x509_req.h>
17 
18 
19 static const char *options = "[-in file] [-out file]";
20 
reqparse_main(int argc,char ** argv)21 int reqparse_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 req[1024];
30 	size_t reqlen;
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 	if (x509_req_from_pem(req, &reqlen, sizeof(req), infp) != 1) {
66 		fprintf(stderr, "%s: read CSR failure\n", prog);
67 		goto end;
68 	}
69 	x509_req_print(outfp, 0, 0, "CertificationRequest", req, reqlen);
70 	if (x509_req_to_pem(req, reqlen, outfp) != 1) {
71 		fprintf(stderr, "%s: output CSR failure\n", prog);
72 		goto end;
73 	}
74 	ret = 0;
75 end:
76 	if (infile && infp) fclose(infp);
77 	if (outfile && outfp) fclose(outfp);
78 	return ret;
79 }
80