2 * uclient - ustream based protocol client library
4 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 #include <libubox/md5.h>
24 #include <libubox/utils.h>
26 #include "uclient-utils.h"
28 static const char *b64 =
29 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
31 void base64_encode(const void *inbuf, unsigned int len, void *outbuf)
33 unsigned char *out = outbuf;
34 const uint8_t *in = inbuf;
38 for (i = 0; i < len - pad; i += 3) {
39 uint32_t in3 = (in[0] << 16) | (in[1] << 8) | in[2];
42 for (k = 3; k >= 0; k--) {
43 out[k] = b64[in3 & 0x3f];
51 uint32_t in2 = in[0] << (16 - 6);
56 in2 |= in[1] << (8 - 6);
57 out[2] = b64[in2 & 0x3f];
63 out[1] = b64[in2 & 0x3f];
65 out[0] = b64[in2 & 0x3f];
73 int uclient_urldecode(const char *in, char *out, bool decode_plus)
79 while ((c = *(in++))) {
81 if (!isxdigit(in[0]) || !isxdigit(in[1]))
86 c = strtol(dec, NULL, 16);
88 } else if (decode_plus && c == '+') {
100 static char hex_digit(char val)
102 val += val > 9 ? 'a' - 10 : '0';
106 void bin_to_hex(char *dest, const void *buf, int len)
108 const uint8_t *data = buf;
111 for (i = 0; i < len; i++) {
112 *(dest++) = hex_digit(data[i] >> 4);
113 *(dest++) = hex_digit(data[i] & 0xf);
118 static void http_create_hash(char *dest, const char * const * str, int n_str)
125 for (i = 0; i < n_str; i++) {
127 md5_hash(":", 1, &md5);
128 md5_hash(str[i], strlen(str[i]), &md5);
131 bin_to_hex(dest, &hash, sizeof(hash));
134 void http_digest_calculate_auth_hash(char *dest, const char *user, const char *realm, const char *password)
136 const char *hash_str[] = {
142 http_create_hash(dest, hash_str, ARRAY_SIZE(hash_str));
145 void http_digest_calculate_response(char *dest, const struct http_digest_data *data)
147 const char *h_a2_strings[] = {
151 const char *resp_strings[] = {
157 dest, /* initialized to H(A2) first */
160 http_create_hash(dest, h_a2_strings, ARRAY_SIZE(h_a2_strings));
161 http_create_hash(dest, resp_strings, ARRAY_SIZE(resp_strings));