1
0

dec.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
  2. /*
  3. * Copyright 2017 Red Hat, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #include "b64.h"
  18. #include <ctype.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #define SUMMARY "Decodes URL-safe Base64 data to binary"
  22. static const char *prefix = "jose b64 dec -i B64 [-O BIN]\n\n" SUMMARY;
  23. static const jcmd_doc_t doc_input[] = {
  24. { .arg = "FILE", .doc="Read Base64 (URL-safe) data from FILE" },
  25. { .arg = "-", .doc="Read Base64 (URL-safe) data from standard input" },
  26. {}
  27. };
  28. static const jcmd_doc_t doc_output[] = {
  29. { .arg = "FILE", .doc="Write binary data to FILE" },
  30. { .arg = "-", .doc="Write binary data to standard output" },
  31. {}
  32. };
  33. static const jcmd_cfg_t cfgs[] = {
  34. {
  35. .opt = { "base64", required_argument, .val = 'i' },
  36. .off = offsetof(jcmd_b64_opt_t, input),
  37. .set = jcmd_opt_set_ifile,
  38. .doc = doc_input,
  39. },
  40. {
  41. .opt = { "binary", required_argument, .val = 'O' },
  42. .off = offsetof(jcmd_b64_opt_t, output),
  43. .set = jcmd_opt_set_ofile,
  44. .doc = doc_output,
  45. .def = "-",
  46. },
  47. {}
  48. };
  49. static int
  50. jcmd_b64_dec(int argc, char *argv[])
  51. {
  52. jcmd_b64_opt_auto_t opt = {};
  53. jose_io_auto_t *b64 = NULL;
  54. jose_io_auto_t *out = NULL;
  55. if (!jcmd_opt_parse(argc, argv, cfgs, &opt, prefix))
  56. return EXIT_FAILURE;
  57. if (!opt.input) {
  58. fprintf(stderr, "Input not specified!\n");
  59. return EXIT_FAILURE;
  60. }
  61. out = jose_io_file(NULL, opt.output);
  62. if (!out)
  63. return EXIT_FAILURE;
  64. b64 = jose_b64_dec_io(out);
  65. if (!b64)
  66. return EXIT_FAILURE;
  67. for (int c = fgetc(opt.input); c != EOF; c = fgetc(opt.input)) {
  68. uint8_t b = c;
  69. if (isspace(c))
  70. continue;
  71. if (!b64->feed(b64, &b, sizeof(b)))
  72. return EXIT_FAILURE;
  73. }
  74. if (!b64->done(b64))
  75. return EXIT_FAILURE;
  76. return EXIT_SUCCESS;
  77. }
  78. JCMD_REGISTER(SUMMARY, jcmd_b64_dec, "b64", "dec")