1
0

enc.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 <string.h>
  19. #include <unistd.h>
  20. #define SUMMARY "Encodes binary data to URL-safe Base64"
  21. static const char *prefix = "jose b64 enc -I BIN [-o B64]\n\n" SUMMARY;
  22. static const jcmd_doc_t doc_input[] = {
  23. { .arg = "FILE", .doc="Read binary data from FILE" },
  24. { .arg = "-", .doc="Read binary data from standard input" },
  25. {}
  26. };
  27. static const jcmd_doc_t doc_output[] = {
  28. { .arg = "FILE", .doc="Write Base64 (URL-safe) to FILE" },
  29. { .arg = "-", .doc="Write Base64 (URL-safe) to standard output" },
  30. {}
  31. };
  32. static const jcmd_cfg_t cfgs[] = {
  33. {
  34. .opt = { "binary", required_argument, .val = 'I' },
  35. .off = offsetof(jcmd_b64_opt_t, input),
  36. .set = jcmd_opt_set_ifile,
  37. .doc = doc_input,
  38. },
  39. {
  40. .opt = { "base64", required_argument, .val = 'o' },
  41. .off = offsetof(jcmd_b64_opt_t, output),
  42. .set = jcmd_opt_set_ofile,
  43. .doc = doc_output,
  44. .def = "-",
  45. },
  46. {}
  47. };
  48. static int
  49. jcmd_b64_enc(int argc, char *argv[])
  50. {
  51. jcmd_b64_opt_auto_t opt = {};
  52. jose_io_auto_t *b64 = NULL;
  53. jose_io_auto_t *out = NULL;
  54. if (!jcmd_opt_parse(argc, argv, cfgs, &opt, prefix))
  55. return EXIT_FAILURE;
  56. if (!opt.input) {
  57. fprintf(stderr, "Input not specified!\n");
  58. return EXIT_FAILURE;
  59. }
  60. out = jose_io_file(NULL, opt.output);
  61. if (!out)
  62. return EXIT_FAILURE;
  63. b64 = jose_b64_enc_io(out);
  64. if (!b64)
  65. return EXIT_FAILURE;
  66. for (int c = fgetc(opt.input); c != EOF; c = fgetc(opt.input)) {
  67. uint8_t b = c;
  68. if (!b64->feed(b64, &b, sizeof(b)))
  69. return EXIT_FAILURE;
  70. }
  71. if (!b64->done(b64))
  72. return EXIT_FAILURE;
  73. if (isatty(fileno(opt.output)))
  74. fprintf(opt.output, "\n");
  75. return EXIT_SUCCESS;
  76. }
  77. JCMD_REGISTER(SUMMARY, jcmd_b64_enc, "b64", "enc")