File: base64filter.c

package info (click to toggle)
skencil 0.6.17-7
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 6,136 kB
  • ctags: 8,589
  • sloc: python: 36,672; ansic: 16,571; sh: 151; makefile: 92
file content (281 lines) | stat: -rw-r--r-- 7,773 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
  Copyright (C) 1998, 1999 by Bernhard Herzog.

			All Rights Reserved

  Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose and without fee is hereby granted,
  provided that the above copyright notice appear in all copies and that
  both that copyright notice and this permission notice appear in
  supporting documentation, and that the name of the author not be used
  in advertising or publicity pertaining to distribution of the software
  without specific, written prior permission.

  THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  PERFORMANCE OF THIS SOFTWARE.

parts of this file are based on code from the python interpreter, which
comes with the following license:

Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI or Corporation for National Research Initiatives or
CNRI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.


*/


#include "base64filter.h"

#define FBUFLEN 1024

/* some code here taken from binascii.c in Python's Modules directory */

static char table_a2b_base64[] = {
	-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
	-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
	-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
	52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */
	-1, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
	15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
	-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
	41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
};

#define BASE64_PAD '='


typedef struct {
    int leftbits;
    unsigned int leftchar;
} Base64DecodeState;


static size_t
read_base64(void* clientdata, PyObject * source, char * buf, size_t length)
{
    size_t bytes_read;
    unsigned char encoded[FBUFLEN];
    unsigned char * ascii_data;
    unsigned char * bin_data;
    int ascii_len, bin_len = 0;
    Base64DecodeState * state = (Base64DecodeState*)clientdata;
    int leftbits = state->leftbits;
    unsigned int leftchar = state->leftchar;
    unsigned char this_ch;
    int npad;

    bin_data = (unsigned char*)buf;

    while (!bin_len)
    {
	ascii_len = (length / 3) * 4; /* lower bound */
	if (ascii_len > FBUFLEN)
	    ascii_len = FBUFLEN;
	ascii_data = encoded;
	npad = 0;
	bytes_read = Filter_Read(source, (char*)ascii_data, ascii_len);
	if (bytes_read == 0)
	{
	    if (!PyErr_Occurred())
	    {
		if (leftbits != 0)
		    PyErr_Format(PyExc_ValueError,
				 "Base64Decode: premature end of data");
	    }
	    return 0;
	}

	ascii_len = bytes_read;
	for(; ascii_len > 0 ; ascii_len--, ascii_data++)
	{
	    /* Skip some punctuation */
	    this_ch = (*ascii_data & 0x7f);
	    if (this_ch == '\r' || this_ch == '\n' || this_ch == ' ')
		continue;
		
	    if (this_ch == BASE64_PAD)
		npad++;
	    this_ch = table_a2b_base64[(*ascii_data) & 0x7f];
	    if (this_ch == (unsigned char) -1)
		continue;
	    /*
	    ** Shift it in on the low end, and see if there's
	    ** a byte ready for output.
	    */
	    leftchar = (leftchar << 6) | (this_ch);
	    leftbits += 6;
	    if (leftbits >= 8)
	    {
		leftbits -= 8;
		*bin_data++ = (leftchar >> leftbits) & 0xff;
		leftchar &= ((1 << leftbits) - 1);
		bin_len++;
	    }
	}
	bin_len -= npad;
    }

    state->leftbits = leftbits;
    state->leftchar = leftchar;

    return bin_len;
}


PyObject *
Filter_Base64Decode(PyObject * self, PyObject * args)
{
    PyObject * source;
    Base64DecodeState * state;

    if (!PyArg_ParseTuple(args, "O", &source))
	return NULL;

    state = malloc(sizeof (Base64DecodeState));
    if (!state)
	return PyErr_NoMemory();
    state->leftbits = 0;
    state->leftchar = 0;

    return Filter_NewDecoder(source, "Base64Decode", 0, read_base64, NULL,
			     free, state);
}

#define BASE64_MAXASCII 76	/* Max chunk size (76 char line) */

static unsigned char table_b2a_base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

typedef struct {
    int leftbits;
    unsigned int leftchar;
    int column;
} Base64EncodeState;

static size_t
write_base64(void * clientdata, PyObject * target, const char * buf,
	     size_t length)
{
    Base64EncodeState * state = (Base64EncodeState*)clientdata;
    unsigned char encoded[FBUFLEN];
    unsigned char *ascii_data = encoded;
    const unsigned char *bin_data = (const unsigned char*)buf;
    int leftbits = state->leftbits;
    unsigned char this_ch;
    unsigned int leftchar = state->leftchar;
    int bin_len = ((FBUFLEN / 4) * 3);
    size_t ascii_left;

    if (bin_len > length)
	bin_len = length;

    /* first, fill the ascii buffer and don't care about max. line length */
    for( ; bin_len > 0 ; bin_len--, bin_data++ )
    {
	/* Shift the data into our buffer */
	leftchar = (leftchar << 8) | *bin_data;
	leftbits += 8;

	/* See if there are 6-bit groups ready */
	while ( leftbits >= 6 )
	{
	    this_ch = (leftchar >> (leftbits-6)) & 0x3f;
	    leftbits -= 6;
	    *ascii_data++ = table_b2a_base64[this_ch];
	}
    }
    state->leftbits = leftbits;
    state->leftchar = leftchar;

    /* now output the ascii data line by line */
    ascii_left = ascii_data - encoded;
    while (ascii_left > 0)
    {
	int linelength = BASE64_MAXASCII - state->column;

	if (ascii_left < linelength)
	    linelength = ascii_left;
	if (Filter_Write(target, ((char*)ascii_data) - ascii_left,
			 linelength) == 0)
	    return 0;
	ascii_left -= linelength;
	state->column += linelength;
	if (state->column >= BASE64_MAXASCII)
	{
	    if (Filter_Write(target, "\n", 1) == 0)
		return 0;
	    state->column = 0;
	}
    }

    return bin_data - (const unsigned char *)buf;
}

static int
close_base64encode(void * clientdata, PyObject * target)
{
    Base64EncodeState * state = (Base64EncodeState*)clientdata;
    unsigned char buf[4];
    unsigned char * ascii_data = buf;
    
    if (state->leftbits == 2)
    {
	*ascii_data++ = table_b2a_base64[(state->leftchar & 3) << 4];
	*ascii_data++ = BASE64_PAD;
	*ascii_data++ = BASE64_PAD;
    }
    else if (state->leftbits == 4)
    {
	*ascii_data++ = table_b2a_base64[(state->leftchar & 0xf) << 2];
	*ascii_data++ = BASE64_PAD;
    }
    
    if (ascii_data > buf || state->column != 0)
    {
	*ascii_data++ = '\n';	/* Append a courtesy newline */
    }
    if (ascii_data > buf)
    {
	if (Filter_Write(target, (char*)buf, ascii_data - buf) == 0)
	    return EOF;
    }

    return 0;
}

PyObject *
Filter_Base64Encode(PyObject * self, PyObject * args)
{
    PyObject * target;
    Base64EncodeState * state;

    if (!PyArg_ParseTuple(args, "O", &target))
	return NULL;

    state = malloc(sizeof (Base64EncodeState));
    if (!state)
	return PyErr_NoMemory();
    state->leftbits = 0;
    state->leftchar = 0;
    state->column = 0; /* assume target is at the beginning of a line */

    return Filter_NewEncoder(target, "Base64Decode", 0, write_base64,
			     close_base64encode, free, state);
}