base64.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * QEMU base64 helpers
  3. *
  4. * Copyright (c) 2015 Red Hat, Inc.
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. #include "qemu/osdep.h"
  21. #include "qapi/error.h"
  22. #include "qemu/base64.h"
  23. static const char *base64_valid_chars =
  24. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n";
  25. uint8_t *qbase64_decode(const char *input,
  26. size_t in_len,
  27. size_t *out_len,
  28. Error **errp)
  29. {
  30. *out_len = 0;
  31. if (in_len != -1) {
  32. /* Lack of NUL terminator is an error */
  33. if (input[in_len] != '\0') {
  34. error_setg(errp, "Base64 data is not NUL terminated");
  35. return NULL;
  36. }
  37. /* Check there's no NULs embedded since we expect
  38. * this to be valid base64 data */
  39. if (memchr(input, '\0', in_len) != NULL) {
  40. error_setg(errp, "Base64 data contains embedded NUL characters");
  41. return NULL;
  42. }
  43. /* Now we know its a valid nul terminated string
  44. * strspn is safe to use... */
  45. } else {
  46. in_len = strlen(input);
  47. }
  48. if (strspn(input, base64_valid_chars) != in_len) {
  49. error_setg(errp, "Base64 data contains invalid characters");
  50. return NULL;
  51. }
  52. return g_base64_decode(input, out_len);
  53. }