blob: 8aa2a5b3ac68c0c42981cdac64d17d7868235f7e [file] [log] [blame]
Daniel P. Berrange89bc0b62015-11-23 15:24:50 +00001/*
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
Peter Maydellaafd7582016-01-29 17:49:55 +000021#include "qemu/osdep.h"
Daniel P. Berrange89bc0b62015-11-23 15:24:50 +000022#include <config-host.h>
23
24#include "qemu/base64.h"
25
26static const char *base64_valid_chars =
27 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n";
28
29uint8_t *qbase64_decode(const char *input,
30 size_t in_len,
31 size_t *out_len,
32 Error **errp)
33{
34 *out_len = 0;
35
36 if (in_len != -1) {
37 /* Lack of NUL terminator is an error */
38 if (input[in_len] != '\0') {
39 error_setg(errp, "Base64 data is not NUL terminated");
40 return NULL;
41 }
42 /* Check there's no NULs embedded since we expect
43 * this to be valid base64 data */
44 if (memchr(input, '\0', in_len) != NULL) {
45 error_setg(errp, "Base64 data contains embedded NUL characters");
46 return NULL;
47 }
48
49 /* Now we know its a valid nul terminated string
50 * strspn is safe to use... */
51 } else {
52 in_len = strlen(input);
53 }
54
55 if (strspn(input, base64_valid_chars) != in_len) {
56 error_setg(errp, "Base64 data contains invalid characters");
57 return NULL;
58 }
59
60 return g_base64_decode(input, out_len);
61}