Further cleanups.
[metze/wireshark/wip.git] / wsutil / base64.c
1 /* base64.c
2  * Base-64 conversion
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include "config.h"
24
25 #include <string.h>
26 #include "base64.h"
27
28 /* Decode a base64 string in-place - simple and slow algorithm.
29    Return length of result. Taken from rproxy/librsync/base64.c by
30    Andrew Tridgell. */
31
32 size_t ws_base64_decode_inplace(char *s)
33 {
34         static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\r\n";
35         int bit_offset, byte_offset, idx, i;
36         unsigned char *d = (unsigned char *)s;
37         char *p;
38         int  cr_idx;
39
40         /* we will allow CR and LF - but ignore them */
41         cr_idx = (int) (strchr(b64, '\r') - b64);
42
43         i = 0;
44
45         while (*s && (p=strchr(b64, *s))) {
46                 idx = (int)(p - b64);
47                 if(idx < cr_idx) {
48                         byte_offset = (i*6)/8;
49                         bit_offset = (i*6)%8;
50                         d[byte_offset] &= ~((1<<(8-bit_offset))-1);
51                         if (bit_offset < 3) {
52                                 d[byte_offset] |= (idx << (2-bit_offset));
53                         } else {
54                                 d[byte_offset] |= (idx >> (bit_offset-2));
55                                 d[byte_offset+1] = 0;
56                                 d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
57                         }
58                         i++;
59                 }
60                 s++;
61         }
62
63         d[i*3/4] = 0;
64         return i*3/4;
65 }
66
67 /*
68  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
69  *
70  * Local variables:
71  * c-basic-offset: 8
72  * tab-width: 8
73  * indent-tabs-mode: t
74  * End:
75  *
76  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
77  * :indentSize=8:tabSize=8:noTabs=false:
78  */