vde_autolink: Add missing null entry in getopt_long array.
[vde.git] / vde-2 / src / vde_over_ns / encode.c
blobc01f62fce624faab6f48f9756dfb0e0a61ef3032
1 /* ----------------------------------------------------------------------------
3 VDE_OVER_NS
4 (C) 2007 Daniele Lacamera
6 Derived from:
7 NSTX -- tunneling network-packets over DNS
9 (C) 2000 by Florian Heinz and Julien Oster
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License version 2, as
13 published by the Free Software Foundation.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 -------------------------------------------------------------------------- */
26 #include <string.h>
27 #include <stdlib.h>
29 #include <config.h>
30 #include <vde.h>
31 #include <vdecommon.h>
33 unsigned char map[] =
34 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_1234567890";
35 unsigned char *revmap = NULL;
37 void init_revmap (void)
39 unsigned int i;
41 revmap = malloc(256);
43 for (i = 0; i < strlen((char*)map); i++)
44 revmap[map[i]] = i;
47 const unsigned char *
48 nstx_encode(const unsigned char *data, int len) {
49 int i = 0, off = 1, cut = 0;
50 static unsigned char *buf = NULL;
52 if (len % 3)
53 cut = 3 - len%3;
55 buf = realloc(buf, ((len+2)/3)*4+2);
56 buf[0] = map[cut];
57 while (i < len) {
58 buf[off + 0] = map[(data[i] & 252) >> 2];
59 buf[off + 1] = map[((data[i] & 3) << 4) | ((data[i+1] & 240) >> 4)];
60 buf[off + 2] = map[((data[i+1] & 15) << 2 ) | ((data[i+2] & 192) >> 6)];
61 buf[off + 3] = map[(data[i+2] & 63)];
62 i += 3;
63 off += 4;
65 buf[off] = '\0';
67 return buf;
70 const unsigned char *
71 nstx_decode(const unsigned char *data, int *rlen) {
72 int i = 0, off = 1;
73 int len;
74 static unsigned char *buf = NULL;
76 if (!revmap)
77 init_revmap();
79 len = strlen((char*)data);
81 buf = realloc(buf, ((len+3)/4)*3);
83 while (off+3 < len) {
84 buf[i+0] = (revmap[data[off]]<<2)|((revmap[data[off+1]]&48)>>4);
85 buf[i+1] = ((revmap[data[off+1]]&15)<<4)|((revmap[data[off+2]]&60)>>2);
86 buf[i+2] = ((revmap[data[off+2]]&3)<<6)|(revmap[data[off+3]]);
87 i += 3;
88 off += 4;
90 *rlen = i - revmap[data[0]];
92 return buf;