reqparse.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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/x509.h>
  14. #include <gmssl/x509_req.h>
  15. static const char *options = "[-in file] [-out file]";
  16. int reqparse_main(int argc, char **argv)
  17. {
  18. int ret = 1;
  19. char *prog = argv[0];
  20. char *infile = NULL;
  21. char *outfile = NULL;
  22. FILE *infp = stdin;
  23. FILE *outfp = stdout;
  24. uint8_t req[1024];
  25. size_t reqlen;
  26. argc--;
  27. argv++;
  28. while (argc > 0) {
  29. if (!strcmp(*argv, "-help")) {
  30. printf("usage: %s %s\n", prog, options);
  31. goto end;
  32. } else if(!strcmp(*argv, "-in")) {
  33. if (--argc < 1) goto bad;
  34. infile = *(++argv);
  35. if (!(infp = fopen(infile, "rb"))) {
  36. fprintf(stderr, "%s: open '%s' failure : %s\n", prog, infile, strerror(errno));
  37. goto end;
  38. }
  39. } else if (!strcmp(*argv, "-out")) {
  40. if (--argc < 1) goto bad;
  41. outfile = *(++argv);
  42. if (!(outfp = fopen(outfile, "wb"))) {
  43. fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
  44. goto end;
  45. }
  46. } else {
  47. fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
  48. goto end;
  49. bad:
  50. fprintf(stderr, "%s: '%s' option value missing\n", prog, *argv);
  51. goto end;
  52. }
  53. argc--;
  54. argv++;
  55. }
  56. if (x509_req_from_pem(req, &reqlen, sizeof(req), infp) != 1) {
  57. fprintf(stderr, "%s: read CSR failure\n", prog);
  58. goto end;
  59. }
  60. x509_req_print(outfp, 0, 0, "CertificationRequest", req, reqlen);
  61. if (x509_req_to_pem(req, reqlen, outfp) != 1) {
  62. fprintf(stderr, "%s: output CSR failure\n", prog);
  63. goto end;
  64. }
  65. ret = 0;
  66. end:
  67. if (infile && infp) fclose(infp);
  68. if (outfile && outfp) fclose(outfp);
  69. return ret;
  70. }