Debian Codegraph @

mypyc/lib-rt/base64/librt_base64.c

raw
1 #define PY_SSIZE_T_CLEAN
2 #include <Python.h>
3 #include <stdbool.h>
4
5 #define BASE64_EXPORTS
6
7 #include "librt_base64.h"
8 #include "libbase64.h"
9 #include "pythoncapi_compat.h"
10
11 static PyObject *
12 b64decode_handle_invalid_input(
13 PyObject *out_bytes, char *outbuf, size_t max_out, const char *src, size_t srclen, bool freesrc);
14
15 #define BASE64_MAXBIN ((PY_SSIZE_T_MAX - 3) / 2)
16
17 #define STACK_BUFFER_SIZE 1024
18
19 static void
20 convert_encoded_to_urlsafe(char *buf, size_t len) {
21 // The loop is written to enable SIMD optimizations
22 for (size_t i = 0; i < len; i++) {
23 char ch = buf[i];
24 if (ch == '+') {
25 ch = '-';
26 } else if (ch == '/') {
27 ch = '_';
28 }
29 buf[i] = ch;
30 }
31 }
32
33 static void
34 convert_urlsafe_to_encoded(const char *src, size_t len, char *buf) {
35 // The loop is written to enable SIMD optimizations
36 for (size_t i = 0; i < len; i++) {
37 char ch = src[i];
38 if (ch == '-') {
39 ch = '+';
40 } else if (ch == '_') {
41 ch = '/';
42 }
43 buf[i] = ch;
44 }
45 }
46
47 static PyObject *
48 b64encode_internal(PyObject *obj, bool urlsafe) {
49 unsigned char *ascii_data;
50 char *bin_data;
51 int leftbits = 0;
52 unsigned char this_ch;
53 unsigned int leftchar = 0;
54 Py_ssize_t bin_len, out_len;
55 PyBytesWriter *writer;
56 int newline = 0; // TODO
57
58 if (!PyBytes_Check(obj)) {
59 PyErr_SetString(PyExc_TypeError, "base64() expects a bytes object");
60 return NULL;
61 }
62
63 bin_data = PyBytes_AS_STRING(obj);
64 bin_len = PyBytes_GET_SIZE(obj);
65 assert(bin_len >= 0);
66
67 if (bin_len > BASE64_MAXBIN) {
68 PyErr_SetString(PyExc_ValueError, "Too much data for base64 line");
69 return NULL;
70 }
71
72 Py_ssize_t buflen = 4 * bin_len / 3 + 4;
73 char *buf;
74 char stack_buf[STACK_BUFFER_SIZE];
75 if (buflen <= STACK_BUFFER_SIZE) {
76 buf = stack_buf;
77 } else {
78 buf = PyMem_Malloc(buflen);
79 if (buf == NULL) {
80 return PyErr_NoMemory();
81 }
82 }
83 size_t actual_len;
84 base64_encode(bin_data, bin_len, buf, &actual_len, 0);
85
86 if (urlsafe) {
87 convert_encoded_to_urlsafe(buf, actual_len);
88 }
89
90 PyObject *res = PyBytes_FromStringAndSize(buf, actual_len);
91 if (buflen > STACK_BUFFER_SIZE)
92 PyMem_Free(buf);
93 return res;
94 }
95
96 static PyObject*
97 b64encode(PyObject *self, PyObject *const *args, size_t nargs) {
98 if (nargs != 1) {
99 PyErr_SetString(PyExc_TypeError, "b64encode() takes exactly one argument");
100 return 0;
101 }
102 return b64encode_internal(args[0], false);
103 }
104
105 static PyObject*
106 urlsafe_b64encode(PyObject *self, PyObject *const *args, size_t nargs) {
107 if (nargs != 1) {
108 PyErr_SetString(PyExc_TypeError, "urlsafe_b64encode() takes exactly one argument");
109 return 0;
110 }
111 return b64encode_internal(args[0], true);
112 }
113
114 static inline int
115 is_valid_base64_char(char c, bool allow_padding) {
116 return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
117 (c >= '0' && c <= '9') || (c == '+') || (c == '/') || (allow_padding && c == '='));
118 }
119
120 static PyObject *
121 b64decode_internal(PyObject *arg, bool urlsafe) {
122 const char *src;
123 Py_ssize_t srclen_ssz;
124
125 // Get input pointer and length
126 if (PyBytes_Check(arg)) {
127 src = PyBytes_AS_STRING(arg);
128 srclen_ssz = PyBytes_GET_SIZE(arg);
129 } else if (PyUnicode_Check(arg)) {
130 if (!PyUnicode_IS_ASCII(arg)) {
131 PyErr_SetString(PyExc_ValueError,
132 "string argument should contain only ASCII characters");
133 return NULL;
134 }
135 src = (const char *)PyUnicode_1BYTE_DATA(arg);
136 srclen_ssz = PyUnicode_GET_LENGTH(arg);
137 } else {
138 PyErr_SetString(PyExc_TypeError,
139 "argument should be a bytes-like object or ASCII string");
140 return NULL;
141 }
142
143 // Fast-path: empty input
144 if (srclen_ssz == 0) {
145 return PyBytes_FromStringAndSize(NULL, 0);
146 }
147
148 if (urlsafe) {
149 char *new_src = PyMem_Malloc(srclen_ssz + 1);
150 if (new_src == NULL) {
151 return PyErr_NoMemory();
152 }
153 convert_urlsafe_to_encoded(src, srclen_ssz, new_src);
154 src = new_src;
155 }
156
157 // Quickly ignore invalid characters at the end. Other invalid characters
158 // are also accepted, but they need a slow path.
159 while (srclen_ssz > 0 && !is_valid_base64_char(src[srclen_ssz - 1], true)) {
160 srclen_ssz--;
161 }
162
163 // Compute an output capacity that's at least 3/4 of input, without overflow:
164 // ceil(3/4 * N) == N - floor(N/4)
165 size_t srclen = (size_t)srclen_ssz;
166 size_t max_out = srclen - (srclen / 4);
167 if (max_out == 0) {
168 max_out = 1; // defensive (srclen > 0 implies >= 1 anyway)
169 }
170 if (max_out > (size_t)PY_SSIZE_T_MAX) {
171 PyErr_SetString(PyExc_OverflowError, "input too large");
172 return NULL;
173 }
174
175 // Allocate output bytes (uninitialized) of the max capacity
176 PyObject *out_bytes = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)max_out);
177 if (out_bytes == NULL) {
178 if (urlsafe) {
179 PyMem_Free((void *)src);
180 }
181 return NULL; // Propagate memory error
182 }
183
184 char *outbuf = PyBytes_AS_STRING(out_bytes);
185 size_t outlen = max_out;
186
187 int ret = base64_decode(src, srclen, outbuf, &outlen, 0);
188
189 if (ret != 1) {
190 if (ret == 0) {
191 // Slow path: handle non-base64 input
192 return b64decode_handle_invalid_input(out_bytes, outbuf, max_out, src, srclen, urlsafe);
193 }
194 Py_DECREF(out_bytes);
195 if (urlsafe) {
196 PyMem_Free((void *)src);
197 }
198 if (ret == -1) {
199 PyErr_SetString(PyExc_NotImplementedError, "base64 codec not available in this build");
200 } else {
201 PyErr_SetString(PyExc_RuntimeError, "base64_decode failed");
202 }
203 return NULL;
204 }
205
206 if (urlsafe) {
207 PyMem_Free((void *)src);
208 }
209
210 // Sanity-check contract (decoder must not overflow our buffer)
211 if (outlen > max_out) {
212 Py_DECREF(out_bytes);
213 PyErr_SetString(PyExc_RuntimeError, "decoder wrote past output buffer");
214 return NULL;
215 }
216
217 // Shrink in place to the actual decoded length
218 if (_PyBytes_Resize(&out_bytes, (Py_ssize_t)outlen) < 0) {
219 // _PyBytes_Resize sets an exception and may free the old object
220 return NULL;
221 }
222 return out_bytes;
223 }
224
225 // Process non-base64 input by ignoring non-base64 characters, for compatibility
226 // with stdlib b64decode.
227 static PyObject *
228 b64decode_handle_invalid_input(
229 PyObject *out_bytes, char *outbuf, size_t max_out, const char *src, size_t srclen, bool freesrc)
230 {
231 // Copy input to a temporary buffer, with non-base64 characters and extra suffix
232 // characters removed
233 size_t newbuf_len = 0;
234 char *newbuf = PyMem_Malloc(srclen);
235 if (newbuf == NULL) {
236 Py_DECREF(out_bytes);
237 if (freesrc) {
238 PyMem_Free((void *)src);
239 }
240 return PyErr_NoMemory();
241 }
242
243 int pad_chars = 0;
244 // Copy base64 characters to the new buffer. Ignore padding to conform to RFC 4648 section 3.3.
245 for (size_t i = 0; i < srclen; i++) {
246 char c = src[i];
247 if (is_valid_base64_char(c, false)) {
248 newbuf[newbuf_len++] = c;
249 pad_chars = 0;
250 } else if (c == '=') {
251 pad_chars++;
252 }
253 }
254
255 int quad_pos = newbuf_len % 4;
256 // Stdlib always performs a non-strict padding check
257 if (quad_pos != 0 && quad_pos + pad_chars < 4) {
258 if (freesrc) {
259 PyMem_Free((void *)src);
260 }
261 Py_DECREF(out_bytes);
262 PyMem_Free(newbuf);
263 PyErr_SetString(PyExc_ValueError, "Incorrect padding");
264 return NULL;
265 }
266
267 if (quad_pos != 0) {
268 // Add padding at the end to make the input length a multiple of 4. We know that this padding
269 // is present in src because otherwise we would report the "Incorrect padding" error above.
270 while (quad_pos < 4) {
271 newbuf[newbuf_len++] = '=';
272 quad_pos++;
273 }
274 }
275
276 size_t outlen = max_out;
277 int ret = base64_decode(newbuf, newbuf_len, outbuf, &outlen, 0);
278 PyMem_Free(newbuf);
279 if (freesrc) {
280 PyMem_Free((void *)src);
281 }
282
283 if (ret != 1) {
284 Py_DECREF(out_bytes);
285 if (ret == 0) {
286 PyErr_SetString(PyExc_ValueError, "Only base64 data is allowed");
287 }
288 if (ret == -1) {
289 PyErr_SetString(PyExc_NotImplementedError, "base64 codec not available in this build");
290 } else {
291 PyErr_SetString(PyExc_RuntimeError, "base64_decode failed");
292 }
293 return NULL;
294 }
295
296 // Shrink in place to the actual decoded length
297 if (_PyBytes_Resize(&out_bytes, (Py_ssize_t)outlen) < 0) {
298 // _PyBytes_Resize sets an exception and may free the old object
299 return NULL;
300 }
301 return out_bytes;
302 }
303
304 static PyObject*
305 b64decode(PyObject *self, PyObject *const *args, size_t nargs) {
306 if (nargs != 1) {
307 PyErr_SetString(PyExc_TypeError, "b64decode() takes exactly one argument");
308 return 0;
309 }
310 return b64decode_internal(args[0], false);
311 }
312
313 static PyObject*
314 urlsafe_b64decode(PyObject *self, PyObject *const *args, size_t nargs) {
315 if (nargs != 1) {
316 PyErr_SetString(PyExc_TypeError, "urlsafe_b64decode() takes exactly one argument");
317 return 0;
318 }
319 return b64decode_internal(args[0], true);
320 }
321
322 static PyMethodDef librt_base64_module_methods[] = {
323 {"b64encode", (PyCFunction)b64encode, METH_FASTCALL, PyDoc_STR("Encode bytes object using Base64.")},
324 {"b64decode", (PyCFunction)b64decode, METH_FASTCALL, PyDoc_STR("Decode a Base64 encoded bytes object or ASCII string.")},
325 {"urlsafe_b64encode", (PyCFunction)urlsafe_b64encode, METH_FASTCALL, PyDoc_STR("Encode bytes object using URL and file system safe Base64 alphabet.")},
326 {"urlsafe_b64decode", (PyCFunction)urlsafe_b64decode, METH_FASTCALL, PyDoc_STR("Decode bytes or ASCII string using URL and file system safe Base64 alphabet.")},
327 {NULL, NULL, 0, NULL}
328 };
329
330 static int
331 base64_abi_version(void) {
332 return LIBRT_BASE64_ABI_VERSION;
333 }
334
335 static int
336 base64_api_version(void) {
337 return LIBRT_BASE64_API_VERSION;
338 }
339
340 static int
341 librt_base64_module_exec(PyObject *m)
342 {
343 // Export mypy internal C API, be careful with the order!
344 static void *base64_api[LIBRT_BASE64_API_LEN] = {
345 (void *)base64_abi_version,
346 (void *)base64_api_version,
347 (void *)b64encode_internal,
348 (void *)b64decode_internal,
349 };
350 PyObject *c_api_object = PyCapsule_New((void *)base64_api, "librt.base64._C_API", NULL);
351 if (PyModule_Add(m, "_C_API", c_api_object) < 0) {
352 return -1;
353 }
354 return 0;
355 }
356
357 static PyModuleDef_Slot librt_base64_module_slots[] = {
358 {Py_mod_exec, librt_base64_module_exec},
359 #ifdef Py_MOD_GIL_NOT_USED
360 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
361 #endif
362 {0, NULL}
363 };
364
365 static PyModuleDef librt_base64_module = {
366 .m_base = PyModuleDef_HEAD_INIT,
367 .m_name = "base64",
368 .m_doc = "Fast base64 encoding and decoding optimized for mypyc",
369 .m_size = 0,
370 .m_methods = librt_base64_module_methods,
371 .m_slots = librt_base64_module_slots,
372 };
373
374 PyMODINIT_FUNC
375 PyInit_base64(void)
376 {
377 return PyModuleDef_Init(&librt_base64_module);
378 }