1 #define _LARGEFILE64_SOURCE 1
2 #define PY_SSIZE_T_CLEAN 1
4 #include "../../config/config.h"
6 // According to Python, its header has to go first:
7 // http://docs.python.org/2/c-api/intro.html#include-files
8 // http://docs.python.org/3/c-api/intro.html#include-files
11 #include <arpa/inet.h>
23 #ifdef HAVE_SYS_MMAN_H
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
29 #ifdef HAVE_SYS_STAT_H
35 #ifdef HAVE_SYS_TIME_H
39 #ifdef HAVE_LINUX_FS_H
42 #ifdef HAVE_SYS_IOCTL_H
43 #include <sys/ioctl.h>
46 #ifdef HAVE_TM_TM_GMTOFF
50 #if defined(BUP_RL_EXPECTED_XOPEN_SOURCE) \
51 && (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < BUP_RL_EXPECTED_XOPEN_SOURCE)
52 # warning "_XOPEN_SOURCE version is incorrect for readline"
55 #ifdef BUP_HAVE_READLINE
56 # pragma GCC diagnostic push
57 # pragma GCC diagnostic ignored "-Wstrict-prototypes"
58 # ifdef BUP_READLINE_INCLUDES_IN_SUBDIR
59 # include <readline/readline.h>
60 # include <readline/history.h>
62 # include <readline.h>
65 # pragma GCC diagnostic pop
69 #include "bup/intprops.h"
71 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
72 #define BUP_HAVE_FILE_ATTRS 1
75 #if PY_MAJOR_VERSION > 2
76 # define BUP_USE_PYTHON_UTIME 1
79 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
81 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
82 * pretend we don't have it.
84 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
87 #endif // defined BUP_USE_PYTHON_UTIME
90 // Of course, this assumes it's a bitfield value.
95 typedef unsigned char byte;
102 // cstr_argf: for byte vectors without null characters (e.g. paths)
103 // rbuf_argf: for read-only byte vectors
104 // wbuf_argf: for mutable byte vectors
106 #if PY_MAJOR_VERSION < 3
107 static state_t state;
108 # define get_state(x) (&state)
109 # define cstr_argf "s"
110 # define rbuf_argf "s#"
111 # define wbuf_argf "s*"
113 # define get_state(x) ((state_t *) PyModule_GetState(x))
114 # define cstr_argf "y"
115 # define rbuf_argf "y#"
116 # define wbuf_argf "y*"
117 #endif // PY_MAJOR_VERSION >= 3
120 static void *checked_calloc(size_t n, size_t size)
122 void *result = calloc(n, size);
128 static void *checked_malloc(size_t n, size_t size)
131 if (!INT_MULTIPLY_OK(n, size, &total))
133 PyErr_Format(PyExc_OverflowError,
134 "request to allocate %zu items of size %zu is too large",
138 void *result = malloc(total);
140 return PyErr_NoMemory();
146 // This function should technically be macro'd out if it's going to be used
147 // more than ocasionally. As of this writing, it'll actually never be called
148 // in real world bup scenarios (because our packs are < MAX_INT bytes).
149 static uint64_t htonll(uint64_t value)
151 static const int endian_test = 42;
153 if (*(char *)&endian_test == endian_test) // LSB-MSB
154 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
155 return value; // already in network byte order MSB-LSB
159 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) INT_ADD_OK(src, 0, dest)
161 #define INTEGER_TO_PY(x) \
162 EXPR_SIGNED(x) ? PyLong_FromLongLong(x) : PyLong_FromUnsignedLongLong(x)
164 #if PY_MAJOR_VERSION < 3
165 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
168 const long tmp = PyInt_AsLong(py);
169 if (tmp == -1 && PyErr_Occurred())
171 if (PyErr_ExceptionMatches(PyExc_OverflowError))
172 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
178 PyErr_Format(PyExc_OverflowError,
179 "negative %s cannot be converted to unsigned long", name);
188 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
190 #if PY_MAJOR_VERSION < 3
192 return bup_ulong_from_pyint(x, py, name);
195 if (!PyLong_Check(py))
197 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
201 const unsigned long tmp = PyLong_AsUnsignedLong(py);
202 if (PyErr_Occurred())
204 if (PyErr_ExceptionMatches(PyExc_OverflowError))
205 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
214 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
217 if (!bup_ulong_from_py(&tmp, py, name))
222 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
225 *x = (unsigned int) tmp;
229 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
232 #if PY_MAJOR_VERSION < 3
236 if (bup_ulong_from_pyint(&tmp, py, name))
245 if (!PyLong_Check(py))
247 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
251 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
252 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
254 if (PyErr_ExceptionMatches(PyExc_OverflowError))
255 PyErr_Format(PyExc_OverflowError,
256 "%s too big for unsigned long long", name);
264 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
266 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
267 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
270 Py_ssize_t s1_len, s2_len;
271 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
273 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
275 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
276 const int cmp = memcmp(s1, s2, n);
278 return PyLong_FromLong(cmp);
279 if (s1_len == s2_len)
280 return PyLong_FromLong(0);;
281 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
285 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
287 unsigned char *bufx = NULL, *bufy = NULL;
288 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
289 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
290 if (!PyArg_ParseTuple(args,
293 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
294 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
297 return PyErr_Format(PyExc_ValueError, "negative x offset");
299 return PyErr_Format(PyExc_ValueError, "negative x extent");
300 if (bufx_ofs > bufx_len)
301 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
302 if (bufx_n > bufx_len - bufx_ofs)
303 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
306 return PyErr_Format(PyExc_ValueError, "negative y offset");
308 return PyErr_Format(PyExc_ValueError, "negative y extent");
309 if (bufy_ofs > bufy_len)
310 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
311 if (bufy_n > bufy_len - bufy_ofs)
312 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
314 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
315 return PyErr_Format(PyExc_OverflowError, "result length too long");
317 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
319 return PyErr_NoMemory();
320 char *buf = PyBytes_AS_STRING(result);
321 memcpy(buf, bufx + bufx_ofs, bufx_n);
322 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
327 static int write_all(int fd, const void *buf, const size_t count)
330 while (written < count)
332 const ssize_t rc = write(fd, buf + written, count - written);
341 static inline int uadd(unsigned long long *dest,
342 const unsigned long long x,
343 const unsigned long long y)
345 return INT_ADD_OK(x, y, dest);
349 static PyObject *append_sparse_region(const int fd, unsigned long long n)
354 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
356 const off_t off = lseek(fd, new_off, SEEK_CUR);
357 if (off == (off_t) -1)
358 return PyErr_SetFromErrno(PyExc_IOError);
365 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
367 unsigned long long prev_pending,
368 const unsigned long long count)
370 // Add count additional sparse zeros to prev_pending and store the
371 // result in new_pending, or if the total won't fit in
372 // new_pending, write some of the zeros to fd sparsely, and store
373 // the remaining sum in new_pending.
374 if (!uadd(new_pending, prev_pending, count))
376 PyObject *err = append_sparse_region(fd, prev_pending);
379 *new_pending = count;
385 static byte* find_not_zero(const byte * const start, const byte * const end)
387 // Return a pointer to first non-zero byte between start and end,
388 // or end if there isn't one.
389 assert(start <= end);
390 const unsigned char *cur = start;
391 while (cur < end && *cur == 0)
397 static byte* find_trailing_zeros(const byte * const start,
398 const byte * const end)
400 // Return a pointer to the start of any trailing run of zeros, or
401 // end if there isn't one.
402 assert(start <= end);
405 const byte * cur = end;
406 while (cur > start && *--cur == 0) {}
410 return (byte *) (cur + 1);
414 static byte *find_non_sparse_end(const byte * const start,
415 const byte * const end,
416 const ptrdiff_t min_len)
418 // Return the first pointer to a min_len sparse block in [start,
419 // end) if there is one, otherwise a pointer to the start of any
420 // trailing run of zeros. If there are no trailing zeros, return
426 // Probe in min_len jumps, searching backward from the jump
427 // destination for a non-zero byte. If such a byte is found, move
428 // just past it and try again.
429 const byte *candidate = start;
430 // End of any run of zeros, starting at candidate, that we've already seen
431 const byte *end_of_known_zeros = candidate;
432 while (end - candidate >= min_len) // Handle all min_len candidate blocks
434 const byte * const probe_end = candidate + min_len;
435 const byte * const trailing_zeros =
436 find_trailing_zeros(end_of_known_zeros, probe_end);
437 if (trailing_zeros == probe_end)
438 end_of_known_zeros = candidate = probe_end;
439 else if (trailing_zeros == end_of_known_zeros)
441 assert(candidate >= start);
442 assert(candidate <= end);
443 assert(*candidate == 0);
444 return (byte *) candidate;
448 candidate = trailing_zeros;
449 end_of_known_zeros = probe_end;
453 if (candidate == end)
456 // No min_len sparse run found, search backward from end
457 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
460 if (trailing_zeros == end_of_known_zeros)
462 assert(candidate >= start);
463 assert(candidate < end);
464 assert(*candidate == 0);
465 assert(end - candidate < min_len);
466 return (byte *) candidate;
469 if (trailing_zeros == end)
471 assert(*(end - 1) != 0);
475 assert(end - trailing_zeros < min_len);
476 assert(trailing_zeros >= start);
477 assert(trailing_zeros < end);
478 assert(*trailing_zeros == 0);
479 return (byte *) trailing_zeros;
483 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
486 unsigned char *buf = NULL;
488 PyObject *py_min_sparse_len, *py_prev_sparse_len;
489 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
490 &fd, &buf, &sbuf_len,
491 &py_min_sparse_len, &py_prev_sparse_len))
493 ptrdiff_t min_sparse_len;
494 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
495 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
497 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
498 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
499 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
502 return PyErr_Format(PyExc_ValueError, "negative bufer length");
503 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
504 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
506 const byte * block = buf; // Start of pending block
507 const byte * const end = buf + buf_len;
508 unsigned long long zeros = prev_sparse_len;
511 assert(block <= end);
513 return PyLong_FromUnsignedLongLong(zeros);
517 // Look for the end of block, i.e. the next sparse run of
518 // at least min_sparse_len zeros, or the end of the
520 const byte * const probe = find_non_sparse_end(block + 1, end,
522 // Either at end of block, or end of non-sparse; write pending data
523 PyObject *err = append_sparse_region(fd, zeros);
526 int rc = write_all(fd, block, probe - block);
528 return PyErr_SetFromErrno(PyExc_IOError);
530 if (end - probe < min_sparse_len)
533 zeros = min_sparse_len;
534 block = probe + zeros;
538 // Should be in the first loop iteration, a sparse run of
539 // zeros, or nearly at the end of the block (within
541 const byte * const zeros_end = find_not_zero(block, end);
542 PyObject *err = record_sparse_zeros(&zeros, fd,
543 zeros, zeros_end - block);
546 assert(block <= zeros_end);
553 static PyObject *selftest(PyObject *self, PyObject *args)
555 if (!PyArg_ParseTuple(args, ""))
558 return Py_BuildValue("i", !bupsplit_selftest());
562 static PyObject *blobbits(PyObject *self, PyObject *args)
564 if (!PyArg_ParseTuple(args, ""))
566 return Py_BuildValue("i", BUP_BLOBBITS);
570 static PyObject *splitbuf(PyObject *self, PyObject *args)
572 // We stick to buffers in python 2 because they appear to be
573 // substantially smaller than memoryviews, and because
574 // zlib.compress() in python 2 can't accept a memoryview
575 // (cf. hashsplit.py).
576 int out = 0, bits = -1;
577 if (PY_MAJOR_VERSION > 2)
580 if (!PyArg_ParseTuple(args, "y*", &buf))
582 assert(buf.len <= INT_MAX);
583 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
584 PyBuffer_Release(&buf);
588 unsigned char *buf = NULL;
590 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
592 assert(len <= INT_MAX);
593 out = bupsplit_find_ofs(buf, (int) len, &bits);
595 if (out) assert(bits >= BUP_BLOBBITS);
596 return Py_BuildValue("ii", out, bits);
600 static PyObject *bitmatch(PyObject *self, PyObject *args)
602 unsigned char *buf1 = NULL, *buf2 = NULL;
603 Py_ssize_t len1 = 0, len2 = 0;
607 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
611 for (byte = 0; byte < len1 && byte < len2; byte++)
613 int b1 = buf1[byte], b2 = buf2[byte];
616 for (bit = 0; bit < 8; bit++)
617 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
623 assert(byte <= (INT_MAX >> 3));
624 return Py_BuildValue("i", byte*8 + bit);
628 static PyObject *firstword(PyObject *self, PyObject *args)
630 unsigned char *buf = NULL;
634 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
640 v = ntohl(*(uint32_t *)buf);
641 return PyLong_FromUnsignedLong(v);
645 #define BLOOM2_HEADERLEN 16
647 static void to_bloom_address_bitmask4(const unsigned char *buf,
648 const int nbits, uint64_t *v, unsigned char *bitmask)
654 memcpy(&high, buf, 4);
655 mask = (1<<nbits) - 1;
656 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
657 bit = (raw >> (37-nbits)) & 0x7;
658 *v = (raw >> (40-nbits)) & mask;
662 static void to_bloom_address_bitmask5(const unsigned char *buf,
663 const int nbits, uint32_t *v, unsigned char *bitmask)
669 memcpy(&high, buf, 4);
670 mask = (1<<nbits) - 1;
672 bit = (raw >> (29-nbits)) & 0x7;
673 *v = (raw >> (32-nbits)) & mask;
677 #define BLOOM_SET_BIT(name, address, otype) \
678 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
680 unsigned char bitmask;\
682 address(buf, nbits, &v, &bitmask);\
683 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
685 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
686 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
689 #define BLOOM_GET_BIT(name, address, otype) \
690 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
692 unsigned char bitmask;\
694 address(buf, nbits, &v, &bitmask);\
695 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
697 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
698 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
701 static PyObject *bloom_add(PyObject *self, PyObject *args)
703 Py_buffer bloom, sha;
704 int nbits = 0, k = 0;
705 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
706 &bloom, &sha, &nbits, &k))
709 PyObject *result = NULL;
711 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
712 goto clean_and_return;
717 goto clean_and_return;
718 unsigned char *cur = sha.buf;
720 for (end = cur + sha.len; cur < end; cur += 20/k)
721 bloom_set_bit5(bloom.buf, cur, nbits);
726 goto clean_and_return;
727 unsigned char *cur = sha.buf;
728 unsigned char *end = cur + sha.len;
729 for (; cur < end; cur += 20/k)
730 bloom_set_bit4(bloom.buf, cur, nbits);
733 goto clean_and_return;
735 result = Py_BuildValue("n", sha.len / 20);
738 PyBuffer_Release(&bloom);
739 PyBuffer_Release(&sha);
743 static PyObject *bloom_contains(PyObject *self, PyObject *args)
746 unsigned char *sha = NULL;
748 int nbits = 0, k = 0;
749 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
750 &bloom, &sha, &len, &nbits, &k))
753 PyObject *result = NULL;
756 goto clean_and_return;
761 goto clean_and_return;
764 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
765 if (!bloom_get_bit5(bloom.buf, sha, nbits))
767 result = Py_BuildValue("Oi", Py_None, steps);
768 goto clean_and_return;
774 goto clean_and_return;
777 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
778 if (!bloom_get_bit4(bloom.buf, sha, nbits))
780 result = Py_BuildValue("Oi", Py_None, steps);
781 goto clean_and_return;
785 goto clean_and_return;
787 result = Py_BuildValue("ii", 1, k);
790 PyBuffer_Release(&bloom);
795 static uint32_t _extract_bits(unsigned char *buf, int nbits)
799 mask = (1<<nbits) - 1;
800 v = ntohl(*(uint32_t *)buf);
801 v = (v >> (32-nbits)) & mask;
806 static PyObject *extract_bits(PyObject *self, PyObject *args)
808 unsigned char *buf = NULL;
812 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
818 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
823 unsigned char bytes[20];
826 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
828 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
841 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
844 Py_ssize_t low, mid, high;
848 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
850 idxs[*last_i] = NULL;
863 mid = (low + high) / 2;
864 c = _cmp_sha(idx->cur, idxs[mid]->cur);
876 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
881 static uint32_t _get_idx_i(struct idx *idx)
883 if (idx->cur_name == NULL)
884 return idx->name_base;
885 return ntohl(*idx->cur_name) + idx->name_base;
888 #define MIDX4_HEADERLEN 12
890 static PyObject *merge_into(PyObject *self, PyObject *args)
892 struct sha *sha_ptr, *sha_start = NULL;
893 uint32_t *table_ptr, *name_ptr, *name_start;
896 uint32_t count, prefix;
901 PyObject *py_total, *ilist = NULL;
902 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
903 &fmap, &bits, &py_total, &ilist))
906 PyObject *result = NULL;
907 struct idx **idxs = NULL;
908 Py_ssize_t num_i = 0;
909 int *idx_buf_init = NULL;
910 Py_buffer *idx_buf = NULL;
912 if (!bup_uint_from_py(&total, py_total, "total"))
913 goto clean_and_return;
915 num_i = PyList_Size(ilist);
917 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
918 goto clean_and_return;
919 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
920 goto clean_and_return;
921 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
922 goto clean_and_return;
924 for (i = 0; i < num_i; i++)
926 long len, sha_ofs, name_map_ofs;
927 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
928 goto clean_and_return;
929 PyObject *itup = PyList_GetItem(ilist, i);
930 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
931 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
932 &idxs[i]->name_base))
935 idxs[i]->map = idx_buf[i].buf;
936 idxs[i]->bytes = idx_buf[i].len;
937 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
938 idxs[i]->end = &idxs[i]->cur[len];
940 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
942 idxs[i]->cur_name = NULL;
944 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
945 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
946 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
948 Py_ssize_t last_i = num_i - 1;
955 if (count % 102424 == 0 && get_state(self)->istty2)
956 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
957 count*100.0/total, count, total);
959 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
960 while (prefix < new_prefix)
961 table_ptr[prefix++] = htonl(count);
962 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
963 *name_ptr++ = htonl(_get_idx_i(idx));
965 if (idx->cur_name != NULL)
967 _fix_idx_order(idxs, &last_i);
970 while (prefix < ((uint32_t) 1 << bits))
971 table_ptr[prefix++] = htonl(count);
972 assert(count == total);
973 assert(prefix == ((uint32_t) 1 << bits));
974 assert(sha_ptr == sha_start+count);
975 assert(name_ptr == name_start+count);
977 result = PyLong_FromUnsignedLong(count);
982 for (i = 0; i < num_i; i++)
984 PyBuffer_Release(&(idx_buf[i]));
990 for (i = 0; i < num_i; i++)
994 PyBuffer_Release(&fmap);
998 #define FAN_ENTRIES 256
1000 static PyObject *write_idx(PyObject *self, PyObject *args)
1002 char *filename = NULL;
1003 PyObject *py_total, *idx = NULL;
1005 unsigned int total = 0;
1008 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1009 uint64_t *ofs64_ptr;
1010 struct sha *sha_ptr;
1013 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1014 &filename, &fmap, &idx, &py_total))
1017 PyObject *result = NULL;
1019 if (!bup_uint_from_py(&total, py_total, "total"))
1020 goto clean_and_return;
1022 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1024 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1026 goto clean_and_return;
1029 const char idx_header[] = "\377tOc\0\0\0\002";
1030 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1032 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1033 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1034 crc_ptr = (uint32_t *)&sha_ptr[total];
1035 ofs_ptr = (uint32_t *)&crc_ptr[total];
1036 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1039 uint32_t ofs64_count = 0;
1040 for (i = 0; i < FAN_ENTRIES; ++i)
1042 part = PyList_GET_ITEM(idx, i);
1045 if (!INTEGRAL_ASSIGNMENT_FITS(&plen, PyList_GET_SIZE(part))
1046 || UINT32_MAX - count < plen) {
1047 PyErr_Format(PyExc_OverflowError, "too many objects in index part");
1048 goto clean_and_return;
1051 *fan_ptr++ = htonl(count);
1053 for (j = 0; j < plen; ++j)
1055 unsigned char *sha = NULL;
1056 Py_ssize_t sha_len = 0;
1057 PyObject *crc_py, *ofs_py;
1059 unsigned PY_LONG_LONG ofs_ull;
1061 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1062 &sha, &sha_len, &crc_py, &ofs_py))
1063 goto clean_and_return;
1064 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1065 goto clean_and_return;
1066 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1067 goto clean_and_return;
1068 assert(crc <= UINT32_MAX);
1069 assert(ofs_ull <= UINT64_MAX);
1071 if (sha_len != sizeof(struct sha))
1072 goto clean_and_return;
1073 memcpy(sha_ptr++, sha, sizeof(struct sha));
1074 *crc_ptr++ = htonl(crc);
1075 if (ofs > 0x7fffffff)
1077 *ofs64_ptr++ = htonll(ofs);
1078 ofs = 0x80000000 | ofs64_count++;
1080 *ofs_ptr++ = htonl((uint32_t)ofs);
1084 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1087 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1088 goto clean_and_return;
1091 result = PyLong_FromUnsignedLong(count);
1094 PyBuffer_Release(&fmap);
1099 // I would have made this a lower-level function that just fills in a buffer
1100 // with random values, and then written those values from python. But that's
1101 // about 20% slower in my tests, and since we typically generate random
1102 // numbers for benchmarking other parts of bup, any slowness in generating
1103 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1104 // pseudorandom bytes much except for this anyway.
1105 static PyObject *write_random(PyObject *self, PyObject *args)
1107 uint32_t buf[1024/4];
1108 int fd = -1, seed = 0, verbose = 0;
1110 long long len = 0, kbytes = 0, written = 0;
1112 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1117 for (kbytes = 0; kbytes < len/1024; kbytes++)
1120 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1121 buf[i] = (uint32_t) random();
1122 ret = write(fd, buf, sizeof(buf));
1126 if (ret < (int)sizeof(buf))
1128 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1129 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1132 // handle non-multiples of 1024
1136 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1137 buf[i] = (uint32_t) random();
1138 ret = write(fd, buf, len % 1024);
1144 if (kbytes/1024 > 0)
1145 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1146 return Py_BuildValue("L", written);
1150 static PyObject *random_sha(PyObject *self, PyObject *args)
1152 static int seeded = 0;
1153 uint32_t shabuf[20/4];
1158 assert(sizeof(shabuf) == 20);
1159 srandom((unsigned int) time(NULL));
1163 if (!PyArg_ParseTuple(args, ""))
1166 memset(shabuf, 0, sizeof(shabuf));
1167 for (i=0; i < 20/4; i++)
1168 shabuf[i] = (uint32_t) random();
1169 return Py_BuildValue(rbuf_argf, shabuf, 20);
1173 static int _open_noatime(const char *filename, int attrs)
1175 int attrs_noatime, fd;
1178 attrs |= O_NOFOLLOW;
1181 attrs |= O_LARGEFILE;
1183 attrs_noatime = attrs;
1185 attrs_noatime |= O_NOATIME;
1187 fd = open(filename, attrs_noatime);
1188 if (fd < 0 && errno == EPERM)
1190 // older Linux kernels would return EPERM if you used O_NOATIME
1191 // and weren't the file's owner. This pointless restriction was
1192 // relaxed eventually, but we have to handle it anyway.
1193 // (VERY old kernels didn't recognized O_NOATIME, but they would
1194 // just harmlessly ignore it, so this branch won't trigger)
1195 fd = open(filename, attrs);
1201 static PyObject *open_noatime(PyObject *self, PyObject *args)
1203 char *filename = NULL;
1205 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1207 fd = _open_noatime(filename, 0);
1209 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1210 return Py_BuildValue("i", fd);
1214 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1217 long long llofs, lllen = 0;
1218 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1221 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1222 return PyErr_Format(PyExc_OverflowError,
1223 "fadvise offset overflows off_t");
1224 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1225 return PyErr_Format(PyExc_OverflowError,
1226 "fadvise length overflows off_t");
1227 #ifdef POSIX_FADV_DONTNEED
1228 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1230 return Py_BuildValue("");
1234 // Currently the Linux kernel and FUSE disagree over the type for
1235 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1236 // but FUSE chose long (matching the declaration in linux/fs.h). So
1237 // if you use int, and then traverse a FUSE filesystem, you may
1238 // corrupt the stack. But if you use long, then you may get invalid
1239 // results on big-endian systems.
1241 // For now, we just use long, and then disable Linux attrs entirely
1242 // (with a warning) in helpers.py on systems that are affected.
1244 #ifdef BUP_HAVE_FILE_ATTRS
1245 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1252 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1255 fd = _open_noatime(path, O_NONBLOCK);
1257 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1259 attr = 0; // Handle int/long mismatch (see above)
1260 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1264 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1267 assert(attr <= UINT_MAX); // Kernel type is actually int
1268 return PyLong_FromUnsignedLong(attr);
1270 #endif /* def BUP_HAVE_FILE_ATTRS */
1274 #ifdef BUP_HAVE_FILE_ATTRS
1275 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1278 unsigned long orig_attr;
1284 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1287 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1290 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1292 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1294 // Restrict attr to modifiable flags acdeijstuADST -- see
1295 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1296 // in pf.c flags_array[].
1297 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1298 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1299 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1300 | FS_TOPDIR_FL | FS_NOCOW_FL;
1302 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1303 orig_attr = 0; // Handle int/long mismatch (see above)
1304 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1308 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1310 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1311 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1313 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1317 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1321 return Py_BuildValue("O", Py_None);
1323 #endif /* def BUP_HAVE_FILE_ATTRS */
1326 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
1327 #ifndef HAVE_UTIMENSAT
1329 #error "cannot find utimensat or utimes()"
1331 #ifndef HAVE_LUTIMES
1332 #error "cannot find utimensat or lutimes()"
1335 #endif // defined BUP_USE_PYTHON_UTIME
1337 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1341 const long long lltmp = PyLong_AsLongLong(pylong); \
1342 if (lltmp == -1 && PyErr_Occurred()) \
1344 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1346 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1347 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1349 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1355 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1363 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1372 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
1373 #ifdef HAVE_UTIMENSAT
1375 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1380 PyObject *access_py, *modification_py;
1381 struct timespec ts[2];
1383 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1386 &access_py, &(ts[0].tv_nsec),
1387 &modification_py, &(ts[1].tv_nsec),
1392 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1395 PyErr_SetString(PyExc_ValueError,
1396 "unable to convert access time seconds for utimensat");
1399 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1402 PyErr_SetString(PyExc_ValueError,
1403 "unable to convert modification time seconds for utimensat");
1406 rc = utimensat(fd, path, ts, flag);
1408 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1410 return Py_BuildValue("O", Py_None);
1413 #endif /* def HAVE_UTIMENSAT */
1416 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1418 static int bup_parse_xutimes_args(char **path,
1419 struct timeval tv[2],
1422 PyObject *access_py, *modification_py;
1423 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1425 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1427 &access_py, &access_us,
1428 &modification_py, &modification_us))
1432 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1435 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1438 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1440 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1443 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1446 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1449 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1451 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1457 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1461 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1464 struct timeval tv[2];
1465 if (!bup_parse_xutimes_args(&path, tv, args))
1467 int rc = utimes(path, tv);
1469 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1470 return Py_BuildValue("O", Py_None);
1472 #endif /* def HAVE_UTIMES */
1476 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1479 struct timeval tv[2];
1480 if (!bup_parse_xutimes_args(&path, tv, args))
1482 int rc = lutimes(path, tv);
1484 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1486 return Py_BuildValue("O", Py_None);
1488 #endif /* def HAVE_LUTIMES */
1490 #endif // defined BUP_USE_PYTHON_UTIME
1493 #ifdef HAVE_STAT_ST_ATIM
1494 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1495 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1496 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1497 #elif defined HAVE_STAT_ST_ATIMENSEC
1498 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1499 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1500 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1502 # define BUP_STAT_ATIME_NS(st) 0
1503 # define BUP_STAT_MTIME_NS(st) 0
1504 # define BUP_STAT_CTIME_NS(st) 0
1508 static PyObject *stat_struct_to_py(const struct stat *st,
1509 const char *filename,
1512 // We can check the known (via POSIX) signed and unsigned types at
1513 // compile time, but not (easily) the unspecified types, so handle
1514 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1516 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1517 INTEGER_TO_PY(st->st_mode),
1518 (unsigned PY_LONG_LONG) st->st_ino,
1519 INTEGER_TO_PY(st->st_dev),
1520 INTEGER_TO_PY(st->st_nlink),
1521 INTEGER_TO_PY(st->st_uid),
1522 INTEGER_TO_PY(st->st_gid),
1523 INTEGER_TO_PY(st->st_rdev),
1524 (PY_LONG_LONG) st->st_size,
1525 INTEGER_TO_PY(st->st_atime),
1526 (long) BUP_STAT_ATIME_NS(st),
1527 INTEGER_TO_PY(st->st_mtime),
1528 (long) BUP_STAT_MTIME_NS(st),
1529 INTEGER_TO_PY(st->st_ctime),
1530 (long) BUP_STAT_CTIME_NS(st));
1534 static PyObject *bup_stat(PyObject *self, PyObject *args)
1539 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1543 rc = stat(filename, &st);
1545 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1546 return stat_struct_to_py(&st, filename, 0);
1550 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1555 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1559 rc = lstat(filename, &st);
1561 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1562 return stat_struct_to_py(&st, filename, 0);
1566 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1570 if (!PyArg_ParseTuple(args, "i", &fd))
1574 rc = fstat(fd, &st);
1576 return PyErr_SetFromErrno(PyExc_OSError);
1577 return stat_struct_to_py(&st, NULL, fd);
1581 #ifdef HAVE_TM_TM_GMTOFF
1582 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1586 if (!PyArg_ParseTuple(args, "L", &lltime))
1588 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1589 return PyErr_Format(PyExc_OverflowError, "time value too large");
1593 if(localtime_r(&ttime, &tm) == NULL)
1594 return PyErr_SetFromErrno(PyExc_OSError);
1596 // Match the Python struct_time values.
1597 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1598 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1599 tm.tm_hour, tm.tm_min, tm.tm_sec,
1600 tm.tm_wday, tm.tm_yday + 1,
1601 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1603 #endif /* def HAVE_TM_TM_GMTOFF */
1606 #ifdef BUP_MINCORE_BUF_TYPE
1607 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1609 Py_buffer src, dest;
1610 PyObject *py_src_n, *py_src_off, *py_dest_off;
1612 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1613 &src, &py_src_n, &py_src_off,
1614 &dest, &py_dest_off))
1617 PyObject *result = NULL;
1619 unsigned long long src_n, src_off, dest_off;
1620 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1621 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1622 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1623 goto clean_and_return;
1625 unsigned long long src_region_end;
1626 if (!uadd(&src_region_end, src_off, src_n)) {
1627 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1628 goto clean_and_return;
1630 assert(src.len >= 0);
1631 if (src_region_end > (unsigned long long) src.len) {
1632 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1633 goto clean_and_return;
1636 unsigned long long dest_size;
1637 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1638 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1639 goto clean_and_return;
1641 if (dest_off > dest_size) {
1642 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1643 goto clean_and_return;
1647 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1648 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1649 goto clean_and_return;
1651 int rc = mincore((void *)(src.buf + src_off), length,
1652 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1654 result = PyErr_SetFromErrno(PyExc_OSError);
1655 goto clean_and_return;
1657 result = Py_BuildValue("O", Py_None);
1660 PyBuffer_Release(&src);
1661 PyBuffer_Release(&dest);
1664 #endif /* def BUP_MINCORE_BUF_TYPE */
1666 static unsigned int vuint_encode(long long val, char *buf)
1668 unsigned int len = 0;
1671 PyErr_SetString(PyExc_Exception, "vuints must not be negative");
1676 buf[len] = val & 0x7f;
1688 static unsigned int vint_encode(long long val, char *buf)
1690 unsigned int len = 1;
1698 buf[0] = (val & 0x3f) | sign;
1704 buf[len] = val & 0x7f;
1714 static PyObject *bup_vuint_encode(PyObject *self, PyObject *args)
1717 // size the buffer appropriately - need 8 bits to encode each 7
1718 char buf[(sizeof(val) + 1) / 7 * 8];
1720 if (!PyArg_ParseTuple(args, "L", &val))
1723 unsigned int len = vuint_encode(val, buf);
1727 return PyBytes_FromStringAndSize(buf, len);
1730 static PyObject *bup_vint_encode(PyObject *self, PyObject *args)
1733 // size the buffer appropriately - need 8 bits to encode each 7
1734 char buf[(sizeof(val) + 1) / 7 * 8];
1736 if (!PyArg_ParseTuple(args, "L", &val))
1739 return PyBytes_FromStringAndSize(buf, vint_encode(val, buf));
1742 static PyObject *tuple_from_cstrs(char **cstrs)
1744 // Assumes list is null terminated
1746 while(cstrs[n] != NULL)
1750 if (!INTEGRAL_ASSIGNMENT_FITS(&sn, n))
1751 return PyErr_Format(PyExc_OverflowError, "string array too large");
1753 PyObject *result = PyTuple_New(sn);
1755 for (i = 0; i < sn; i++)
1757 PyObject *gname = Py_BuildValue(cstr_argf, cstrs[i]);
1763 PyTuple_SET_ITEM(result, i, gname);
1768 static PyObject *appropriate_errno_ex(void)
1772 return PyErr_NoMemory();
1776 // In 3.3 IOError was merged into OSError.
1777 return PyErr_SetFromErrno(PyExc_IOError);
1779 return PyErr_SetFromErrno(PyExc_OSError);
1784 static PyObject *pwd_struct_to_py(const struct passwd *pwd)
1786 // We can check the known (via POSIX) signed and unsigned types at
1787 // compile time, but not (easily) the unspecified types, so handle
1788 // those via INTEGER_TO_PY().
1791 return Py_BuildValue(cstr_argf cstr_argf "OO"
1792 cstr_argf cstr_argf cstr_argf,
1795 INTEGER_TO_PY(pwd->pw_uid),
1796 INTEGER_TO_PY(pwd->pw_gid),
1802 static PyObject *bup_getpwuid(PyObject *self, PyObject *args)
1804 unsigned long long py_uid;
1805 if (!PyArg_ParseTuple(args, "K", &py_uid))
1808 if (!INTEGRAL_ASSIGNMENT_FITS(&uid, py_uid))
1809 return PyErr_Format(PyExc_OverflowError, "uid too large for uid_t");
1812 struct passwd *pwd = getpwuid(uid);
1814 return appropriate_errno_ex();
1815 return pwd_struct_to_py(pwd);
1818 static PyObject *bup_getpwnam(PyObject *self, PyObject *args)
1821 if (!PyArg_ParseTuple(args, "S", &py_name))
1824 char *name = PyBytes_AS_STRING(py_name);
1826 struct passwd *pwd = getpwnam(name);
1828 return appropriate_errno_ex();
1829 return pwd_struct_to_py(pwd);
1832 static PyObject *grp_struct_to_py(const struct group *grp)
1834 // We can check the known (via POSIX) signed and unsigned types at
1835 // compile time, but not (easily) the unspecified types, so handle
1836 // those via INTEGER_TO_PY().
1840 PyObject *members = tuple_from_cstrs(grp->gr_mem);
1841 if (members == NULL)
1843 return Py_BuildValue(cstr_argf cstr_argf "OO",
1846 INTEGER_TO_PY(grp->gr_gid),
1850 static PyObject *bup_getgrgid(PyObject *self, PyObject *args)
1852 unsigned long long py_gid;
1853 if (!PyArg_ParseTuple(args, "K", &py_gid))
1856 if (!INTEGRAL_ASSIGNMENT_FITS(&gid, py_gid))
1857 return PyErr_Format(PyExc_OverflowError, "gid too large for gid_t");
1860 struct group *grp = getgrgid(gid);
1862 return appropriate_errno_ex();
1863 return grp_struct_to_py(grp);
1866 static PyObject *bup_getgrnam(PyObject *self, PyObject *args)
1869 if (!PyArg_ParseTuple(args, "S", &py_name))
1872 char *name = PyBytes_AS_STRING(py_name);
1874 struct group *grp = getgrnam(name);
1876 return appropriate_errno_ex();
1877 return grp_struct_to_py(grp);
1881 static PyObject *bup_gethostname(PyObject *mod, PyObject *ignore)
1883 #ifdef HOST_NAME_MAX
1884 char buf[HOST_NAME_MAX + 1] = {};
1886 /* 'SUSv2 guarantees that "Host names are limited to 255 bytes".' */
1890 if (gethostname(buf, sizeof(buf) - 1))
1891 return PyErr_SetFromErrno(PyExc_IOError);
1892 return PyBytes_FromString(buf);
1896 #ifdef BUP_HAVE_READLINE
1898 static char *cstr_from_bytes(PyObject *bytes)
1902 int rc = PyBytes_AsStringAndSize(bytes, &buf, &length);
1906 if (!INT_ADD_OK(length, 1, &c_len)) {
1907 PyErr_Format(PyExc_OverflowError,
1908 "Cannot convert ssize_t sized bytes object (%zd) to C string",
1912 char *result = checked_malloc(c_len, sizeof(char));
1915 memcpy(result, buf, length);
1920 static char **cstrs_from_seq(PyObject *seq)
1922 char **result = NULL;
1923 seq = PySequence_Fast(seq, "Cannot convert sequence items to C strings");
1927 const Py_ssize_t len = PySequence_Fast_GET_SIZE(seq);
1928 if (len > PY_SSIZE_T_MAX - 1) {
1929 PyErr_Format(PyExc_OverflowError,
1930 "Sequence length %zd too large for conversion to C array",
1934 result = checked_malloc(len + 1, sizeof(char *));
1938 for (i = 0; i < len; i++)
1940 PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
1942 goto abandon_result;
1943 result[i] = cstr_from_bytes(item);
1946 goto abandon_result;
1964 static char* our_word_break_chars = NULL;
1967 bup_set_completer_word_break_characters(PyObject *self, PyObject *args)
1970 if (!PyArg_ParseTuple(args, cstr_argf, &bytes))
1972 char *prev = our_word_break_chars;
1973 char *next = strdup(bytes);
1975 return PyErr_NoMemory();
1976 our_word_break_chars = next;
1977 rl_completer_word_break_characters = next;
1984 bup_get_completer_word_break_characters(PyObject *self, PyObject *args)
1986 return PyBytes_FromString(rl_completer_word_break_characters);
1989 static PyObject *bup_get_line_buffer(PyObject *self, PyObject *args)
1991 return PyBytes_FromString(rl_line_buffer);
1995 bup_parse_and_bind(PyObject *self, PyObject *args)
1998 if (!PyArg_ParseTuple(args, cstr_argf ":parse_and_bind", &bytes))
2000 char *tmp = strdup(bytes); // Because it may modify the arg
2002 return PyErr_NoMemory();
2003 int rc = rl_parse_and_bind(tmp);
2006 return PyErr_Format(PyExc_OSError,
2007 "system rl_parse_and_bind failed (%d)", rc);
2012 static PyObject *py_on_attempted_completion;
2013 static char **prev_completions;
2015 static char **on_attempted_completion(const char *text, int start, int end)
2017 if (!py_on_attempted_completion)
2020 char **result = NULL;
2021 PyObject *py_result = PyObject_CallFunction(py_on_attempted_completion,
2026 if (py_result != Py_None) {
2027 result = cstrs_from_seq(py_result);
2028 free(prev_completions);
2029 prev_completions = result;
2031 Py_DECREF(py_result);
2036 bup_set_attempted_completion_function(PyObject *self, PyObject *args)
2038 PyObject *completer;
2039 if (!PyArg_ParseTuple(args, "O", &completer))
2042 PyObject *prev = py_on_attempted_completion;
2043 if (completer == Py_None)
2045 py_on_attempted_completion = NULL;
2046 rl_attempted_completion_function = NULL;
2048 py_on_attempted_completion = completer;
2049 rl_attempted_completion_function = on_attempted_completion;
2050 Py_INCREF(completer);
2057 static PyObject *py_on_completion_entry;
2059 static char *on_completion_entry(const char *text, int state)
2061 if (!py_on_completion_entry)
2064 PyObject *py_result = PyObject_CallFunction(py_on_completion_entry,
2065 cstr_argf "i", text, state);
2068 char *result = (py_result == Py_None) ? NULL : cstr_from_bytes(py_result);
2069 Py_DECREF(py_result);
2074 bup_set_completion_entry_function(PyObject *self, PyObject *args)
2076 PyObject *completer;
2077 if (!PyArg_ParseTuple(args, "O", &completer))
2080 PyObject *prev = py_on_completion_entry;
2081 if (completer == Py_None) {
2082 py_on_completion_entry = NULL;
2083 rl_completion_entry_function = NULL;
2085 py_on_completion_entry = completer;
2086 rl_completion_entry_function = on_completion_entry;
2087 Py_INCREF(completer);
2094 bup_readline(PyObject *self, PyObject *args)
2097 if (!PyArg_ParseTuple(args, cstr_argf, &prompt))
2099 char *line = readline(prompt);
2101 return PyErr_Format(PyExc_EOFError, "readline EOF");
2102 PyObject *result = PyBytes_FromString(line);
2107 #endif // defined BUP_HAVE_READLINE
2109 #if defined(HAVE_SYS_ACL_H) && \
2110 defined(HAVE_ACL_LIBACL_H) && \
2111 defined(HAVE_ACL_EXTENDED_FILE) && \
2112 defined(HAVE_ACL_GET_FILE) && \
2113 defined(HAVE_ACL_TO_ANY_TEXT) && \
2114 defined(HAVE_ACL_FROM_TEXT) && \
2115 defined(HAVE_ACL_SET_FILE)
2116 #define ACL_SUPPORT 1
2117 #include <sys/acl.h>
2118 #include <acl/libacl.h>
2122 // -1 for errors, with python exception set
2123 // -2 for ignored errors (not supported)
2124 static int bup_read_acl_to_text(const char *name, acl_type_t type,
2125 char **txt, char **num)
2129 acl = acl_get_file(name, type);
2131 if (errno == EOPNOTSUPP || errno == ENOSYS)
2133 PyErr_SetFromErrno(PyExc_IOError);
2138 *txt = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE);
2140 *num = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE | TEXT_NUMERIC_IDS);
2145 if (errno == ENOMEM)
2148 PyErr_SetFromErrno(PyExc_IOError);
2151 acl_free((acl_t)*txt);
2153 acl_free((acl_t)*num);
2158 static PyObject *bup_read_acl(PyObject *self, PyObject *args)
2162 PyObject *ret = NULL;
2163 char *acl_txt = NULL, *acl_num = NULL;
2165 if (!PyArg_ParseTuple(args, cstr_argf "i", &name, &isdir))
2168 if (!acl_extended_file(name))
2171 rv = bup_read_acl_to_text(name, ACL_TYPE_ACCESS, &acl_txt, &acl_num);
2176 char *def_txt = NULL, *def_num = NULL;
2178 rv = bup_read_acl_to_text(name, ACL_TYPE_DEFAULT, &def_txt, &def_num);
2182 ret = Py_BuildValue("[" cstr_argf cstr_argf cstr_argf cstr_argf "]",
2183 acl_txt, acl_num, def_txt, def_num);
2186 acl_free((acl_t)def_txt);
2188 acl_free((acl_t)def_num);
2190 ret = Py_BuildValue("[" cstr_argf cstr_argf "]",
2196 acl_free((acl_t)acl_txt);
2198 acl_free((acl_t)acl_num);
2204 static int bup_apply_acl_string(const char *name, const char *s)
2206 acl_t acl = acl_from_text(s);
2210 PyErr_SetFromErrno(PyExc_IOError);
2214 if (acl_set_file(name, ACL_TYPE_ACCESS, acl)) {
2215 PyErr_SetFromErrno(PyExc_IOError);
2224 static PyObject *bup_apply_acl(PyObject *self, PyObject *args)
2226 char *name, *acl, *def = NULL;
2228 if (!PyArg_ParseTuple(args, cstr_argf cstr_argf "|" cstr_argf, &name, &acl, &def))
2231 if (bup_apply_acl_string(name, acl))
2234 if (def && bup_apply_acl_string(name, def))
2241 static PyObject *bup_limited_vint_pack(PyObject *self, PyObject *args)
2244 PyObject *packargs, *result;
2245 Py_ssize_t sz, i, bufsz;
2246 char *buf, *pos, *end;
2248 if (!PyArg_ParseTuple(args, "sO", &fmt, &packargs))
2251 if (!PyTuple_Check(packargs))
2252 return PyErr_Format(PyExc_Exception, "pack() arg must be tuple");
2254 sz = PyTuple_GET_SIZE(packargs);
2255 if (sz != (Py_ssize_t)strlen(fmt))
2256 return PyErr_Format(PyExc_Exception,
2257 "number of arguments (%ld) does not match format string (%ld)",
2258 (unsigned long)sz, (unsigned long)strlen(fmt));
2260 if (sz > INT_MAX / 20)
2261 return PyErr_Format(PyExc_Exception, "format is far too long");
2263 // estimate no more than 20 bytes for each on average, the maximum
2264 // vint/vuint we can encode is anyway 10 bytes, so this gives us
2265 // some headroom for a few strings before we need to realloc ...
2267 buf = malloc(bufsz);
2269 return PyErr_NoMemory();
2273 for (i = 0; i < sz; i++) {
2274 PyObject *item = PyTuple_GET_ITEM(packargs, i);
2279 long long val = PyLong_AsLongLong(item);
2280 if (val == -1 && PyErr_Occurred())
2281 return PyErr_Format(PyExc_OverflowError,
2282 "pack arg %d invalid", (int)i);
2285 pos += vuint_encode(val, pos);
2289 long long val = PyLong_AsLongLong(item);
2290 if (val == -1 && PyErr_Occurred())
2291 return PyErr_Format(PyExc_OverflowError,
2292 "pack arg %d invalid", (int)i);
2295 pos += vint_encode(val, pos);
2299 bytes = PyBytes_AsString(item);
2304 Py_ssize_t val = PyBytes_GET_SIZE(item);
2305 pos += vuint_encode(val, pos);
2306 if (end - pos < val)
2308 memcpy(pos, bytes, val);
2313 PyErr_Format(PyExc_Exception, "unknown xpack format string item %c",
2319 result = PyBytes_FromStringAndSize(buf, pos - buf);
2324 PyErr_SetString(PyExc_OverflowError, "buffer (potentially) overflowed");
2330 static PyMethodDef helper_methods[] = {
2331 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
2332 "Write buf excepting zeros at the end. Return trailing zero count." },
2333 { "selftest", selftest, METH_VARARGS,
2334 "Check that the rolling checksum rolls correctly (for unit tests)." },
2335 { "blobbits", blobbits, METH_VARARGS,
2336 "Return the number of bits in the rolling checksum." },
2337 { "splitbuf", splitbuf, METH_VARARGS,
2338 "Split a list of strings based on a rolling checksum." },
2339 { "bitmatch", bitmatch, METH_VARARGS,
2340 "Count the number of matching prefix bits between two strings." },
2341 { "firstword", firstword, METH_VARARGS,
2342 "Return an int corresponding to the first 32 bits of buf." },
2343 { "bloom_contains", bloom_contains, METH_VARARGS,
2344 "Check if a bloom filter of 2^nbits bytes contains an object" },
2345 { "bloom_add", bloom_add, METH_VARARGS,
2346 "Add an object to a bloom filter of 2^nbits bytes" },
2347 { "extract_bits", extract_bits, METH_VARARGS,
2348 "Take the first 'nbits' bits from 'buf' and return them as an int." },
2349 { "merge_into", merge_into, METH_VARARGS,
2350 "Merges a bunch of idx and midx files into a single midx." },
2351 { "write_idx", write_idx, METH_VARARGS,
2352 "Write a PackIdxV2 file from an idx list of lists of tuples" },
2353 { "write_random", write_random, METH_VARARGS,
2354 "Write random bytes to the given file descriptor" },
2355 { "random_sha", random_sha, METH_VARARGS,
2356 "Return a random 20-byte string" },
2357 { "open_noatime", open_noatime, METH_VARARGS,
2358 "open() the given filename for read with O_NOATIME if possible" },
2359 { "fadvise_done", fadvise_done, METH_VARARGS,
2360 "Inform the kernel that we're finished with earlier parts of a file" },
2361 #ifdef BUP_HAVE_FILE_ATTRS
2362 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
2363 "Return the Linux attributes for the given file." },
2365 #ifdef BUP_HAVE_FILE_ATTRS
2366 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
2367 "Set the Linux attributes for the given file." },
2370 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
2371 #ifdef HAVE_UTIMENSAT
2372 { "bup_utimensat", bup_utimensat, METH_VARARGS,
2373 "Change path timestamps with nanosecond precision (POSIX)." },
2376 { "bup_utimes", bup_utimes, METH_VARARGS,
2377 "Change path timestamps with microsecond precision." },
2380 { "bup_lutimes", bup_lutimes, METH_VARARGS,
2381 "Change path timestamps with microsecond precision;"
2382 " don't follow symlinks." },
2384 #endif // defined BUP_USE_PYTHON_UTIME
2386 { "stat", bup_stat, METH_VARARGS,
2387 "Extended version of stat." },
2388 { "lstat", bup_lstat, METH_VARARGS,
2389 "Extended version of lstat." },
2390 { "fstat", bup_fstat, METH_VARARGS,
2391 "Extended version of fstat." },
2392 #ifdef HAVE_TM_TM_GMTOFF
2393 { "localtime", bup_localtime, METH_VARARGS,
2394 "Return struct_time elements plus the timezone offset and name." },
2396 { "bytescmp", bup_bytescmp, METH_VARARGS,
2397 "Return a negative value if x < y, zero if equal, positive otherwise."},
2398 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
2399 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
2400 #ifdef BUP_MINCORE_BUF_TYPE
2401 { "mincore", bup_mincore, METH_VARARGS,
2402 "For mincore(src, src_n, src_off, dest, dest_off)"
2403 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
2405 { "getpwuid", bup_getpwuid, METH_VARARGS,
2406 "Return the password database entry for the given numeric user id,"
2407 " as a tuple with all C strings as bytes(), or None if the user does"
2409 { "getpwnam", bup_getpwnam, METH_VARARGS,
2410 "Return the password database entry for the given user name,"
2411 " as a tuple with all C strings as bytes(), or None if the user does"
2413 { "getgrgid", bup_getgrgid, METH_VARARGS,
2414 "Return the group database entry for the given numeric group id,"
2415 " as a tuple with all C strings as bytes(), or None if the group does"
2417 { "getgrnam", bup_getgrnam, METH_VARARGS,
2418 "Return the group database entry for the given group name,"
2419 " as a tuple with all C strings as bytes(), or None if the group does"
2421 { "gethostname", bup_gethostname, METH_NOARGS,
2422 "Return the current hostname (as bytes)" },
2423 #ifdef BUP_HAVE_READLINE
2424 { "set_completion_entry_function", bup_set_completion_entry_function, METH_VARARGS,
2425 "Set rl_completion_entry_function. Called as f(text, state)." },
2426 { "set_attempted_completion_function", bup_set_attempted_completion_function, METH_VARARGS,
2427 "Set rl_attempted_completion_function. Called as f(text, start, end)." },
2428 { "parse_and_bind", bup_parse_and_bind, METH_VARARGS,
2429 "Call rl_parse_and_bind." },
2430 { "get_line_buffer", bup_get_line_buffer, METH_NOARGS,
2431 "Return rl_line_buffer." },
2432 { "get_completer_word_break_characters", bup_get_completer_word_break_characters, METH_NOARGS,
2433 "Return rl_completer_word_break_characters." },
2434 { "set_completer_word_break_characters", bup_set_completer_word_break_characters, METH_VARARGS,
2435 "Set rl_completer_word_break_characters." },
2436 { "readline", bup_readline, METH_VARARGS,
2437 "Call readline(prompt)." },
2438 #endif // defined BUP_HAVE_READLINE
2440 { "read_acl", bup_read_acl, METH_VARARGS,
2441 "read_acl(name, isdir)\n\n"
2442 "Read ACLs for the given file/dirname and return the correctly encoded"
2443 " list [txt, num, def_tx, def_num] (the def_* being empty bytestrings"
2444 " unless the second argument 'isdir' is True)." },
2445 { "apply_acl", bup_apply_acl, METH_VARARGS,
2446 "apply_acl(name, acl, def=None)\n\n"
2447 "Given a file/dirname (bytes) and the ACLs to restore, do that." },
2448 #endif /* HAVE_ACLS */
2449 { "vuint_encode", bup_vuint_encode, METH_VARARGS, "encode an int to vuint" },
2450 { "vint_encode", bup_vint_encode, METH_VARARGS, "encode an int to vint" },
2451 { "limited_vint_pack", bup_limited_vint_pack, METH_VARARGS,
2452 "Try to pack vint/vuint/str, throwing OverflowError when unable." },
2453 { NULL, NULL, 0, NULL }, // sentinel
2456 static void test_integral_assignment_fits(void)
2458 assert(sizeof(signed short) == sizeof(unsigned short));
2459 assert(sizeof(signed short) < sizeof(signed long long));
2460 assert(sizeof(signed short) < sizeof(unsigned long long));
2461 assert(sizeof(unsigned short) < sizeof(signed long long));
2462 assert(sizeof(unsigned short) < sizeof(unsigned long long));
2463 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
2465 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
2466 unsigned short us, usmax = USHRT_MAX;
2467 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
2468 unsigned long long ullmax = ULLONG_MAX;
2470 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
2471 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
2472 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
2473 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
2474 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
2475 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
2477 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
2478 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
2479 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
2480 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
2481 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
2485 static int setup_module(PyObject *m)
2487 // FIXME: migrate these tests to configure, or at least don't
2488 // possibly crash the whole application. Check against the type
2489 // we're going to use when passing to python. Other stat types
2490 // are tested at runtime.
2491 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
2492 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
2493 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
2494 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
2495 // Just be sure (relevant when passing timestamps back to Python above).
2496 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
2497 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
2498 // At least for INTEGER_TO_PY
2499 assert(sizeof(intmax_t) <= sizeof(long long));
2500 assert(sizeof(uintmax_t) <= sizeof(unsigned long long));
2502 test_integral_assignment_fits();
2504 // Originally required by append_sparse_region()
2507 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
2509 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
2517 value = INTEGER_TO_PY(INT_MAX);
2518 PyObject_SetAttrString(m, "INT_MAX", value);
2520 value = INTEGER_TO_PY(UINT_MAX);
2521 PyObject_SetAttrString(m, "UINT_MAX", value);
2525 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
2526 #ifdef HAVE_UTIMENSAT
2529 value = INTEGER_TO_PY(AT_FDCWD);
2530 PyObject_SetAttrString(m, "AT_FDCWD", value);
2532 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
2533 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
2535 value = INTEGER_TO_PY(UTIME_NOW);
2536 PyObject_SetAttrString(m, "UTIME_NOW", value);
2540 #endif // defined BUP_USE_PYTHON_UTIME
2542 #ifdef BUP_HAVE_MINCORE_INCORE
2545 value = INTEGER_TO_PY(MINCORE_INCORE);
2546 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
2551 e = getenv("BUP_FORCE_TTY");
2552 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
2557 #if PY_MAJOR_VERSION < 3
2559 PyMODINIT_FUNC init_helpers(void)
2561 PyObject *m = Py_InitModule("_helpers", helper_methods);
2563 PyErr_SetString(PyExc_RuntimeError, "bup._helpers init failed");
2566 if (!setup_module(m))
2568 PyErr_SetString(PyExc_RuntimeError, "bup._helpers set up failed");
2574 # else // PY_MAJOR_VERSION >= 3
2576 static struct PyModuleDef helpers_def = {
2577 PyModuleDef_HEAD_INIT,
2583 NULL, // helpers_traverse,
2584 NULL, // helpers_clear,
2588 PyMODINIT_FUNC PyInit__helpers(void)
2590 PyObject *module = PyModule_Create(&helpers_def);
2593 if (!setup_module(module))
2601 #endif // PY_MAJOR_VERSION >= 3