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 <sys/stat.h>
16 #include <gmssl/cms.h>
17 #include <gmssl/x509.h>
18 #include <gmssl/rand.h>
19
20
21 static const char *options = "-in file";
22
cmsparse_main(int argc,char ** argv)23 int cmsparse_main(int argc, char **argv)
24 {
25 int ret = 1;
26 char *prog = argv[0];
27 char *infile = NULL;
28 FILE *infp = stdin;
29 struct stat st;
30 uint8_t *cms = NULL;
31 size_t cms_maxlen, cmslen;
32
33 argc--;
34 argv++;
35
36 if (argc < 1) {
37 fprintf(stderr, "usage: %s %s\n", prog, options);
38 return 1;
39 }
40 while (argc > 1) {
41 if (!strcmp(*argv, "-help")) {
42 printf("usage: %s %s\n", prog, options);
43 ret = 0;
44 goto end;
45 } else if (!strcmp(*argv, "-in")) {
46 if (--argc < 1) goto bad;
47 infile = *(++argv);
48 if (!(infp = fopen(infile, "r"))) {
49 fprintf(stderr, "%s: open '%s' failure : %s\n", prog, infile, strerror(errno));
50 goto end;
51 }
52 } else {
53 fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
54 goto end;
55 bad:
56 fprintf(stderr, "%s: '%s' option value missing\n", prog, *argv);
57 goto end;
58 }
59
60 argc--;
61 argv++;
62 }
63
64 if (!infile) {
65 fprintf(stderr, "%s: option '-in' required'\n", prog);
66 goto end;
67 }
68
69 if (fstat(fileno(infp), &st) < 0) {
70 fprintf(stderr, "%s: access '%s' failed : %s\n", prog, infile, strerror(errno));
71 goto end;
72 }
73 cms_maxlen = (st.st_size * 3)/4 + 1;
74 if (!(cms = malloc(cms_maxlen))) {
75 fprintf(stderr, "%s: malloc failure\n", prog);
76 goto end;
77 }
78 if (cms_from_pem(cms, &cmslen, cms_maxlen, infp) != 1) {
79 fprintf(stderr, "%s: parse CMS error\n", prog);
80 goto end;
81 }
82 cms_print(stdout, 0, 0, "CMS", cms, cmslen);
83 ret = 0;
84 end:
85 if (infp) fclose(infp);
86 if (cms) free(cms);
87 return ret;
88 }
89