cmsparse.c 1.9 KB

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