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
10 #include <arpa/inet.h>
22 #ifdef HAVE_SYS_MMAN_H
25 #ifdef HAVE_SYS_TYPES_H
26 #include <sys/types.h>
28 #ifdef HAVE_SYS_STAT_H
34 #ifdef HAVE_SYS_TIME_H
38 #ifdef HAVE_LINUX_FS_H
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
45 #ifdef HAVE_TM_TM_GMTOFF
49 #if defined(BUP_RL_EXPECTED_XOPEN_SOURCE) \
50 && (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < BUP_RL_EXPECTED_XOPEN_SOURCE)
51 # warning "_XOPEN_SOURCE version is incorrect for readline"
54 #ifdef BUP_HAVE_READLINE
55 # pragma GCC diagnostic push
56 # pragma GCC diagnostic ignored "-Wstrict-prototypes"
57 # include <readline/readline.h>
58 # include <readline/history.h>
59 # pragma GCC diagnostic pop
64 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
65 #define BUP_HAVE_FILE_ATTRS 1
69 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
70 * pretend we don't have it.
72 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
77 // Of course, this assumes it's a bitfield value.
82 typedef unsigned char byte;
89 // cstr_argf: for byte vectors without null characters (e.g. paths)
90 // rbuf_argf: for read-only byte vectors
91 // wbuf_argf: for mutable byte vectors
93 #if PY_MAJOR_VERSION < 3
95 # define get_state(x) (&state)
96 # define cstr_argf "s"
97 # define rbuf_argf "s#"
98 # define wbuf_argf "s*"
100 # define get_state(x) ((state_t *) PyModule_GetState(x))
101 # define cstr_argf "y"
102 # define rbuf_argf "y#"
103 # define wbuf_argf "y*"
104 #endif // PY_MAJOR_VERSION >= 3
107 static void *checked_calloc(size_t n, size_t size)
109 void *result = calloc(n, size);
115 #ifndef BUP_HAVE_BUILTIN_MUL_OVERFLOW
117 #define checked_malloc checked_calloc
119 #else // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
121 static void *checked_malloc(size_t n, size_t size)
124 if (__builtin_mul_overflow(n, size, &total))
126 PyErr_Format(PyExc_OverflowError,
127 "request to allocate %lu items of size %lu is too large",
131 void *result = malloc(total);
133 return PyErr_NoMemory();
137 #endif // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
141 // This function should technically be macro'd out if it's going to be used
142 // more than ocasionally. As of this writing, it'll actually never be called
143 // in real world bup scenarios (because our packs are < MAX_INT bytes).
144 static uint64_t htonll(uint64_t value)
146 static const int endian_test = 42;
148 if (*(char *)&endian_test == endian_test) // LSB-MSB
149 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
150 return value; // already in network byte order MSB-LSB
155 // Disabling sign-compare here should be fine since we're explicitly
156 // checking for a sign mismatch, i.e. if the signs don't match, then
157 // it doesn't matter what the value comparison says.
158 // FIXME: ... so should we reverse the order?
159 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
161 _Pragma("GCC diagnostic push"); \
162 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
163 _Pragma("clang diagnostic push"); \
164 _Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\""); \
166 int result = *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
167 _Pragma("clang diagnostic pop"); \
168 _Pragma("GCC diagnostic pop"); \
173 // At the moment any code that calls INTEGER_TO_PY() will have to
174 // disable -Wtautological-compare for clang. See below.
176 #define INTEGER_TO_PY(x) \
177 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
181 #if PY_MAJOR_VERSION < 3
182 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
185 const long tmp = PyInt_AsLong(py);
186 if (tmp == -1 && PyErr_Occurred())
188 if (PyErr_ExceptionMatches(PyExc_OverflowError))
189 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
195 PyErr_Format(PyExc_OverflowError,
196 "negative %s cannot be converted to unsigned long", name);
205 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
207 #if PY_MAJOR_VERSION < 3
209 return bup_ulong_from_pyint(x, py, name);
212 if (!PyLong_Check(py))
214 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
218 const unsigned long tmp = PyLong_AsUnsignedLong(py);
219 if (PyErr_Occurred())
221 if (PyErr_ExceptionMatches(PyExc_OverflowError))
222 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
231 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
234 if (!bup_ulong_from_py(&tmp, py, name))
239 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
242 *x = (unsigned int) tmp;
246 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
249 #if PY_MAJOR_VERSION < 3
253 if (bup_ulong_from_pyint(&tmp, py, name))
262 if (!PyLong_Check(py))
264 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
268 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
269 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
271 if (PyErr_ExceptionMatches(PyExc_OverflowError))
272 PyErr_Format(PyExc_OverflowError,
273 "%s too big for unsigned long long", name);
281 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
283 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
284 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
287 Py_ssize_t s1_len, s2_len;
288 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
290 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
292 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
293 const int cmp = memcmp(s1, s2, n);
295 return PyLong_FromLong(cmp);
296 if (s1_len == s2_len)
297 return PyLong_FromLong(0);;
298 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
302 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
304 unsigned char *bufx = NULL, *bufy = NULL;
305 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
306 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
307 if (!PyArg_ParseTuple(args,
310 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
311 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
314 return PyErr_Format(PyExc_ValueError, "negative x offset");
316 return PyErr_Format(PyExc_ValueError, "negative x extent");
317 if (bufx_ofs > bufx_len)
318 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
319 if (bufx_n > bufx_len - bufx_ofs)
320 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
323 return PyErr_Format(PyExc_ValueError, "negative y offset");
325 return PyErr_Format(PyExc_ValueError, "negative y extent");
326 if (bufy_ofs > bufy_len)
327 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
328 if (bufy_n > bufy_len - bufy_ofs)
329 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
331 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
332 return PyErr_Format(PyExc_OverflowError, "result length too long");
334 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
336 return PyErr_NoMemory();
337 char *buf = PyBytes_AS_STRING(result);
338 memcpy(buf, bufx + bufx_ofs, bufx_n);
339 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
345 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
346 #if __WIN32__ || __CYGWIN__
348 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
349 static void unpythonize_argv(void) { }
351 #else // not __WIN32__
353 // For some reason this isn't declared in Python.h
354 extern void Py_GetArgcArgv(int *argc, char ***argv);
356 static void unpythonize_argv(void)
361 Py_GetArgcArgv(&argc, &argv);
363 for (i = 0; i < argc-1; i++)
365 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
367 // The argv block doesn't work the way we expected; it's unsafe
373 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
375 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
379 p = strrchr(argv[1], '/');
385 memmove(argv[0], p, len);
386 memset(arge - diff, 0, diff);
387 for (i = 0; i < argc; i++)
388 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
393 #endif // not __WIN32__ or __CYGWIN__
396 static int write_all(int fd, const void *buf, const size_t count)
399 while (written < count)
401 const ssize_t rc = write(fd, buf + written, count - written);
410 static int uadd(unsigned long long *dest,
411 const unsigned long long x,
412 const unsigned long long y)
414 const unsigned long long result = x + y;
415 if (result < x || result < y)
422 static PyObject *append_sparse_region(const int fd, unsigned long long n)
427 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
429 const off_t off = lseek(fd, new_off, SEEK_CUR);
430 if (off == (off_t) -1)
431 return PyErr_SetFromErrno(PyExc_IOError);
438 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
440 unsigned long long prev_pending,
441 const unsigned long long count)
443 // Add count additional sparse zeros to prev_pending and store the
444 // result in new_pending, or if the total won't fit in
445 // new_pending, write some of the zeros to fd sparsely, and store
446 // the remaining sum in new_pending.
447 if (!uadd(new_pending, prev_pending, count))
449 PyObject *err = append_sparse_region(fd, prev_pending);
452 *new_pending = count;
458 static byte* find_not_zero(const byte * const start, const byte * const end)
460 // Return a pointer to first non-zero byte between start and end,
461 // or end if there isn't one.
462 assert(start <= end);
463 const unsigned char *cur = start;
464 while (cur < end && *cur == 0)
470 static byte* find_trailing_zeros(const byte * const start,
471 const byte * const end)
473 // Return a pointer to the start of any trailing run of zeros, or
474 // end if there isn't one.
475 assert(start <= end);
478 const byte * cur = end;
479 while (cur > start && *--cur == 0) {}
483 return (byte *) (cur + 1);
487 static byte *find_non_sparse_end(const byte * const start,
488 const byte * const end,
489 const ptrdiff_t min_len)
491 // Return the first pointer to a min_len sparse block in [start,
492 // end) if there is one, otherwise a pointer to the start of any
493 // trailing run of zeros. If there are no trailing zeros, return
499 // Probe in min_len jumps, searching backward from the jump
500 // destination for a non-zero byte. If such a byte is found, move
501 // just past it and try again.
502 const byte *candidate = start;
503 // End of any run of zeros, starting at candidate, that we've already seen
504 const byte *end_of_known_zeros = candidate;
505 while (end - candidate >= min_len) // Handle all min_len candidate blocks
507 const byte * const probe_end = candidate + min_len;
508 const byte * const trailing_zeros =
509 find_trailing_zeros(end_of_known_zeros, probe_end);
510 if (trailing_zeros == probe_end)
511 end_of_known_zeros = candidate = probe_end;
512 else if (trailing_zeros == end_of_known_zeros)
514 assert(candidate >= start);
515 assert(candidate <= end);
516 assert(*candidate == 0);
517 return (byte *) candidate;
521 candidate = trailing_zeros;
522 end_of_known_zeros = probe_end;
526 if (candidate == end)
529 // No min_len sparse run found, search backward from end
530 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
533 if (trailing_zeros == end_of_known_zeros)
535 assert(candidate >= start);
536 assert(candidate < end);
537 assert(*candidate == 0);
538 assert(end - candidate < min_len);
539 return (byte *) candidate;
542 if (trailing_zeros == end)
544 assert(*(end - 1) != 0);
548 assert(end - trailing_zeros < min_len);
549 assert(trailing_zeros >= start);
550 assert(trailing_zeros < end);
551 assert(*trailing_zeros == 0);
552 return (byte *) trailing_zeros;
556 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
559 unsigned char *buf = NULL;
561 PyObject *py_min_sparse_len, *py_prev_sparse_len;
562 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
563 &fd, &buf, &sbuf_len,
564 &py_min_sparse_len, &py_prev_sparse_len))
566 ptrdiff_t min_sparse_len;
567 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
568 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
570 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
571 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
572 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
575 return PyErr_Format(PyExc_ValueError, "negative bufer length");
576 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
577 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
579 const byte * block = buf; // Start of pending block
580 const byte * const end = buf + buf_len;
581 unsigned long long zeros = prev_sparse_len;
584 assert(block <= end);
586 return PyLong_FromUnsignedLongLong(zeros);
590 // Look for the end of block, i.e. the next sparse run of
591 // at least min_sparse_len zeros, or the end of the
593 const byte * const probe = find_non_sparse_end(block + 1, end,
595 // Either at end of block, or end of non-sparse; write pending data
596 PyObject *err = append_sparse_region(fd, zeros);
599 int rc = write_all(fd, block, probe - block);
601 return PyErr_SetFromErrno(PyExc_IOError);
603 if (end - probe < min_sparse_len)
606 zeros = min_sparse_len;
607 block = probe + zeros;
611 // Should be in the first loop iteration, a sparse run of
612 // zeros, or nearly at the end of the block (within
614 const byte * const zeros_end = find_not_zero(block, end);
615 PyObject *err = record_sparse_zeros(&zeros, fd,
616 zeros, zeros_end - block);
619 assert(block <= zeros_end);
626 static PyObject *selftest(PyObject *self, PyObject *args)
628 if (!PyArg_ParseTuple(args, ""))
631 return Py_BuildValue("i", !bupsplit_selftest());
635 static PyObject *blobbits(PyObject *self, PyObject *args)
637 if (!PyArg_ParseTuple(args, ""))
639 return Py_BuildValue("i", BUP_BLOBBITS);
643 static PyObject *splitbuf(PyObject *self, PyObject *args)
645 // We stick to buffers in python 2 because they appear to be
646 // substantially smaller than memoryviews, and because
647 // zlib.compress() in python 2 can't accept a memoryview
648 // (cf. hashsplit.py).
649 int out = 0, bits = -1;
650 if (PY_MAJOR_VERSION > 2)
653 if (!PyArg_ParseTuple(args, "y*", &buf))
655 assert(buf.len <= INT_MAX);
656 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
657 PyBuffer_Release(&buf);
661 unsigned char *buf = NULL;
663 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
665 assert(len <= INT_MAX);
666 out = bupsplit_find_ofs(buf, (int) len, &bits);
668 if (out) assert(bits >= BUP_BLOBBITS);
669 return Py_BuildValue("ii", out, bits);
673 static PyObject *bitmatch(PyObject *self, PyObject *args)
675 unsigned char *buf1 = NULL, *buf2 = NULL;
676 Py_ssize_t len1 = 0, len2 = 0;
680 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
684 for (byte = 0; byte < len1 && byte < len2; byte++)
686 int b1 = buf1[byte], b2 = buf2[byte];
689 for (bit = 0; bit < 8; bit++)
690 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
696 assert(byte <= (INT_MAX >> 3));
697 return Py_BuildValue("i", byte*8 + bit);
701 static PyObject *firstword(PyObject *self, PyObject *args)
703 unsigned char *buf = NULL;
707 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
713 v = ntohl(*(uint32_t *)buf);
714 return PyLong_FromUnsignedLong(v);
718 #define BLOOM2_HEADERLEN 16
720 static void to_bloom_address_bitmask4(const unsigned char *buf,
721 const int nbits, uint64_t *v, unsigned char *bitmask)
727 memcpy(&high, buf, 4);
728 mask = (1<<nbits) - 1;
729 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
730 bit = (raw >> (37-nbits)) & 0x7;
731 *v = (raw >> (40-nbits)) & mask;
735 static void to_bloom_address_bitmask5(const unsigned char *buf,
736 const int nbits, uint32_t *v, unsigned char *bitmask)
742 memcpy(&high, buf, 4);
743 mask = (1<<nbits) - 1;
745 bit = (raw >> (29-nbits)) & 0x7;
746 *v = (raw >> (32-nbits)) & mask;
750 #define BLOOM_SET_BIT(name, address, otype) \
751 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
753 unsigned char bitmask;\
755 address(buf, nbits, &v, &bitmask);\
756 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
758 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
759 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
762 #define BLOOM_GET_BIT(name, address, otype) \
763 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
765 unsigned char bitmask;\
767 address(buf, nbits, &v, &bitmask);\
768 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
770 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
771 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
774 static PyObject *bloom_add(PyObject *self, PyObject *args)
776 Py_buffer bloom, sha;
777 int nbits = 0, k = 0;
778 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
779 &bloom, &sha, &nbits, &k))
782 PyObject *result = NULL;
784 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
785 goto clean_and_return;
790 goto clean_and_return;
791 unsigned char *cur = sha.buf;
793 for (end = cur + sha.len; cur < end; cur += 20/k)
794 bloom_set_bit5(bloom.buf, cur, nbits);
799 goto clean_and_return;
800 unsigned char *cur = sha.buf;
801 unsigned char *end = cur + sha.len;
802 for (; cur < end; cur += 20/k)
803 bloom_set_bit4(bloom.buf, cur, nbits);
806 goto clean_and_return;
808 result = Py_BuildValue("n", sha.len / 20);
811 PyBuffer_Release(&bloom);
812 PyBuffer_Release(&sha);
816 static PyObject *bloom_contains(PyObject *self, PyObject *args)
819 unsigned char *sha = NULL;
821 int nbits = 0, k = 0;
822 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
823 &bloom, &sha, &len, &nbits, &k))
826 PyObject *result = NULL;
829 goto clean_and_return;
834 goto clean_and_return;
837 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
838 if (!bloom_get_bit5(bloom.buf, sha, nbits))
840 result = Py_BuildValue("Oi", Py_None, steps);
841 goto clean_and_return;
847 goto clean_and_return;
850 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
851 if (!bloom_get_bit4(bloom.buf, sha, nbits))
853 result = Py_BuildValue("Oi", Py_None, steps);
854 goto clean_and_return;
858 goto clean_and_return;
860 result = Py_BuildValue("ii", 1, k);
863 PyBuffer_Release(&bloom);
868 static uint32_t _extract_bits(unsigned char *buf, int nbits)
872 mask = (1<<nbits) - 1;
873 v = ntohl(*(uint32_t *)buf);
874 v = (v >> (32-nbits)) & mask;
879 static PyObject *extract_bits(PyObject *self, PyObject *args)
881 unsigned char *buf = NULL;
885 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
891 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
896 unsigned char bytes[20];
899 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
901 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
914 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
917 Py_ssize_t low, mid, high;
921 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
923 idxs[*last_i] = NULL;
936 mid = (low + high) / 2;
937 c = _cmp_sha(idx->cur, idxs[mid]->cur);
949 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
954 static uint32_t _get_idx_i(struct idx *idx)
956 if (idx->cur_name == NULL)
957 return idx->name_base;
958 return ntohl(*idx->cur_name) + idx->name_base;
961 #define MIDX4_HEADERLEN 12
963 static PyObject *merge_into(PyObject *self, PyObject *args)
965 struct sha *sha_ptr, *sha_start = NULL;
966 uint32_t *table_ptr, *name_ptr, *name_start;
969 uint32_t count, prefix;
974 PyObject *py_total, *ilist = NULL;
975 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
976 &fmap, &bits, &py_total, &ilist))
979 PyObject *result = NULL;
980 struct idx **idxs = NULL;
981 Py_ssize_t num_i = 0;
982 int *idx_buf_init = NULL;
983 Py_buffer *idx_buf = NULL;
985 if (!bup_uint_from_py(&total, py_total, "total"))
986 goto clean_and_return;
988 num_i = PyList_Size(ilist);
990 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
991 goto clean_and_return;
992 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
993 goto clean_and_return;
994 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
995 goto clean_and_return;
997 for (i = 0; i < num_i; i++)
999 long len, sha_ofs, name_map_ofs;
1000 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
1001 goto clean_and_return;
1002 PyObject *itup = PyList_GetItem(ilist, i);
1003 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
1004 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
1005 &idxs[i]->name_base))
1007 idx_buf_init[i] = 1;
1008 idxs[i]->map = idx_buf[i].buf;
1009 idxs[i]->bytes = idx_buf[i].len;
1010 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
1011 idxs[i]->end = &idxs[i]->cur[len];
1013 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
1015 idxs[i]->cur_name = NULL;
1017 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
1018 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
1019 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
1021 Py_ssize_t last_i = num_i - 1;
1027 uint32_t new_prefix;
1028 if (count % 102424 == 0 && get_state(self)->istty2)
1029 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
1030 count*100.0/total, count, total);
1032 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
1033 while (prefix < new_prefix)
1034 table_ptr[prefix++] = htonl(count);
1035 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
1036 *name_ptr++ = htonl(_get_idx_i(idx));
1038 if (idx->cur_name != NULL)
1040 _fix_idx_order(idxs, &last_i);
1043 while (prefix < ((uint32_t) 1 << bits))
1044 table_ptr[prefix++] = htonl(count);
1045 assert(count == total);
1046 assert(prefix == ((uint32_t) 1 << bits));
1047 assert(sha_ptr == sha_start+count);
1048 assert(name_ptr == name_start+count);
1050 result = PyLong_FromUnsignedLong(count);
1055 for (i = 0; i < num_i; i++)
1056 if (idx_buf_init[i])
1057 PyBuffer_Release(&(idx_buf[i]));
1063 for (i = 0; i < num_i; i++)
1067 PyBuffer_Release(&fmap);
1071 #define FAN_ENTRIES 256
1073 static PyObject *write_idx(PyObject *self, PyObject *args)
1075 char *filename = NULL;
1076 PyObject *py_total, *idx = NULL;
1078 unsigned int total = 0;
1080 int i, j, ofs64_count;
1081 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1082 uint64_t *ofs64_ptr;
1083 struct sha *sha_ptr;
1086 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1087 &filename, &fmap, &idx, &py_total))
1090 PyObject *result = NULL;
1092 if (!bup_uint_from_py(&total, py_total, "total"))
1093 goto clean_and_return;
1095 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1097 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1099 goto clean_and_return;
1102 const char idx_header[] = "\377tOc\0\0\0\002";
1103 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1105 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1106 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1107 crc_ptr = (uint32_t *)&sha_ptr[total];
1108 ofs_ptr = (uint32_t *)&crc_ptr[total];
1109 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1113 for (i = 0; i < FAN_ENTRIES; ++i)
1116 part = PyList_GET_ITEM(idx, i);
1118 plen = PyList_GET_SIZE(part);
1119 if (plen > UINT32_MAX || UINT32_MAX - count < plen) {
1120 PyErr_Format(PyExc_OverflowError, "too many objects in index part");
1121 goto clean_and_return;
1123 count += (uint32_t) plen;
1124 *fan_ptr++ = htonl(count);
1125 for (j = 0; j < plen; ++j)
1127 unsigned char *sha = NULL;
1128 Py_ssize_t sha_len = 0;
1129 PyObject *crc_py, *ofs_py;
1131 unsigned PY_LONG_LONG ofs_ull;
1133 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1134 &sha, &sha_len, &crc_py, &ofs_py))
1135 goto clean_and_return;
1136 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1137 goto clean_and_return;
1138 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1139 goto clean_and_return;
1140 assert(crc <= UINT32_MAX);
1141 assert(ofs_ull <= UINT64_MAX);
1143 if (sha_len != sizeof(struct sha))
1144 goto clean_and_return;
1145 memcpy(sha_ptr++, sha, sizeof(struct sha));
1146 *crc_ptr++ = htonl(crc);
1147 if (ofs > 0x7fffffff)
1149 *ofs64_ptr++ = htonll(ofs);
1150 ofs = 0x80000000 | ofs64_count++;
1152 *ofs_ptr++ = htonl((uint32_t)ofs);
1156 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1159 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1160 goto clean_and_return;
1163 result = PyLong_FromUnsignedLong(count);
1166 PyBuffer_Release(&fmap);
1171 // I would have made this a lower-level function that just fills in a buffer
1172 // with random values, and then written those values from python. But that's
1173 // about 20% slower in my tests, and since we typically generate random
1174 // numbers for benchmarking other parts of bup, any slowness in generating
1175 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1176 // pseudorandom bytes much except for this anyway.
1177 static PyObject *write_random(PyObject *self, PyObject *args)
1179 uint32_t buf[1024/4];
1180 int fd = -1, seed = 0, verbose = 0;
1182 long long len = 0, kbytes = 0, written = 0;
1184 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1189 for (kbytes = 0; kbytes < len/1024; kbytes++)
1192 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1193 buf[i] = (uint32_t) random();
1194 ret = write(fd, buf, sizeof(buf));
1198 if (ret < (int)sizeof(buf))
1200 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1201 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1204 // handle non-multiples of 1024
1208 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1209 buf[i] = (uint32_t) random();
1210 ret = write(fd, buf, len % 1024);
1216 if (kbytes/1024 > 0)
1217 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1218 return Py_BuildValue("L", written);
1222 static PyObject *random_sha(PyObject *self, PyObject *args)
1224 static int seeded = 0;
1225 uint32_t shabuf[20/4];
1230 assert(sizeof(shabuf) == 20);
1231 srandom((unsigned int) time(NULL));
1235 if (!PyArg_ParseTuple(args, ""))
1238 memset(shabuf, 0, sizeof(shabuf));
1239 for (i=0; i < 20/4; i++)
1240 shabuf[i] = (uint32_t) random();
1241 return Py_BuildValue(rbuf_argf, shabuf, 20);
1245 static int _open_noatime(const char *filename, int attrs)
1247 int attrs_noatime, fd;
1250 attrs |= O_NOFOLLOW;
1253 attrs |= O_LARGEFILE;
1255 attrs_noatime = attrs;
1257 attrs_noatime |= O_NOATIME;
1259 fd = open(filename, attrs_noatime);
1260 if (fd < 0 && errno == EPERM)
1262 // older Linux kernels would return EPERM if you used O_NOATIME
1263 // and weren't the file's owner. This pointless restriction was
1264 // relaxed eventually, but we have to handle it anyway.
1265 // (VERY old kernels didn't recognized O_NOATIME, but they would
1266 // just harmlessly ignore it, so this branch won't trigger)
1267 fd = open(filename, attrs);
1273 static PyObject *open_noatime(PyObject *self, PyObject *args)
1275 char *filename = NULL;
1277 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1279 fd = _open_noatime(filename, 0);
1281 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1282 return Py_BuildValue("i", fd);
1286 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1289 long long llofs, lllen = 0;
1290 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1293 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1294 return PyErr_Format(PyExc_OverflowError,
1295 "fadvise offset overflows off_t");
1296 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1297 return PyErr_Format(PyExc_OverflowError,
1298 "fadvise length overflows off_t");
1299 #ifdef POSIX_FADV_DONTNEED
1300 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1302 return Py_BuildValue("");
1306 // Currently the Linux kernel and FUSE disagree over the type for
1307 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1308 // but FUSE chose long (matching the declaration in linux/fs.h). So
1309 // if you use int, and then traverse a FUSE filesystem, you may
1310 // corrupt the stack. But if you use long, then you may get invalid
1311 // results on big-endian systems.
1313 // For now, we just use long, and then disable Linux attrs entirely
1314 // (with a warning) in helpers.py on systems that are affected.
1316 #ifdef BUP_HAVE_FILE_ATTRS
1317 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1324 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1327 fd = _open_noatime(path, O_NONBLOCK);
1329 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1331 attr = 0; // Handle int/long mismatch (see above)
1332 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1336 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1339 assert(attr <= UINT_MAX); // Kernel type is actually int
1340 return PyLong_FromUnsignedLong(attr);
1342 #endif /* def BUP_HAVE_FILE_ATTRS */
1346 #ifdef BUP_HAVE_FILE_ATTRS
1347 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1350 unsigned long orig_attr;
1356 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1359 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1362 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1364 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1366 // Restrict attr to modifiable flags acdeijstuADST -- see
1367 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1368 // in pf.c flags_array[].
1369 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1370 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1371 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1372 | FS_TOPDIR_FL | FS_NOCOW_FL;
1374 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1375 orig_attr = 0; // Handle int/long mismatch (see above)
1376 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1380 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1382 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1383 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1385 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1389 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1393 return Py_BuildValue("O", Py_None);
1395 #endif /* def BUP_HAVE_FILE_ATTRS */
1398 #ifndef HAVE_UTIMENSAT
1400 #error "cannot find utimensat or utimes()"
1402 #ifndef HAVE_LUTIMES
1403 #error "cannot find utimensat or lutimes()"
1407 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1411 const long long lltmp = PyLong_AsLongLong(pylong); \
1412 if (lltmp == -1 && PyErr_Occurred()) \
1414 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1416 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1417 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1419 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1425 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1433 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1442 #ifdef HAVE_UTIMENSAT
1444 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1449 PyObject *access_py, *modification_py;
1450 struct timespec ts[2];
1452 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1455 &access_py, &(ts[0].tv_nsec),
1456 &modification_py, &(ts[1].tv_nsec),
1461 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1464 PyErr_SetString(PyExc_ValueError,
1465 "unable to convert access time seconds for utimensat");
1468 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1471 PyErr_SetString(PyExc_ValueError,
1472 "unable to convert modification time seconds for utimensat");
1475 rc = utimensat(fd, path, ts, flag);
1477 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1479 return Py_BuildValue("O", Py_None);
1482 #endif /* def HAVE_UTIMENSAT */
1485 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1487 static int bup_parse_xutimes_args(char **path,
1488 struct timeval tv[2],
1491 PyObject *access_py, *modification_py;
1492 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1494 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1496 &access_py, &access_us,
1497 &modification_py, &modification_us))
1501 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1504 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1507 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1509 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1512 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1515 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1518 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1520 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1526 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1530 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1533 struct timeval tv[2];
1534 if (!bup_parse_xutimes_args(&path, tv, args))
1536 int rc = utimes(path, tv);
1538 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1539 return Py_BuildValue("O", Py_None);
1541 #endif /* def HAVE_UTIMES */
1545 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1548 struct timeval tv[2];
1549 if (!bup_parse_xutimes_args(&path, tv, args))
1551 int rc = lutimes(path, tv);
1553 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1555 return Py_BuildValue("O", Py_None);
1557 #endif /* def HAVE_LUTIMES */
1560 #ifdef HAVE_STAT_ST_ATIM
1561 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1562 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1563 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1564 #elif defined HAVE_STAT_ST_ATIMENSEC
1565 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1566 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1567 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1569 # define BUP_STAT_ATIME_NS(st) 0
1570 # define BUP_STAT_MTIME_NS(st) 0
1571 # define BUP_STAT_CTIME_NS(st) 0
1575 #pragma clang diagnostic push
1576 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1578 static PyObject *stat_struct_to_py(const struct stat *st,
1579 const char *filename,
1582 // We can check the known (via POSIX) signed and unsigned types at
1583 // compile time, but not (easily) the unspecified types, so handle
1584 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1586 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1587 INTEGER_TO_PY(st->st_mode),
1588 (unsigned PY_LONG_LONG) st->st_ino,
1589 INTEGER_TO_PY(st->st_dev),
1590 INTEGER_TO_PY(st->st_nlink),
1591 INTEGER_TO_PY(st->st_uid),
1592 INTEGER_TO_PY(st->st_gid),
1593 INTEGER_TO_PY(st->st_rdev),
1594 (PY_LONG_LONG) st->st_size,
1595 INTEGER_TO_PY(st->st_atime),
1596 (long) BUP_STAT_ATIME_NS(st),
1597 INTEGER_TO_PY(st->st_mtime),
1598 (long) BUP_STAT_MTIME_NS(st),
1599 INTEGER_TO_PY(st->st_ctime),
1600 (long) BUP_STAT_CTIME_NS(st));
1603 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1605 static PyObject *bup_stat(PyObject *self, PyObject *args)
1610 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1614 rc = stat(filename, &st);
1616 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1617 return stat_struct_to_py(&st, filename, 0);
1621 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1626 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1630 rc = lstat(filename, &st);
1632 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1633 return stat_struct_to_py(&st, filename, 0);
1637 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1641 if (!PyArg_ParseTuple(args, "i", &fd))
1645 rc = fstat(fd, &st);
1647 return PyErr_SetFromErrno(PyExc_OSError);
1648 return stat_struct_to_py(&st, NULL, fd);
1652 #ifdef HAVE_TM_TM_GMTOFF
1653 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1657 if (!PyArg_ParseTuple(args, "L", &lltime))
1659 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1660 return PyErr_Format(PyExc_OverflowError, "time value too large");
1664 if(localtime_r(&ttime, &tm) == NULL)
1665 return PyErr_SetFromErrno(PyExc_OSError);
1667 // Match the Python struct_time values.
1668 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1669 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1670 tm.tm_hour, tm.tm_min, tm.tm_sec,
1671 tm.tm_wday, tm.tm_yday + 1,
1672 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1674 #endif /* def HAVE_TM_TM_GMTOFF */
1677 #ifdef BUP_MINCORE_BUF_TYPE
1678 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1680 Py_buffer src, dest;
1681 PyObject *py_src_n, *py_src_off, *py_dest_off;
1683 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1684 &src, &py_src_n, &py_src_off,
1685 &dest, &py_dest_off))
1688 PyObject *result = NULL;
1690 unsigned long long src_n, src_off, dest_off;
1691 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1692 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1693 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1694 goto clean_and_return;
1696 unsigned long long src_region_end;
1697 if (!uadd(&src_region_end, src_off, src_n)) {
1698 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1699 goto clean_and_return;
1701 assert(src.len >= 0);
1702 if (src_region_end > (unsigned long long) src.len) {
1703 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1704 goto clean_and_return;
1707 unsigned long long dest_size;
1708 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1709 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1710 goto clean_and_return;
1712 if (dest_off > dest_size) {
1713 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1714 goto clean_and_return;
1718 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1719 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1720 goto clean_and_return;
1722 int rc = mincore((void *)(src.buf + src_off), src_n,
1723 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1725 result = PyErr_SetFromErrno(PyExc_OSError);
1726 goto clean_and_return;
1728 result = Py_BuildValue("O", Py_None);
1731 PyBuffer_Release(&src);
1732 PyBuffer_Release(&dest);
1735 #endif /* def BUP_MINCORE_BUF_TYPE */
1738 static PyObject *tuple_from_cstrs(char **cstrs)
1740 // Assumes list is null terminated
1742 while(cstrs[n] != NULL)
1746 if (!INTEGRAL_ASSIGNMENT_FITS(&sn, n))
1747 return PyErr_Format(PyExc_OverflowError, "string array too large");
1749 PyObject *result = PyTuple_New(sn);
1751 for (i = 0; i < sn; i++)
1753 PyObject *gname = Py_BuildValue(cstr_argf, cstrs[i]);
1759 PyTuple_SET_ITEM(result, i, gname);
1765 static long getpw_buf_size;
1767 static PyObject *pwd_struct_to_py(const struct passwd *pwd, int rc)
1769 // We can check the known (via POSIX) signed and unsigned types at
1770 // compile time, but not (easily) the unspecified types, so handle
1771 // those via INTEGER_TO_PY().
1773 return Py_BuildValue(cstr_argf cstr_argf "OO"
1774 cstr_argf cstr_argf cstr_argf,
1777 INTEGER_TO_PY(pwd->pw_uid),
1778 INTEGER_TO_PY(pwd->pw_gid),
1783 return Py_BuildValue("O", Py_None);
1784 if (rc == EIO || rc == EMFILE || rc == ENFILE)
1785 return PyErr_SetFromErrno(PyExc_IOError);
1787 return PyErr_SetFromErrno(PyExc_OSError);
1791 static PyObject *bup_getpwuid(PyObject *self, PyObject *args)
1793 unsigned long long py_uid;
1794 if (!PyArg_ParseTuple(args, "K", &py_uid))
1797 if (!INTEGRAL_ASSIGNMENT_FITS(&uid, py_uid))
1798 return PyErr_Format(PyExc_OverflowError, "uid too large for uid_t");
1800 struct passwd pwd, *result_pwd;
1801 char *buf = PyMem_Malloc(getpw_buf_size);
1805 int rc = getpwuid_r(uid, &pwd, buf, getpw_buf_size, &result_pwd);
1806 PyObject *result = pwd_struct_to_py(result_pwd, rc);
1811 static PyObject *bup_getpwnam(PyObject *self, PyObject *args)
1814 if (!PyArg_ParseTuple(args, "S", &py_name))
1817 struct passwd pwd, *result_pwd;
1818 char *buf = PyMem_Malloc(getpw_buf_size);
1822 char *name = PyBytes_AS_STRING(py_name);
1823 int rc = getpwnam_r(name, &pwd, buf, getpw_buf_size, &result_pwd);
1824 PyObject *result = pwd_struct_to_py(result_pwd, rc);
1829 static long getgr_buf_size;
1831 static PyObject *grp_struct_to_py(const struct group *grp, int rc)
1833 // We can check the known (via POSIX) signed and unsigned types at
1834 // compile time, but not (easily) the unspecified types, so handle
1835 // those via INTEGER_TO_PY().
1837 PyObject *members = tuple_from_cstrs(grp->gr_mem);
1838 if (members == NULL)
1840 return Py_BuildValue(cstr_argf cstr_argf "OO",
1843 INTEGER_TO_PY(grp->gr_gid),
1847 return Py_BuildValue("O", Py_None);
1849 if (rc == EIO || rc == EMFILE || rc == ENFILE)
1850 return PyErr_SetFromErrno(PyExc_IOError);
1851 return PyErr_SetFromErrno(PyExc_OSError);
1854 static PyObject *bup_getgrgid(PyObject *self, PyObject *args)
1856 unsigned long long py_gid;
1857 if (!PyArg_ParseTuple(args, "K", &py_gid))
1860 if (!INTEGRAL_ASSIGNMENT_FITS(&gid, py_gid))
1861 return PyErr_Format(PyExc_OverflowError, "gid too large for gid_t");
1863 struct group grp, *result_grp;
1864 char *buf = PyMem_Malloc(getgr_buf_size);
1868 int rc = getgrgid_r(gid, &grp, buf, getgr_buf_size, &result_grp);
1869 PyObject *result = grp_struct_to_py(result_grp, rc);
1874 static PyObject *bup_getgrnam(PyObject *self, PyObject *args)
1877 if (!PyArg_ParseTuple(args, "S", &py_name))
1880 struct group grp, *result_grp;
1881 char *buf = PyMem_Malloc(getgr_buf_size);
1885 char *name = PyBytes_AS_STRING(py_name);
1886 int rc = getgrnam_r(name, &grp, buf, getgr_buf_size, &result_grp);
1887 PyObject *result = grp_struct_to_py(result_grp, rc);
1892 static PyObject *bup_gethostname(PyObject *mod, PyObject *ignore)
1894 #ifdef HOST_NAME_MAX
1895 char buf[HOST_NAME_MAX + 1] = {};
1897 /* 'SUSv2 guarantees that "Host names are limited to 255 bytes".' */
1901 if (gethostname(buf, sizeof(buf) - 1))
1902 return PyErr_SetFromErrno(PyExc_IOError);
1903 return PyBytes_FromString(buf);
1907 #ifdef BUP_HAVE_READLINE
1909 static char *cstr_from_bytes(PyObject *bytes)
1913 int rc = PyBytes_AsStringAndSize(bytes, &buf, &length);
1916 char *result = checked_malloc(length, sizeof(char));
1919 memcpy(result, buf, length);
1923 static char **cstrs_from_seq(PyObject *seq)
1925 char **result = NULL;
1926 seq = PySequence_Fast(seq, "Cannot convert sequence items to C strings");
1930 const Py_ssize_t len = PySequence_Fast_GET_SIZE(seq);
1931 if (len > PY_SSIZE_T_MAX - 1) {
1932 PyErr_Format(PyExc_OverflowError,
1933 "Sequence length %zd too large for conversion to C array",
1937 result = checked_malloc(len + 1, sizeof(char *));
1941 for (i = 0; i < len; i++)
1943 PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
1945 goto abandon_result;
1946 result[i] = cstr_from_bytes(item);
1949 goto abandon_result;
1967 static char* our_word_break_chars = NULL;
1970 bup_set_completer_word_break_characters(PyObject *self, PyObject *args)
1973 if (!PyArg_ParseTuple(args, cstr_argf, &bytes))
1975 char *prev = our_word_break_chars;
1976 char *next = strdup(bytes);
1978 return PyErr_NoMemory();
1979 our_word_break_chars = next;
1980 rl_completer_word_break_characters = next;
1987 bup_get_completer_word_break_characters(PyObject *self, PyObject *args)
1989 if (!PyArg_ParseTuple(args, ""))
1991 return PyBytes_FromString(rl_completer_word_break_characters);
1994 static PyObject *bup_get_line_buffer(PyObject *self, PyObject *args)
1996 if (!PyArg_ParseTuple(args, ""))
1998 return PyBytes_FromString(rl_line_buffer);
2002 bup_parse_and_bind(PyObject *self, PyObject *args)
2005 if (!PyArg_ParseTuple(args, cstr_argf ":parse_and_bind", &bytes))
2007 char *tmp = strdup(bytes); // Because it may modify the arg
2009 return PyErr_NoMemory();
2010 int rc = rl_parse_and_bind(tmp);
2013 return PyErr_Format(PyExc_OSError,
2014 "system rl_parse_and_bind failed (%d)", rc);
2019 static PyObject *py_on_attempted_completion;
2020 static char **prev_completions;
2022 static char **on_attempted_completion(const char *text, int start, int end)
2024 if (!py_on_attempted_completion)
2027 char **result = NULL;
2028 PyObject *py_result = PyObject_CallFunction(py_on_attempted_completion,
2033 if (py_result != Py_None) {
2034 result = cstrs_from_seq(py_result);
2035 free(prev_completions);
2036 prev_completions = result;
2038 Py_DECREF(py_result);
2043 bup_set_attempted_completion_function(PyObject *self, PyObject *args)
2045 PyObject *completer;
2046 if (!PyArg_ParseTuple(args, "O", &completer))
2049 PyObject *prev = py_on_attempted_completion;
2050 if (completer == Py_None)
2052 py_on_attempted_completion = NULL;
2053 rl_attempted_completion_function = NULL;
2055 py_on_attempted_completion = completer;
2056 rl_attempted_completion_function = on_attempted_completion;
2057 Py_INCREF(completer);
2064 static PyObject *py_on_completion_entry;
2066 static char *on_completion_entry(const char *text, int state)
2068 if (!py_on_completion_entry)
2071 PyObject *py_result = PyObject_CallFunction(py_on_completion_entry,
2072 cstr_argf "i", text, state);
2075 char *result = (py_result == Py_None) ? NULL : cstr_from_bytes(py_result);
2076 Py_DECREF(py_result);
2081 bup_set_completion_entry_function(PyObject *self, PyObject *args)
2083 PyObject *completer;
2084 if (!PyArg_ParseTuple(args, "O", &completer))
2087 PyObject *prev = py_on_completion_entry;
2088 if (completer == Py_None) {
2089 py_on_completion_entry = NULL;
2090 rl_completion_entry_function = NULL;
2092 py_on_completion_entry = completer;
2093 rl_completion_entry_function = on_completion_entry;
2094 Py_INCREF(completer);
2101 bup_readline(PyObject *self, PyObject *args)
2104 if (!PyArg_ParseTuple(args, cstr_argf, &prompt))
2106 char *line = readline(prompt);
2108 return PyErr_Format(PyExc_EOFError, "readline EOF");
2109 PyObject *result = PyBytes_FromString(line);
2114 #endif // defined BUP_HAVE_READLINE
2116 #if defined(HAVE_SYS_ACL_H) && \
2117 defined(HAVE_ACL_LIBACL_H) && \
2118 defined(HAVE_ACL_EXTENDED_FILE) && \
2119 defined(HAVE_ACL_GET_FILE) && \
2120 defined(HAVE_ACL_TO_ANY_TEXT) && \
2121 defined(HAVE_ACL_FROM_TEXT) && \
2122 defined(HAVE_ACL_SET_FILE)
2123 #define ACL_SUPPORT 1
2124 #include <sys/acl.h>
2125 #include <acl/libacl.h>
2129 // -1 for errors, with python exception set
2130 // -2 for ignored errors (not supported)
2131 static int bup_read_acl_to_text(const char *name, acl_type_t type,
2132 char **txt, char **num)
2136 acl = acl_get_file(name, type);
2138 if (errno == EOPNOTSUPP || errno == ENOSYS)
2140 PyErr_SetFromErrno(PyExc_IOError);
2145 *txt = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE);
2147 *num = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE | TEXT_NUMERIC_IDS);
2152 if (errno == ENOMEM)
2155 PyErr_SetFromErrno(PyExc_IOError);
2158 acl_free((acl_t)*txt);
2160 acl_free((acl_t)*num);
2165 static PyObject *bup_read_acl(PyObject *self, PyObject *args)
2169 PyObject *ret = NULL;
2170 char *acl_txt = NULL, *acl_num = NULL;
2172 if (!PyArg_ParseTuple(args, cstr_argf "i", &name, &isdir))
2175 if (!acl_extended_file(name))
2178 rv = bup_read_acl_to_text(name, ACL_TYPE_ACCESS, &acl_txt, &acl_num);
2183 char *def_txt = NULL, *def_num = NULL;
2185 rv = bup_read_acl_to_text(name, ACL_TYPE_DEFAULT, &def_txt, &def_num);
2189 ret = Py_BuildValue("[" cstr_argf cstr_argf cstr_argf cstr_argf "]",
2190 acl_txt, acl_num, def_txt, def_num);
2193 acl_free((acl_t)def_txt);
2195 acl_free((acl_t)def_num);
2197 ret = Py_BuildValue("[" cstr_argf cstr_argf "]",
2203 acl_free((acl_t)acl_txt);
2205 acl_free((acl_t)acl_num);
2211 static int bup_apply_acl_string(const char *name, const char *s)
2213 acl_t acl = acl_from_text(s);
2217 PyErr_SetFromErrno(PyExc_IOError);
2221 if (acl_set_file(name, ACL_TYPE_ACCESS, acl)) {
2222 PyErr_SetFromErrno(PyExc_IOError);
2231 static PyObject *bup_apply_acl(PyObject *self, PyObject *args)
2233 char *name, *acl, *def = NULL;
2235 if (!PyArg_ParseTuple(args, cstr_argf cstr_argf "|" cstr_argf, &name, &acl, &def))
2238 if (bup_apply_acl_string(name, acl))
2241 if (def && bup_apply_acl_string(name, def))
2248 static PyMethodDef helper_methods[] = {
2249 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
2250 "Write buf excepting zeros at the end. Return trailing zero count." },
2251 { "selftest", selftest, METH_VARARGS,
2252 "Check that the rolling checksum rolls correctly (for unit tests)." },
2253 { "blobbits", blobbits, METH_VARARGS,
2254 "Return the number of bits in the rolling checksum." },
2255 { "splitbuf", splitbuf, METH_VARARGS,
2256 "Split a list of strings based on a rolling checksum." },
2257 { "bitmatch", bitmatch, METH_VARARGS,
2258 "Count the number of matching prefix bits between two strings." },
2259 { "firstword", firstword, METH_VARARGS,
2260 "Return an int corresponding to the first 32 bits of buf." },
2261 { "bloom_contains", bloom_contains, METH_VARARGS,
2262 "Check if a bloom filter of 2^nbits bytes contains an object" },
2263 { "bloom_add", bloom_add, METH_VARARGS,
2264 "Add an object to a bloom filter of 2^nbits bytes" },
2265 { "extract_bits", extract_bits, METH_VARARGS,
2266 "Take the first 'nbits' bits from 'buf' and return them as an int." },
2267 { "merge_into", merge_into, METH_VARARGS,
2268 "Merges a bunch of idx and midx files into a single midx." },
2269 { "write_idx", write_idx, METH_VARARGS,
2270 "Write a PackIdxV2 file from an idx list of lists of tuples" },
2271 { "write_random", write_random, METH_VARARGS,
2272 "Write random bytes to the given file descriptor" },
2273 { "random_sha", random_sha, METH_VARARGS,
2274 "Return a random 20-byte string" },
2275 { "open_noatime", open_noatime, METH_VARARGS,
2276 "open() the given filename for read with O_NOATIME if possible" },
2277 { "fadvise_done", fadvise_done, METH_VARARGS,
2278 "Inform the kernel that we're finished with earlier parts of a file" },
2279 #ifdef BUP_HAVE_FILE_ATTRS
2280 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
2281 "Return the Linux attributes for the given file." },
2283 #ifdef BUP_HAVE_FILE_ATTRS
2284 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
2285 "Set the Linux attributes for the given file." },
2287 #ifdef HAVE_UTIMENSAT
2288 { "bup_utimensat", bup_utimensat, METH_VARARGS,
2289 "Change path timestamps with nanosecond precision (POSIX)." },
2292 { "bup_utimes", bup_utimes, METH_VARARGS,
2293 "Change path timestamps with microsecond precision." },
2296 { "bup_lutimes", bup_lutimes, METH_VARARGS,
2297 "Change path timestamps with microsecond precision;"
2298 " don't follow symlinks." },
2300 { "stat", bup_stat, METH_VARARGS,
2301 "Extended version of stat." },
2302 { "lstat", bup_lstat, METH_VARARGS,
2303 "Extended version of lstat." },
2304 { "fstat", bup_fstat, METH_VARARGS,
2305 "Extended version of fstat." },
2306 #ifdef HAVE_TM_TM_GMTOFF
2307 { "localtime", bup_localtime, METH_VARARGS,
2308 "Return struct_time elements plus the timezone offset and name." },
2310 { "bytescmp", bup_bytescmp, METH_VARARGS,
2311 "Return a negative value if x < y, zero if equal, positive otherwise."},
2312 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
2313 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
2314 #ifdef BUP_MINCORE_BUF_TYPE
2315 { "mincore", bup_mincore, METH_VARARGS,
2316 "For mincore(src, src_n, src_off, dest, dest_off)"
2317 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
2319 { "getpwuid", bup_getpwuid, METH_VARARGS,
2320 "Return the password database entry for the given numeric user id,"
2321 " as a tuple with all C strings as bytes(), or None if the user does"
2323 { "getpwnam", bup_getpwnam, METH_VARARGS,
2324 "Return the password database entry for the given user name,"
2325 " as a tuple with all C strings as bytes(), or None if the user does"
2327 { "getgrgid", bup_getgrgid, METH_VARARGS,
2328 "Return the group database entry for the given numeric group id,"
2329 " as a tuple with all C strings as bytes(), or None if the group does"
2331 { "getgrnam", bup_getgrnam, METH_VARARGS,
2332 "Return the group database entry for the given group name,"
2333 " as a tuple with all C strings as bytes(), or None if the group does"
2335 { "gethostname", bup_gethostname, METH_NOARGS,
2336 "Return the current hostname (as bytes)" },
2337 #ifdef BUP_HAVE_READLINE
2338 { "set_completion_entry_function", bup_set_completion_entry_function, METH_VARARGS,
2339 "Set rl_completion_entry_function. Called as f(text, state)." },
2340 { "set_attempted_completion_function", bup_set_attempted_completion_function, METH_VARARGS,
2341 "Set rl_attempted_completion_function. Called as f(text, start, end)." },
2342 { "parse_and_bind", bup_parse_and_bind, METH_VARARGS,
2343 "Call rl_parse_and_bind." },
2344 { "get_line_buffer", bup_get_line_buffer, METH_NOARGS,
2345 "Return rl_line_buffer." },
2346 { "get_completer_word_break_characters", bup_get_completer_word_break_characters, METH_NOARGS,
2347 "Return rl_completer_word_break_characters." },
2348 { "set_completer_word_break_characters", bup_set_completer_word_break_characters, METH_VARARGS,
2349 "Set rl_completer_word_break_characters." },
2350 { "readline", bup_readline, METH_VARARGS,
2351 "Call readline(prompt)." },
2352 #endif // defined BUP_HAVE_READLINE
2354 { "read_acl", bup_read_acl, METH_VARARGS,
2355 "read_acl(name, isdir)\n\n"
2356 "Read ACLs for the given file/dirname and return the correctly encoded"
2357 " list [txt, num, def_tx, def_num] (the def_* being empty bytestrings"
2358 " unless the second argument 'isdir' is True)." },
2359 { "apply_acl", bup_apply_acl, METH_VARARGS,
2360 "apply_acl(name, acl, def=None)\n\n"
2361 "Given a file/dirname (bytes) and the ACLs to restore, do that." },
2362 #endif /* HAVE_ACLS */
2363 { NULL, NULL, 0, NULL }, // sentinel
2366 static void test_integral_assignment_fits(void)
2368 assert(sizeof(signed short) == sizeof(unsigned short));
2369 assert(sizeof(signed short) < sizeof(signed long long));
2370 assert(sizeof(signed short) < sizeof(unsigned long long));
2371 assert(sizeof(unsigned short) < sizeof(signed long long));
2372 assert(sizeof(unsigned short) < sizeof(unsigned long long));
2373 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
2375 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
2376 unsigned short us, usmax = USHRT_MAX;
2377 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
2378 unsigned long long ullmax = ULLONG_MAX;
2380 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
2381 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
2382 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
2383 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
2384 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
2385 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
2387 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
2388 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
2389 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
2390 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
2391 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
2395 static int setup_module(PyObject *m)
2397 // FIXME: migrate these tests to configure, or at least don't
2398 // possibly crash the whole application. Check against the type
2399 // we're going to use when passing to python. Other stat types
2400 // are tested at runtime.
2401 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
2402 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
2403 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
2404 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
2405 // Just be sure (relevant when passing timestamps back to Python above).
2406 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
2407 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
2409 test_integral_assignment_fits();
2411 // Originally required by append_sparse_region()
2414 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
2416 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
2422 #pragma clang diagnostic push
2423 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
2426 value = INTEGER_TO_PY(INT_MAX);
2427 PyObject_SetAttrString(m, "INT_MAX", value);
2429 value = INTEGER_TO_PY(UINT_MAX);
2430 PyObject_SetAttrString(m, "UINT_MAX", value);
2433 #ifdef HAVE_UTIMENSAT
2436 value = INTEGER_TO_PY(AT_FDCWD);
2437 PyObject_SetAttrString(m, "AT_FDCWD", value);
2439 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
2440 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
2442 value = INTEGER_TO_PY(UTIME_NOW);
2443 PyObject_SetAttrString(m, "UTIME_NOW", value);
2447 #ifdef BUP_HAVE_MINCORE_INCORE
2450 value = INTEGER_TO_PY(MINCORE_INCORE);
2451 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
2455 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
2457 getpw_buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
2458 if (getpw_buf_size == -1)
2459 getpw_buf_size = 16384;
2461 getgr_buf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
2462 if (getgr_buf_size == -1)
2463 getgr_buf_size = 16384;
2465 e = getenv("BUP_FORCE_TTY");
2466 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
2472 #if PY_MAJOR_VERSION < 3
2474 PyMODINIT_FUNC init_helpers(void)
2476 PyObject *m = Py_InitModule("_helpers", helper_methods);
2480 if (!setup_module(m))
2487 # else // PY_MAJOR_VERSION >= 3
2489 static struct PyModuleDef helpers_def = {
2490 PyModuleDef_HEAD_INIT,
2496 NULL, // helpers_traverse,
2497 NULL, // helpers_clear,
2501 PyMODINIT_FUNC PyInit__helpers(void)
2503 PyObject *module = PyModule_Create(&helpers_def);
2506 if (!setup_module(module))
2514 #endif // PY_MAJOR_VERSION >= 3