s4:heimdal: import lorikeet-heimdal-202201172009 (commit 5a0b45cd723628b3690ea848548b...
[samba.git] / source4 / heimdal / lib / roken / base32.c
1 /*
2  * Copyright (c) 2020 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include <config.h>
35
36 #include <errno.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <limits.h>
40 #ifdef TEST
41 #include <stdio.h>
42 #include <getarg.h>
43 #include <err.h>
44 #endif
45 #include "base32.h"
46 #include "roken.h"
47
48 static const unsigned char base32_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
49 static const unsigned char base32op_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
50
51 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
52 rk_base32_encode(const void *data, int size, char **str, enum rk_base32_flags flags)
53 {
54     const unsigned char *chars =
55         (flags & RK_BASE32_FLAG_PRESERVE_ORDER) ? base32op_chars :
56                                                   base32_chars;
57     uint64_t c;
58     char *s, *p;
59     int i;
60     const unsigned char *q;
61
62     if (size > INT_MAX/8 || size < 0) {
63         *str = NULL;
64         errno = ERANGE;
65         return -1;
66     }
67
68     p = s = malloc(((size + 5 - 1) / 5) * 8 + 1);
69     if (p == NULL) {
70         *str = NULL;
71         return -1;
72     }
73     q = (const unsigned char *) data;
74
75     for (i = 0; i < size;) {
76         /* 5 bytes of input will give us 8 output bytes' worth of bits */
77         c = q[i++];
78         c <<= 8;
79         if (i < size)
80             c += q[i];
81         i++;
82         c <<= 8;
83         if (i < size)
84             c += q[i];
85         i++;
86         c <<= 8;
87         if (i < size)
88             c += q[i];
89         i++;
90         c <<= 8;
91         if (i < size)
92             c += q[i];
93         i++;
94         p[0] = chars[(c & 0x00000000f800000000ULL) >> 35];
95         p[1] = chars[(c & 0x0000000007c0000000ULL) >> 30];
96         p[2] = chars[(c & 0x00000000003e000000ULL) >> 25];
97         p[3] = chars[(c & 0x000000000001f00000ULL) >> 20];
98         p[4] = chars[(c & 0x0000000000000f8000ULL) >> 15];
99         p[5] = chars[(c & 0x000000000000007c00ULL) >> 10];
100         p[6] = chars[(c & 0x0000000000000003e0ULL) >> 5];
101         p[7] = chars[(c & 0x00000000000000001fULL) >> 0];
102         switch (i - size) {
103         case 4: p[2] = p[3] = '=';  /*fallthrough*/
104         case 3: p[4] = '=';         /*fallthrough*/
105         case 2: p[5] = p[6] = '=';  /*fallthrough*/
106         case 1: p[7] = '=';         /*fallthrough*/
107         default:                    break;
108         }
109         p += 8;
110     }
111     *p = 0;
112     *str = s;
113     return (int) strlen(s);
114 }
115
116 #define DECODE_ERROR ((uint64_t)-1)
117
118 static int
119 pos(char c, int preserve_order)
120 {
121     /* EBCDIC need not apply */
122     if (preserve_order) {
123         if (c >= '0' && c <= '9')
124             return c - '0';
125         if (c >= 'A' && c <= 'V')
126             return c - 'A' + ('9' - '0') + 1;
127     } else {
128         if (c >= 'A' && c <= 'Z')
129             return c - 'A';
130         if (c >= '2' && c <= '7')
131             return c - '2' + ('Z' - 'A') + 1;
132     }
133     return -1;
134 }
135
136 static uint64_t
137 token_decode(const char *token, enum rk_base32_flags flags)
138 {
139     uint64_t marker = 0;
140     uint64_t val = 0;
141     int preserve_order = !!(flags & RK_BASE32_FLAG_PRESERVE_ORDER);
142     int i, c;
143
144     if (strlen(token) < 8)
145         return DECODE_ERROR;
146     for (i = 0; i < 8; i++) {
147         val <<= 5;
148         if (token[i] == '=')
149             marker++;
150         else if (marker)
151             return DECODE_ERROR;
152         else if ((c = pos(token[i], preserve_order)) == -1 &&
153             (flags & RK_BASE32_FLAG_STOP_ON_GARBAGE))
154             break;
155         else if (c == -1)
156             return DECODE_ERROR;
157         else
158             val |= c;
159     }
160     if (marker > 6)
161         return DECODE_ERROR;
162     return (marker << 40) | val;
163 }
164
165 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
166 rk_base32_decode(const char *str, void *data, enum rk_base32_flags flags)
167 {
168     const char *p;
169     unsigned char *q;
170     int preserve_order = !!(flags & RK_BASE32_FLAG_PRESERVE_ORDER);
171
172     q = data;
173     for (p = str; *p && (*p == '=' || pos(*p, preserve_order) != -1); p += 8) {
174         uint64_t val = token_decode(p, flags);
175         uint64_t marker = (val >> 40) & 0xffULL;
176
177         if (val == DECODE_ERROR) {
178             errno = EINVAL;
179             return -1;
180         }
181         *q++ = (val >> 32) & 0xffULL;
182         if (marker < 6)
183             *q++ = (val >> 24) & 0xffULL;
184         if (marker < 4)
185             *q++ = (val >> 16) & 0xffULL;
186         if (marker < 3)
187             *q++ = (val >> 8) & 0xffULL;
188         if (marker < 1)
189             *q++ = val & 0xffULL;
190         if (marker && !(flags & RK_BASE32_FLAG_INTERIOR_PADDING_OK))
191             break;
192     }
193     if (q - (unsigned char *) data > INT_MAX) {
194         errno = EOVERFLOW;
195         return -1;
196     }
197     return q - (unsigned char *) data;
198 }
199
200 #ifdef TEST
201 static int interior_padding_ok;
202 static int preserve_order_flag;
203 static int stop_on_garbage;
204 static int decode_flag;
205 static int help_flag;
206
207 /*
208  * The short options are compatible with a subset of the FreeBSD contrib
209  * vis(1).  Heimdal additions have long option names only.
210  */
211 static struct getargs args[] = {
212     { "preserve-order", 'P', arg_flag, &preserve_order_flag,
213         "Use order-preserving alphabet", NULL },
214     { "interior-padding-ok", 'O', arg_flag, &interior_padding_ok,
215         "Decode concatenated padded base32 strings as one", NULL },
216     { "stop-on-garbage", 'G', arg_flag, &stop_on_garbage,
217         "Do not error on garbage", NULL },
218     { "decode", 'd', arg_flag, &decode_flag, "Decode", NULL },
219     { "help", 'h', arg_flag, &help_flag, "Print help message", NULL },
220 };
221 static size_t num_args = sizeof(args)/sizeof(args[0]);
222
223 int
224 main(int argc, char **argv)
225 {
226     enum rk_base32_flags flags = 0;
227     unsigned char *buf = NULL;
228     size_t buflen = 0;
229     size_t bufsz = 0;
230     int goptind = 0;
231     int ret;
232
233     setprogname("rkbase32");
234     if (getarg(args, num_args, argc, argv, &goptind) || help_flag) {
235         arg_printusage(args, num_args, NULL, "FILE | -");
236         return help_flag ? 0 : 1;
237     }
238
239     argc -= goptind;
240     argv += goptind;
241
242     flags |= preserve_order_flag ? RK_BASE32_FLAG_PRESERVE_ORDER : 0;
243     flags |= interior_padding_ok ? RK_BASE32_FLAG_INTERIOR_PADDING_OK : 0;
244     flags |= stop_on_garbage ? RK_BASE32_FLAG_STOP_ON_GARBAGE : 0;
245
246     if (help_flag)
247         return arg_printusage(args, num_args, NULL, "FILE | -- -"), 0;
248     if (argc != 1)
249         return arg_printusage(args, num_args, NULL, "FILE | -- -"), 1;
250
251     if (strcmp(argv[0], "-") == 0) {
252         unsigned char *tmp;
253         unsigned char d[4096];
254         size_t bytes;
255
256         while (!feof(stdin) && !ferror(stdin)) {
257             bytes = fread(d, 1, sizeof(d), stdin);
258             if (bytes == 0)
259                 continue;
260             if (buflen + bytes > bufsz) {
261                 if ((tmp = realloc(buf, bufsz + (bufsz >> 2) + sizeof(d))) == NULL)
262                     err(1, "Could not read stdin");
263                 buf = tmp;
264                 bufsz = bufsz + (bufsz >> 2) + sizeof(d);
265             }
266             memcpy(buf + buflen, d, bytes);
267             buflen += bytes;
268         }
269         if (ferror(stdin))
270             err(1, "Could not read stdin");
271     } else {
272         void *d;
273
274         if ((ret = rk_undumpdata(argv[0], &d, &bufsz)))
275             err(1, "Could not read %s", argv[0]);
276         buflen = bufsz;
277         buf = d;
278     }
279
280     if (decode_flag) {
281         unsigned char *d;
282
283         if (buflen == bufsz) {
284             unsigned char *tmp;
285
286             if ((tmp = realloc(buf, bufsz + 1)) == NULL)
287                 err(1, "Could not decode data");
288             buf = tmp;
289             bufsz++;
290         }
291         buf[buflen] = '\0';
292
293         if ((d = malloc(buflen * 5 / 8 + 4)) == NULL)
294             err(1, "Could not decode data");
295
296         if ((ret = rk_base32_decode((const char *)buf, d, flags)) < 0)
297             err(1, "Could not decode data");
298         if (fwrite(d, ret, 1, stdout) != 1)
299             err(1, "Could not write decoded data");
300         free(d);
301     } else {
302         char *e;
303
304         if ((ret = rk_base32_encode(buf, buflen, &e, flags)) < 0)
305             err(1, "Could not encode data");
306         if (fwrite(e, ret, 1, stdout) != 1)
307             err(1, "Could not write decoded data");
308         free(e);
309         if (fwrite("\n", 1, 1, stdout) != 1)
310             err(1, "Could not write decoded data");
311     }
312     free(buf);
313     return 0;
314 }
315 #endif