1 /* -*- c-file-style: "python"; indent-tabs-mode: nil; -*-
3 Python wrapper for Samba tdb pack/unpack functions
4 Copyright (C) Martin Pool 2002
7 NOTE PYTHON STYLE GUIDE
8 http://www.python.org/peps/pep-0007.html
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
30 static int pytdbpack_calc_reqd_len(char *format_str,
33 static PyObject *pytdbpack_unpack_item(char, char **pbuf, int *plen, PyObject *);
35 static PyObject *pytdbpack_pack_data(const char *format_str,
42 static PyObject *pytdbpack_bad_type(char ch,
46 static const char * pytdbpack_docstring =
47 "Convert between Python values and Samba binary encodings.
49 This module is conceptually similar to the standard 'struct' module, but it
50 uses both a different binary format and a different description string.
52 Samba's encoding is based on that used inside DCE-RPC and SMB: a
53 little-endian, unpadded, non-self-describing binary format. It is intended
54 that these functions be as similar as possible to the routines in Samba's
55 tdb/tdbutil module, with appropriate adjustments for Python datatypes.
57 Python strings are used to specify the format of data to be packed or
60 Strings in TDBs are typically stored in DOS codepages. The caller of this
61 module must make appropriate translations if necessary, typically to and from
64 tdbpack format strings:
66 'f': NULL-terminated string in DOS codepage
70 'd': 4 byte little-endian unsigned number
72 'w': 2 byte little-endian unsigned number
74 'P': \"Pointer\" value -- in the subset of DCERPC used by Samba, this is
75 really just an \"exists\" or \"does not exist\" flag. The boolean
76 value of the Python object is used.
78 'B': 4-byte LE length, followed by that many bytes of binary data.
79 Corresponds to a Python integer giving the length, followed by a byte
80 string of the appropriate length.
82 '$': Special flag indicating that the preceding format code should be
83 repeated while data remains. This is only supported for unpacking.
85 Every code corresponds to a single Python object, except 'B' which
86 corresponds to two values (length and contents), and '$', which produces
87 however many make sense.
91 static char const pytdbpack_pack_doc[] =
92 "pack(format, values) -> buffer
93 Pack Python objects into Samba binary format according to format string.
96 format -- string of tdbpack format characters
97 values -- sequence of value objects corresponding 1:1 to format characters
100 buffer -- string containing packed data
103 IndexError -- if there are too few values for the format
104 ValueError -- if any of the format characters is illegal
105 TypeError -- if the format is not a string, or values is not a sequence,
106 or any of the values is of the wrong type for the corresponding
110 For historical reasons, it is not an error to pass more values than are consumed
115 static char const pytdbpack_unpack_doc[] =
116 "unpack(format, buffer) -> (values, rest)
117 Unpack Samba binary data according to format string.
120 format -- string of tdbpack characters
121 buffer -- string of packed binary data
125 values -- sequence of values corresponding 1:1 to format characters
126 rest -- string containing data that was not decoded, or '' if the
127 whole string was consumed
130 IndexError -- if there is insufficient data in the buffer for the
131 format (or if the data is corrupt and contains a variable-length
132 field extending past the end)
133 ValueError -- if any of the format characters is illegal
136 Because unconsumed data is returned, you can feed it back in to the
137 unpacker to extract further fields. Alternatively, if you wish to modify
138 some fields near the start of the data, you may be able to save time by
139 only unpacking and repacking the necessary part.
145 Game plan is to first of all walk through the arguments and calculate the
146 total length that will be required. We allocate a Python string of that
147 size, then walk through again and fill it in.
149 We just borrow references to all the passed arguments, since none of them
150 need to be permanently stored. We transfer ownership to the returned
154 pytdbpack_pack(PyObject *self,
158 PyObject *val_seq, *fast_seq, *buf_str;
162 /* TODO: Test passing wrong types or too many arguments */
163 if (!PyArg_ParseTuple(args, "sO", &format_str, &val_seq))
166 /* Convert into a list or tuple (if not already one), so that we can
167 * index more easily. */
168 fast_seq = PySequence_Fast(val_seq,
169 __FUNCTION__ ": argument 2 must be sequence");
173 reqd_len = pytdbpack_calc_reqd_len(format_str, fast_seq);
174 if (reqd_len == -1) /* exception was thrown */
179 This design causes an unnecessary copying of the data when Python
180 constructs an object, and that might possibly be avoided by using a
181 Buffer object of some kind instead. I'm not doing that for now
183 packed_buf = malloc(reqd_len);
185 PyErr_Format(PyExc_MemoryError,
186 "%s: couldn't allocate %d bytes for packed buffer",
187 __FUNCTION__, reqd_len);
191 if (!pytdbpack_pack_data(format_str, fast_seq, packed_buf)) {
196 buf_str = PyString_FromStringAndSize(packed_buf, reqd_len);
197 free(packed_buf); /* get rid of tmp buf */
205 pytdbpack_unpack(PyObject *self,
208 char *format_str, *packed_str, *ppacked;
209 PyObject *val_list = NULL, *ret_tuple = NULL;
210 PyObject *rest_string = NULL;
211 int format_len, packed_len;
213 char last_format = '#';
216 if (!PyArg_ParseTuple(args, "ss#", &format_str, &packed_str, &packed_len))
219 format_len = strlen(format_str);
221 /* Allocate list to hold results. Initially empty, and we append
222 results as we go along. */
223 val_list = PyList_New(0);
226 ret_tuple = PyTuple_New(2);
230 /* For every object, unpack. */
231 for (ppacked = packed_str, i = 0; i < format_len; i++) {
234 format = format_str[i];
237 PyErr_Format(PyExc_ValueError,
238 "%s: '$' may not be first character in format",
243 format = last_format; /* repeat */
247 if (!pytdbpack_unpack_item(format, &ppacked, &packed_len, val_list))
250 last_format = format;
253 /* save leftovers for next time */
254 rest_string = PyString_FromStringAndSize(ppacked, packed_len);
258 /* return (values, rest) tuple; give up references to them */
259 PyTuple_SET_ITEM(ret_tuple, 0, val_list);
261 PyTuple_SET_ITEM(ret_tuple, 1, rest_string);
266 /* handle failure: deallocate anything. XDECREF forms handle NULL
267 pointers for objects that haven't been allocated yet. */
268 Py_XDECREF(val_list);
269 Py_XDECREF(ret_tuple);
270 Py_XDECREF(rest_string);
276 Internal routine that calculates how many bytes will be required to
277 encode the values in the format.
279 Also checks that the value list is the right size for the format list.
281 Returns number of bytes (may be 0), or -1 if there's something wrong, in
282 which case a Python exception has been raised.
286 val_seq: a Fast Sequence (list or tuple), being all the values
289 pytdbpack_calc_reqd_len(char *format_str,
297 val_len = PySequence_Length(val_seq);
301 for (p = format_str, val_i = 0; *p; p++, val_i++) {
304 if (val_i >= val_len) {
305 PyErr_Format(PyExc_IndexError,
306 "%s: value list is too short for format string",
311 /* borrow a reference to the item */
312 if (ch == 'd' || ch == 'p')
316 else if (ch == 'f' || ch == 'P') {
317 /* nul-terminated 8-bit string */
321 str_obj = PySequence_GetItem(val_seq, val_i);
325 if (!PyString_Check(str_obj) || ((item_len = PyString_Size(str_obj)) == -1)) {
326 pytdbpack_bad_type(ch, "String", str_obj);
332 else if (ch == 'B') {
333 /* length-preceded byte buffer: n bytes, plus a preceding
338 len_obj = PySequence_GetItem(val_seq, val_i);
339 val_i++; /* skip over buffer */
341 if (!PyNumber_Check(len_obj)) {
342 pytdbpack_bad_type(ch, "Number", len_obj);
346 len_val = PyInt_AsLong(len_obj);
348 PyErr_Format(PyExc_ValueError,
349 "%s: format 'B' requires positive integer", __FUNCTION__);
356 PyErr_Format(PyExc_ValueError,
357 "%s: format character '%c' is not supported",
368 static PyObject *pytdbpack_bad_type(char ch,
369 const char *expected,
372 PyObject *r = PyObject_Repr(val_obj);
375 PyErr_Format(PyExc_TypeError,
376 "tdbpack: format '%c' requires %s, not %s",
377 ch, expected, PyString_AS_STRING(r));
384 XXX: glib and Samba have quicker macro for doing the endianness conversions,
385 but I don't know of one in plain libc, and it's probably not a big deal. I
386 realize this is kind of dumb because we'll almost always be on x86, but
387 being safe is important.
389 static void pack_uint32(unsigned long val_long, unsigned char **pbuf)
391 (*pbuf)[0] = val_long & 0xff;
392 (*pbuf)[1] = (val_long >> 8) & 0xff;
393 (*pbuf)[2] = (val_long >> 16) & 0xff;
394 (*pbuf)[3] = (val_long >> 24) & 0xff;
399 static void pack_bytes(long len, const char *from,
400 unsigned char **pbuf)
402 memcpy(*pbuf, from, len);
408 unpack_err_too_short(void)
410 PyErr_Format(PyExc_IndexError,
411 __FUNCTION__ ": data too short for unpack format");
416 unpack_uint32(char **pbuf, int *plen)
422 unpack_err_too_short();
427 v = b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24;
432 return PyLong_FromUnsignedLong(v);
436 static PyObject *unpack_int16(char **pbuf, int *plen)
442 unpack_err_too_short();
452 return PyInt_FromLong(v);
457 unpack_string(char **pbuf, int *plen)
460 char *nul_ptr, *start;
464 nul_ptr = memchr(start, '\0', *plen);
466 unpack_err_too_short();
470 len = nul_ptr - start;
472 *pbuf += len + 1; /* skip \0 */
475 return PyString_FromStringAndSize(start, len);
480 unpack_buffer(char **pbuf, int *plen, PyObject *val_list)
482 /* first get 32-bit len */
485 unsigned char *start;
486 PyObject *str_obj = NULL, *len_obj = NULL;
489 unpack_err_too_short();
494 slen = b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24;
496 if (slen < 0) { /* surely you jest */
497 PyErr_Format(PyExc_ValueError,
498 __FUNCTION__ ": buffer seems to have negative length");
507 PyErr_Format(PyExc_IndexError,
508 __FUNCTION__ ": not enough data to unpack buffer: "
509 "need %d bytes, have %d",
517 if (!(len_obj = PyInt_FromLong(slen)))
520 if (PyList_Append(val_list, len_obj) == -1)
523 if (!(str_obj = PyString_FromStringAndSize(start, slen)))
526 if (PyList_Append(val_list, str_obj) == -1)
532 Py_XDECREF(len_obj); /* handles NULL */
538 /* Unpack a single field from packed data, according to format character CH.
539 Remaining data is at *PBUF, of *PLEN.
541 *PBUF is advanced, and *PLEN reduced to reflect the amount of data that has
544 Returns a reference to None, or NULL for failure.
546 static PyObject *pytdbpack_unpack_item(char ch,
553 if (ch == 'w') { /* 16-bit int */
554 result = unpack_int16(pbuf, plen);
556 else if (ch == 'd' || ch == 'p') { /* 32-bit int */
557 /* pointers can just come through as integers */
558 result = unpack_uint32(pbuf, plen);
560 else if (ch == 'f' || ch == 'P') { /* nul-term string */
561 result = unpack_string(pbuf, plen);
563 else if (ch == 'B') { /* length, buffer */
564 return unpack_buffer(pbuf, plen, val_list);
567 PyErr_Format(PyExc_ValueError,
568 __FUNCTION__ ": format character '%c' is not supported",
577 if (PyList_Append(val_list, result) == -1)
587 Pack data according to FORMAT_STR from the elements of VAL_SEQ into
590 The string has already been checked out, so we know that VAL_SEQ is large
591 enough to hold the packed data, and that there are enough value items.
592 (However, their types may not have been thoroughly checked yet.)
594 In addition, val_seq is a Python Fast sequence.
596 Returns NULL for error (with exception set), or None.
599 pytdbpack_pack_data(const char *format_str,
601 unsigned char *packed)
603 int format_i, val_i = 0;
605 for (format_i = 0, val_i = 0; format_str[format_i]; format_i++) {
606 char ch = format_str[format_i];
609 /* borrow a reference to the item */
610 val_obj = PySequence_GetItem(val_seq, val_i++);
615 unsigned long val_long;
618 if (!(long_obj = PyNumber_Long(val_obj))) {
619 pytdbpack_bad_type(ch, "Long", val_obj);
623 val_long = PyLong_AsUnsignedLong(long_obj);
624 (packed)[0] = val_long & 0xff;
625 (packed)[1] = (val_long >> 8) & 0xff;
629 else if (ch == 'd') {
630 /* 4-byte LE number */
633 if (!(long_obj = PyNumber_Long(val_obj))) {
634 pytdbpack_bad_type(ch, "Long", val_obj);
638 pack_uint32(PyLong_AsUnsignedLong(long_obj), &packed);
642 else if (ch == 'p') {
643 /* "Pointer" value -- in the subset of DCERPC used by Samba,
644 this is really just an "exists" or "does not exist"
646 pack_uint32(PyObject_IsTrue(val_obj), &packed);
648 else if (ch == 'f' || ch == 'P') {
652 size = PySequence_Length(val_obj);
655 sval = PyString_AsString(val_obj);
658 pack_bytes(size+1, sval, &packed); /* include nul */
660 else if (ch == 'B') {
664 if (!PyInt_Check(val_obj)) {
665 pytdbpack_bad_type(ch, "Integer", val_obj);
669 size = PyInt_AsLong(val_obj);
670 pack_uint32(size, &packed);
672 val_obj = PySequence_GetItem(val_seq, val_i++);
676 sval = PyString_AsString(val_obj);
680 pack_bytes(size, sval, &packed); /* do not include nul */
683 /* this ought to be caught while calculating the length, but
685 PyErr_Format(PyExc_ValueError,
686 "%s: format character '%c' is not supported",
698 static PyMethodDef pytdbpack_methods[] = {
699 { "pack", pytdbpack_pack, METH_VARARGS, (char *) pytdbpack_pack_doc },
700 { "unpack", pytdbpack_unpack, METH_VARARGS, (char *) pytdbpack_unpack_doc },
706 Py_InitModule3("tdbpack", pytdbpack_methods,
707 (char *) pytdbpack_docstring);