varnish-cache/bin/varnishncsa/b64.c
1
/*
2
 * Written by Poul-Henning Kamp <phk@phk.freebsd.dk>
3
 *
4
 * This file is in the public domain.
5
 */
6
7
#include "config.h"
8
9
#include <stdlib.h>
10
#include <string.h>
11
12
#include "b64.h"
13
14
static const char b64[] =
15
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
16
17
static char i64[256];
18
19
void
20 29
VB64_init(void)
21
{
22
        int i;
23
        const char *p;
24
25 7453
        for (i = 0; i < 256; i++)
26 7424
                i64[i] = -1;
27 1885
        for (p = b64, i = 0; *p; p++, i++)
28 1856
                i64[(int)*p] = (char)i;
29 29
        i64['='] = 0;
30 29
}
31
32
int
33 3
VB64_decode(char *d, unsigned dlen, const char *s, const char *e)
34
{
35
        unsigned u, v, l;
36
        int i;
37
38 3
        if (e == NULL)
39 0
                e = s + strlen(s);
40 3
        u = 0;
41 3
        l = 0;
42 15
        while (s < e) {
43 45
                for (v = 0; s < e && v < 4; v++) {
44 36
                        i = i64[(int)*s++];
45 36
                        if (i < 0)
46 0
                                return (-1);
47 36
                        u <<= 6;
48 36
                        u |= i;
49
                }
50 36
                for (v = 0; v < 3; v++) {
51 27
                        if (l >= dlen - 1)
52 0
                                return (-1);
53 27
                        *d = (u >> 16) & 0xff;
54 27
                        u <<= 8;
55 27
                        l++;
56 27
                        d++;
57
                }
58
        }
59 3
        *d = '\0';
60 3
        return (0);
61
}
62
63
#ifdef TEST_DRIVER
64
65
#include <stdio.h>              // for test-prog
66
67
const char *test1 =
68
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
69
"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
70
"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
71
"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
72
"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
73
74
int
75
main(int argc, char **argv)
76
{
77
        int i;
78
        char buf[BUFSIZ];
79
        unsigned l;
80
81
        (void)argc;
82
        (void)argv;
83
84
        VB64_init();
85
        l = sizeof buf;
86
        VB64_decode(buf, l, test1, NULL);
87
        printf("%s\n", buf);
88
        return (0);
89
}
90
#endif