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 #ifdef BUP_HAVE_READLINE
50 #if ! defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < BUP_RL_EXPECTED_XOPEN_SOURCE
51 # warning "_XOPEN_SOURCE version is too low for readline"
53 #include <readline/readline.h>
54 #include <readline/history.h>
59 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
60 #define BUP_HAVE_FILE_ATTRS 1
64 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
65 * pretend we don't have it.
67 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
72 // Of course, this assumes it's a bitfield value.
77 typedef unsigned char byte;
84 // cstr_argf: for byte vectors without null characters (e.g. paths)
85 // rbuf_argf: for read-only byte vectors
86 // wbuf_argf: for mutable byte vectors
88 #if PY_MAJOR_VERSION < 3
90 # define get_state(x) (&state)
91 # define cstr_argf "s"
92 # define rbuf_argf "s#"
93 # define wbuf_argf "s*"
95 # define get_state(x) ((state_t *) PyModule_GetState(x))
96 # define cstr_argf "y"
97 # define rbuf_argf "y#"
98 # define wbuf_argf "y*"
99 #endif // PY_MAJOR_VERSION >= 3
102 static void *checked_calloc(size_t n, size_t size)
104 void *result = calloc(n, size);
110 #ifndef BUP_HAVE_BUILTIN_MUL_OVERFLOW
112 #define checked_malloc checked_calloc
114 #else // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
116 static void *checked_malloc(size_t n, size_t size)
119 if (__builtin_mul_overflow(n, size, &total))
121 PyErr_Format(PyExc_OverflowError,
122 "request to allocate %lu items of size %lu is too large",
126 void *result = malloc(total);
128 return PyErr_NoMemory();
132 #endif // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
136 // This function should technically be macro'd out if it's going to be used
137 // more than ocasionally. As of this writing, it'll actually never be called
138 // in real world bup scenarios (because our packs are < MAX_INT bytes).
139 static uint64_t htonll(uint64_t value)
141 static const int endian_test = 42;
143 if (*(char *)&endian_test == endian_test) // LSB-MSB
144 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
145 return value; // already in network byte order MSB-LSB
150 // Disabling sign-compare here should be fine since we're explicitly
151 // checking for a sign mismatch, i.e. if the signs don't match, then
152 // it doesn't matter what the value comparison says.
153 // FIXME: ... so should we reverse the order?
154 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
156 _Pragma("GCC diagnostic push"); \
157 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
159 int result = *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
160 _Pragma("GCC diagnostic pop"); \
165 // At the moment any code that calls INTEGER_TO_PY() will have to
166 // disable -Wtautological-compare for clang. See below.
168 #define INTEGER_TO_PY(x) \
169 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
173 #if PY_MAJOR_VERSION < 3
174 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
177 const long tmp = PyInt_AsLong(py);
178 if (tmp == -1 && PyErr_Occurred())
180 if (PyErr_ExceptionMatches(PyExc_OverflowError))
181 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
187 PyErr_Format(PyExc_OverflowError,
188 "negative %s cannot be converted to unsigned long", name);
197 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
199 #if PY_MAJOR_VERSION < 3
201 return bup_ulong_from_pyint(x, py, name);
204 if (!PyLong_Check(py))
206 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
210 const unsigned long tmp = PyLong_AsUnsignedLong(py);
211 if (PyErr_Occurred())
213 if (PyErr_ExceptionMatches(PyExc_OverflowError))
214 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
223 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
226 if (!bup_ulong_from_py(&tmp, py, name))
231 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
238 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
241 #if PY_MAJOR_VERSION < 3
245 if (bup_ulong_from_pyint(&tmp, py, name))
254 if (!PyLong_Check(py))
256 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
260 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
261 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
263 if (PyErr_ExceptionMatches(PyExc_OverflowError))
264 PyErr_Format(PyExc_OverflowError,
265 "%s too big for unsigned long long", name);
273 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
275 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
276 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
279 Py_ssize_t s1_len, s2_len;
280 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
282 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
284 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
285 const int cmp = memcmp(s1, s2, n);
287 return PyLong_FromLong(cmp);
288 if (s1_len == s2_len)
289 return PyLong_FromLong(0);;
290 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
294 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
296 unsigned char *bufx = NULL, *bufy = NULL;
297 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
298 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
299 if (!PyArg_ParseTuple(args,
302 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
303 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
306 return PyErr_Format(PyExc_ValueError, "negative x offset");
308 return PyErr_Format(PyExc_ValueError, "negative x extent");
309 if (bufx_ofs > bufx_len)
310 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
311 if (bufx_n > bufx_len - bufx_ofs)
312 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
315 return PyErr_Format(PyExc_ValueError, "negative y offset");
317 return PyErr_Format(PyExc_ValueError, "negative y extent");
318 if (bufy_ofs > bufy_len)
319 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
320 if (bufy_n > bufy_len - bufy_ofs)
321 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
323 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
324 return PyErr_Format(PyExc_OverflowError, "result length too long");
326 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
328 return PyErr_NoMemory();
329 char *buf = PyBytes_AS_STRING(result);
330 memcpy(buf, bufx + bufx_ofs, bufx_n);
331 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
337 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
338 #if __WIN32__ || __CYGWIN__
340 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
341 static void unpythonize_argv(void) { }
343 #else // not __WIN32__
345 // For some reason this isn't declared in Python.h
346 extern void Py_GetArgcArgv(int *argc, char ***argv);
348 static void unpythonize_argv(void)
353 Py_GetArgcArgv(&argc, &argv);
355 for (i = 0; i < argc-1; i++)
357 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
359 // The argv block doesn't work the way we expected; it's unsafe
365 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
367 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
371 p = strrchr(argv[1], '/');
377 memmove(argv[0], p, len);
378 memset(arge - diff, 0, diff);
379 for (i = 0; i < argc; i++)
380 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
385 #endif // not __WIN32__ or __CYGWIN__
388 static int write_all(int fd, const void *buf, const size_t count)
391 while (written < count)
393 const ssize_t rc = write(fd, buf + written, count - written);
402 static int uadd(unsigned long long *dest,
403 const unsigned long long x,
404 const unsigned long long y)
406 const unsigned long long result = x + y;
407 if (result < x || result < y)
414 static PyObject *append_sparse_region(const int fd, unsigned long long n)
419 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
421 const off_t off = lseek(fd, new_off, SEEK_CUR);
422 if (off == (off_t) -1)
423 return PyErr_SetFromErrno(PyExc_IOError);
430 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
432 unsigned long long prev_pending,
433 const unsigned long long count)
435 // Add count additional sparse zeros to prev_pending and store the
436 // result in new_pending, or if the total won't fit in
437 // new_pending, write some of the zeros to fd sparsely, and store
438 // the remaining sum in new_pending.
439 if (!uadd(new_pending, prev_pending, count))
441 PyObject *err = append_sparse_region(fd, prev_pending);
444 *new_pending = count;
450 static byte* find_not_zero(const byte * const start, const byte * const end)
452 // Return a pointer to first non-zero byte between start and end,
453 // or end if there isn't one.
454 assert(start <= end);
455 const unsigned char *cur = start;
456 while (cur < end && *cur == 0)
462 static byte* find_trailing_zeros(const byte * const start,
463 const byte * const end)
465 // Return a pointer to the start of any trailing run of zeros, or
466 // end if there isn't one.
467 assert(start <= end);
470 const byte * cur = end;
471 while (cur > start && *--cur == 0) {}
475 return (byte *) (cur + 1);
479 static byte *find_non_sparse_end(const byte * const start,
480 const byte * const end,
481 const ptrdiff_t min_len)
483 // Return the first pointer to a min_len sparse block in [start,
484 // end) if there is one, otherwise a pointer to the start of any
485 // trailing run of zeros. If there are no trailing zeros, return
491 // Probe in min_len jumps, searching backward from the jump
492 // destination for a non-zero byte. If such a byte is found, move
493 // just past it and try again.
494 const byte *candidate = start;
495 // End of any run of zeros, starting at candidate, that we've already seen
496 const byte *end_of_known_zeros = candidate;
497 while (end - candidate >= min_len) // Handle all min_len candidate blocks
499 const byte * const probe_end = candidate + min_len;
500 const byte * const trailing_zeros =
501 find_trailing_zeros(end_of_known_zeros, probe_end);
502 if (trailing_zeros == probe_end)
503 end_of_known_zeros = candidate = probe_end;
504 else if (trailing_zeros == end_of_known_zeros)
506 assert(candidate >= start);
507 assert(candidate <= end);
508 assert(*candidate == 0);
509 return (byte *) candidate;
513 candidate = trailing_zeros;
514 end_of_known_zeros = probe_end;
518 if (candidate == end)
521 // No min_len sparse run found, search backward from end
522 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
525 if (trailing_zeros == end_of_known_zeros)
527 assert(candidate >= start);
528 assert(candidate < end);
529 assert(*candidate == 0);
530 assert(end - candidate < min_len);
531 return (byte *) candidate;
534 if (trailing_zeros == end)
536 assert(*(end - 1) != 0);
540 assert(end - trailing_zeros < min_len);
541 assert(trailing_zeros >= start);
542 assert(trailing_zeros < end);
543 assert(*trailing_zeros == 0);
544 return (byte *) trailing_zeros;
548 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
551 unsigned char *buf = NULL;
553 PyObject *py_min_sparse_len, *py_prev_sparse_len;
554 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
555 &fd, &buf, &sbuf_len,
556 &py_min_sparse_len, &py_prev_sparse_len))
558 ptrdiff_t min_sparse_len;
559 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
560 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
562 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
563 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
564 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
567 return PyErr_Format(PyExc_ValueError, "negative bufer length");
568 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
569 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
571 const byte * block = buf; // Start of pending block
572 const byte * const end = buf + buf_len;
573 unsigned long long zeros = prev_sparse_len;
576 assert(block <= end);
578 return PyLong_FromUnsignedLongLong(zeros);
582 // Look for the end of block, i.e. the next sparse run of
583 // at least min_sparse_len zeros, or the end of the
585 const byte * const probe = find_non_sparse_end(block + 1, end,
587 // Either at end of block, or end of non-sparse; write pending data
588 PyObject *err = append_sparse_region(fd, zeros);
591 int rc = write_all(fd, block, probe - block);
593 return PyErr_SetFromErrno(PyExc_IOError);
595 if (end - probe < min_sparse_len)
598 zeros = min_sparse_len;
599 block = probe + zeros;
603 // Should be in the first loop iteration, a sparse run of
604 // zeros, or nearly at the end of the block (within
606 const byte * const zeros_end = find_not_zero(block, end);
607 PyObject *err = record_sparse_zeros(&zeros, fd,
608 zeros, zeros_end - block);
611 assert(block <= zeros_end);
618 static PyObject *selftest(PyObject *self, PyObject *args)
620 if (!PyArg_ParseTuple(args, ""))
623 return Py_BuildValue("i", !bupsplit_selftest());
627 static PyObject *blobbits(PyObject *self, PyObject *args)
629 if (!PyArg_ParseTuple(args, ""))
631 return Py_BuildValue("i", BUP_BLOBBITS);
635 static PyObject *splitbuf(PyObject *self, PyObject *args)
637 // We stick to buffers in python 2 because they appear to be
638 // substantially smaller than memoryviews, and because
639 // zlib.compress() in python 2 can't accept a memoryview
640 // (cf. hashsplit.py).
641 int out = 0, bits = -1;
642 if (PY_MAJOR_VERSION > 2)
645 if (!PyArg_ParseTuple(args, "y*", &buf))
647 assert(buf.len <= INT_MAX);
648 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
649 PyBuffer_Release(&buf);
653 unsigned char *buf = NULL;
655 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
657 assert(len <= INT_MAX);
658 out = bupsplit_find_ofs(buf, len, &bits);
660 if (out) assert(bits >= BUP_BLOBBITS);
661 return Py_BuildValue("ii", out, bits);
665 static PyObject *bitmatch(PyObject *self, PyObject *args)
667 unsigned char *buf1 = NULL, *buf2 = NULL;
668 Py_ssize_t len1 = 0, len2 = 0;
672 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
676 for (byte = 0; byte < len1 && byte < len2; byte++)
678 int b1 = buf1[byte], b2 = buf2[byte];
681 for (bit = 0; bit < 8; bit++)
682 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
688 assert(byte <= (INT_MAX >> 3));
689 return Py_BuildValue("i", byte*8 + bit);
693 static PyObject *firstword(PyObject *self, PyObject *args)
695 unsigned char *buf = NULL;
699 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
705 v = ntohl(*(uint32_t *)buf);
706 return PyLong_FromUnsignedLong(v);
710 #define BLOOM2_HEADERLEN 16
712 static void to_bloom_address_bitmask4(const unsigned char *buf,
713 const int nbits, uint64_t *v, unsigned char *bitmask)
719 memcpy(&high, buf, 4);
720 mask = (1<<nbits) - 1;
721 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
722 bit = (raw >> (37-nbits)) & 0x7;
723 *v = (raw >> (40-nbits)) & mask;
727 static void to_bloom_address_bitmask5(const unsigned char *buf,
728 const int nbits, uint32_t *v, unsigned char *bitmask)
734 memcpy(&high, buf, 4);
735 mask = (1<<nbits) - 1;
737 bit = (raw >> (29-nbits)) & 0x7;
738 *v = (raw >> (32-nbits)) & mask;
742 #define BLOOM_SET_BIT(name, address, otype) \
743 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
745 unsigned char bitmask;\
747 address(buf, nbits, &v, &bitmask);\
748 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
750 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
751 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
754 #define BLOOM_GET_BIT(name, address, otype) \
755 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
757 unsigned char bitmask;\
759 address(buf, nbits, &v, &bitmask);\
760 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
762 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
763 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
766 static PyObject *bloom_add(PyObject *self, PyObject *args)
768 Py_buffer bloom, sha;
769 int nbits = 0, k = 0;
770 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
771 &bloom, &sha, &nbits, &k))
774 PyObject *result = NULL;
776 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
777 goto clean_and_return;
782 goto clean_and_return;
783 unsigned char *cur = sha.buf;
785 for (end = cur + sha.len; cur < end; cur += 20/k)
786 bloom_set_bit5(bloom.buf, cur, nbits);
791 goto clean_and_return;
792 unsigned char *cur = sha.buf;
793 unsigned char *end = cur + sha.len;
794 for (; cur < end; cur += 20/k)
795 bloom_set_bit4(bloom.buf, cur, nbits);
798 goto clean_and_return;
800 result = Py_BuildValue("n", sha.len / 20);
803 PyBuffer_Release(&bloom);
804 PyBuffer_Release(&sha);
808 static PyObject *bloom_contains(PyObject *self, PyObject *args)
811 unsigned char *sha = NULL;
813 int nbits = 0, k = 0;
814 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
815 &bloom, &sha, &len, &nbits, &k))
818 PyObject *result = NULL;
821 goto clean_and_return;
826 goto clean_and_return;
829 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
830 if (!bloom_get_bit5(bloom.buf, sha, nbits))
832 result = Py_BuildValue("Oi", Py_None, steps);
833 goto clean_and_return;
839 goto clean_and_return;
842 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
843 if (!bloom_get_bit4(bloom.buf, sha, nbits))
845 result = Py_BuildValue("Oi", Py_None, steps);
846 goto clean_and_return;
850 goto clean_and_return;
852 result = Py_BuildValue("ii", 1, k);
855 PyBuffer_Release(&bloom);
860 static uint32_t _extract_bits(unsigned char *buf, int nbits)
864 mask = (1<<nbits) - 1;
865 v = ntohl(*(uint32_t *)buf);
866 v = (v >> (32-nbits)) & mask;
871 static PyObject *extract_bits(PyObject *self, PyObject *args)
873 unsigned char *buf = NULL;
877 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
883 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
888 unsigned char bytes[20];
891 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
893 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
906 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
909 int low, mid, high, c = 0;
912 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
914 idxs[*last_i] = NULL;
927 mid = (low + high) / 2;
928 c = _cmp_sha(idx->cur, idxs[mid]->cur);
940 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
945 static uint32_t _get_idx_i(struct idx *idx)
947 if (idx->cur_name == NULL)
948 return idx->name_base;
949 return ntohl(*idx->cur_name) + idx->name_base;
952 #define MIDX4_HEADERLEN 12
954 static PyObject *merge_into(PyObject *self, PyObject *args)
956 struct sha *sha_ptr, *sha_start = NULL;
957 uint32_t *table_ptr, *name_ptr, *name_start;
960 uint32_t count, prefix;
965 PyObject *py_total, *ilist = NULL;
966 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
967 &fmap, &bits, &py_total, &ilist))
970 PyObject *result = NULL;
971 struct idx **idxs = NULL;
972 Py_ssize_t num_i = 0;
973 int *idx_buf_init = NULL;
974 Py_buffer *idx_buf = NULL;
976 if (!bup_uint_from_py(&total, py_total, "total"))
977 goto clean_and_return;
979 num_i = PyList_Size(ilist);
981 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
982 goto clean_and_return;
983 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
984 goto clean_and_return;
985 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
986 goto clean_and_return;
988 for (i = 0; i < num_i; i++)
990 long len, sha_ofs, name_map_ofs;
991 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
992 goto clean_and_return;
993 PyObject *itup = PyList_GetItem(ilist, i);
994 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
995 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
996 &idxs[i]->name_base))
999 idxs[i]->map = idx_buf[i].buf;
1000 idxs[i]->bytes = idx_buf[i].len;
1001 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
1002 idxs[i]->end = &idxs[i]->cur[len];
1004 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
1006 idxs[i]->cur_name = NULL;
1008 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
1009 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
1010 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
1012 Py_ssize_t last_i = num_i - 1;
1018 uint32_t new_prefix;
1019 if (count % 102424 == 0 && get_state(self)->istty2)
1020 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
1021 count*100.0/total, count, total);
1023 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
1024 while (prefix < new_prefix)
1025 table_ptr[prefix++] = htonl(count);
1026 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
1027 *name_ptr++ = htonl(_get_idx_i(idx));
1029 if (idx->cur_name != NULL)
1031 _fix_idx_order(idxs, &last_i);
1034 while (prefix < ((uint32_t) 1 << bits))
1035 table_ptr[prefix++] = htonl(count);
1036 assert(count == total);
1037 assert(prefix == ((uint32_t) 1 << bits));
1038 assert(sha_ptr == sha_start+count);
1039 assert(name_ptr == name_start+count);
1041 result = PyLong_FromUnsignedLong(count);
1046 for (i = 0; i < num_i; i++)
1047 if (idx_buf_init[i])
1048 PyBuffer_Release(&(idx_buf[i]));
1054 for (i = 0; i < num_i; i++)
1058 PyBuffer_Release(&fmap);
1062 #define FAN_ENTRIES 256
1064 static PyObject *write_idx(PyObject *self, PyObject *args)
1066 char *filename = NULL;
1067 PyObject *py_total, *idx = NULL;
1069 unsigned int total = 0;
1071 int i, j, ofs64_count;
1072 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1073 uint64_t *ofs64_ptr;
1074 struct sha *sha_ptr;
1077 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1078 &filename, &fmap, &idx, &py_total))
1081 PyObject *result = NULL;
1083 if (!bup_uint_from_py(&total, py_total, "total"))
1084 goto clean_and_return;
1086 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1088 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1090 goto clean_and_return;
1093 const char idx_header[] = "\377tOc\0\0\0\002";
1094 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1096 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1097 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1098 crc_ptr = (uint32_t *)&sha_ptr[total];
1099 ofs_ptr = (uint32_t *)&crc_ptr[total];
1100 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1104 for (i = 0; i < FAN_ENTRIES; ++i)
1107 part = PyList_GET_ITEM(idx, i);
1109 plen = PyList_GET_SIZE(part);
1111 *fan_ptr++ = htonl(count);
1112 for (j = 0; j < plen; ++j)
1114 unsigned char *sha = NULL;
1115 Py_ssize_t sha_len = 0;
1116 PyObject *crc_py, *ofs_py;
1118 unsigned PY_LONG_LONG ofs_ull;
1120 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1121 &sha, &sha_len, &crc_py, &ofs_py))
1122 goto clean_and_return;
1123 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1124 goto clean_and_return;
1125 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1126 goto clean_and_return;
1127 assert(crc <= UINT32_MAX);
1128 assert(ofs_ull <= UINT64_MAX);
1130 if (sha_len != sizeof(struct sha))
1131 goto clean_and_return;
1132 memcpy(sha_ptr++, sha, sizeof(struct sha));
1133 *crc_ptr++ = htonl(crc);
1134 if (ofs > 0x7fffffff)
1136 *ofs64_ptr++ = htonll(ofs);
1137 ofs = 0x80000000 | ofs64_count++;
1139 *ofs_ptr++ = htonl((uint32_t)ofs);
1143 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1146 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1147 goto clean_and_return;
1150 result = PyLong_FromUnsignedLong(count);
1153 PyBuffer_Release(&fmap);
1158 // I would have made this a lower-level function that just fills in a buffer
1159 // with random values, and then written those values from python. But that's
1160 // about 20% slower in my tests, and since we typically generate random
1161 // numbers for benchmarking other parts of bup, any slowness in generating
1162 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1163 // pseudorandom bytes much except for this anyway.
1164 static PyObject *write_random(PyObject *self, PyObject *args)
1166 uint32_t buf[1024/4];
1167 int fd = -1, seed = 0, verbose = 0;
1169 long long len = 0, kbytes = 0, written = 0;
1171 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1176 for (kbytes = 0; kbytes < len/1024; kbytes++)
1179 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1181 ret = write(fd, buf, sizeof(buf));
1185 if (ret < (int)sizeof(buf))
1187 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1188 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1191 // handle non-multiples of 1024
1195 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1197 ret = write(fd, buf, len % 1024);
1203 if (kbytes/1024 > 0)
1204 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1205 return Py_BuildValue("L", written);
1209 static PyObject *random_sha(PyObject *self, PyObject *args)
1211 static int seeded = 0;
1212 uint32_t shabuf[20/4];
1217 assert(sizeof(shabuf) == 20);
1218 srandom(time(NULL));
1222 if (!PyArg_ParseTuple(args, ""))
1225 memset(shabuf, 0, sizeof(shabuf));
1226 for (i=0; i < 20/4; i++)
1227 shabuf[i] = random();
1228 return Py_BuildValue(rbuf_argf, shabuf, 20);
1232 static int _open_noatime(const char *filename, int attrs)
1234 int attrs_noatime, fd;
1237 attrs |= O_NOFOLLOW;
1240 attrs |= O_LARGEFILE;
1242 attrs_noatime = attrs;
1244 attrs_noatime |= O_NOATIME;
1246 fd = open(filename, attrs_noatime);
1247 if (fd < 0 && errno == EPERM)
1249 // older Linux kernels would return EPERM if you used O_NOATIME
1250 // and weren't the file's owner. This pointless restriction was
1251 // relaxed eventually, but we have to handle it anyway.
1252 // (VERY old kernels didn't recognized O_NOATIME, but they would
1253 // just harmlessly ignore it, so this branch won't trigger)
1254 fd = open(filename, attrs);
1260 static PyObject *open_noatime(PyObject *self, PyObject *args)
1262 char *filename = NULL;
1264 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1266 fd = _open_noatime(filename, 0);
1268 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1269 return Py_BuildValue("i", fd);
1273 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1276 long long llofs, lllen = 0;
1277 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1280 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1281 return PyErr_Format(PyExc_OverflowError,
1282 "fadvise offset overflows off_t");
1283 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1284 return PyErr_Format(PyExc_OverflowError,
1285 "fadvise length overflows off_t");
1286 #ifdef POSIX_FADV_DONTNEED
1287 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1289 return Py_BuildValue("");
1293 // Currently the Linux kernel and FUSE disagree over the type for
1294 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1295 // but FUSE chose long (matching the declaration in linux/fs.h). So
1296 // if you use int, and then traverse a FUSE filesystem, you may
1297 // corrupt the stack. But if you use long, then you may get invalid
1298 // results on big-endian systems.
1300 // For now, we just use long, and then disable Linux attrs entirely
1301 // (with a warning) in helpers.py on systems that are affected.
1303 #ifdef BUP_HAVE_FILE_ATTRS
1304 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1311 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1314 fd = _open_noatime(path, O_NONBLOCK);
1316 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1318 attr = 0; // Handle int/long mismatch (see above)
1319 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1323 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1326 assert(attr <= UINT_MAX); // Kernel type is actually int
1327 return PyLong_FromUnsignedLong(attr);
1329 #endif /* def BUP_HAVE_FILE_ATTRS */
1333 #ifdef BUP_HAVE_FILE_ATTRS
1334 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1337 unsigned long orig_attr;
1343 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1346 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1349 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1351 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1353 // Restrict attr to modifiable flags acdeijstuADST -- see
1354 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1355 // in pf.c flags_array[].
1356 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1357 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1358 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1359 | FS_TOPDIR_FL | FS_NOCOW_FL;
1361 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1362 orig_attr = 0; // Handle int/long mismatch (see above)
1363 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1367 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1369 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1370 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1372 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1376 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1380 return Py_BuildValue("O", Py_None);
1382 #endif /* def BUP_HAVE_FILE_ATTRS */
1385 #ifndef HAVE_UTIMENSAT
1387 #error "cannot find utimensat or utimes()"
1389 #ifndef HAVE_LUTIMES
1390 #error "cannot find utimensat or lutimes()"
1394 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1398 const long long lltmp = PyLong_AsLongLong(pylong); \
1399 if (lltmp == -1 && PyErr_Occurred()) \
1401 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1403 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1404 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1406 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1412 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1420 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1429 #ifdef HAVE_UTIMENSAT
1431 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1436 PyObject *access_py, *modification_py;
1437 struct timespec ts[2];
1439 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1442 &access_py, &(ts[0].tv_nsec),
1443 &modification_py, &(ts[1].tv_nsec),
1448 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1451 PyErr_SetString(PyExc_ValueError,
1452 "unable to convert access time seconds for utimensat");
1455 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1458 PyErr_SetString(PyExc_ValueError,
1459 "unable to convert modification time seconds for utimensat");
1462 rc = utimensat(fd, path, ts, flag);
1464 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1466 return Py_BuildValue("O", Py_None);
1469 #endif /* def HAVE_UTIMENSAT */
1472 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1474 static int bup_parse_xutimes_args(char **path,
1475 struct timeval tv[2],
1478 PyObject *access_py, *modification_py;
1479 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1481 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1483 &access_py, &access_us,
1484 &modification_py, &modification_us))
1488 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1491 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1494 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1496 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1499 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1502 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1505 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1507 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1513 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1517 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1520 struct timeval tv[2];
1521 if (!bup_parse_xutimes_args(&path, tv, args))
1523 int rc = utimes(path, tv);
1525 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1526 return Py_BuildValue("O", Py_None);
1528 #endif /* def HAVE_UTIMES */
1532 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1535 struct timeval tv[2];
1536 if (!bup_parse_xutimes_args(&path, tv, args))
1538 int rc = lutimes(path, tv);
1540 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1542 return Py_BuildValue("O", Py_None);
1544 #endif /* def HAVE_LUTIMES */
1547 #ifdef HAVE_STAT_ST_ATIM
1548 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1549 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1550 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1551 #elif defined HAVE_STAT_ST_ATIMENSEC
1552 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1553 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1554 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1556 # define BUP_STAT_ATIME_NS(st) 0
1557 # define BUP_STAT_MTIME_NS(st) 0
1558 # define BUP_STAT_CTIME_NS(st) 0
1562 #pragma clang diagnostic push
1563 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1565 static PyObject *stat_struct_to_py(const struct stat *st,
1566 const char *filename,
1569 // We can check the known (via POSIX) signed and unsigned types at
1570 // compile time, but not (easily) the unspecified types, so handle
1571 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1573 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1574 INTEGER_TO_PY(st->st_mode),
1575 (unsigned PY_LONG_LONG) st->st_ino,
1576 INTEGER_TO_PY(st->st_dev),
1577 INTEGER_TO_PY(st->st_nlink),
1578 INTEGER_TO_PY(st->st_uid),
1579 INTEGER_TO_PY(st->st_gid),
1580 INTEGER_TO_PY(st->st_rdev),
1581 (PY_LONG_LONG) st->st_size,
1582 INTEGER_TO_PY(st->st_atime),
1583 (long) BUP_STAT_ATIME_NS(st),
1584 INTEGER_TO_PY(st->st_mtime),
1585 (long) BUP_STAT_MTIME_NS(st),
1586 INTEGER_TO_PY(st->st_ctime),
1587 (long) BUP_STAT_CTIME_NS(st));
1590 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1592 static PyObject *bup_stat(PyObject *self, PyObject *args)
1597 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1601 rc = stat(filename, &st);
1603 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1604 return stat_struct_to_py(&st, filename, 0);
1608 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1613 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1617 rc = lstat(filename, &st);
1619 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1620 return stat_struct_to_py(&st, filename, 0);
1624 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1628 if (!PyArg_ParseTuple(args, "i", &fd))
1632 rc = fstat(fd, &st);
1634 return PyErr_SetFromErrno(PyExc_OSError);
1635 return stat_struct_to_py(&st, NULL, fd);
1639 #ifdef HAVE_TM_TM_GMTOFF
1640 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1644 if (!PyArg_ParseTuple(args, "L", &lltime))
1646 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1647 return PyErr_Format(PyExc_OverflowError, "time value too large");
1651 if(localtime_r(&ttime, &tm) == NULL)
1652 return PyErr_SetFromErrno(PyExc_OSError);
1654 // Match the Python struct_time values.
1655 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1656 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1657 tm.tm_hour, tm.tm_min, tm.tm_sec,
1658 tm.tm_wday, tm.tm_yday + 1,
1659 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1661 #endif /* def HAVE_TM_TM_GMTOFF */
1664 #ifdef BUP_MINCORE_BUF_TYPE
1665 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1667 Py_buffer src, dest;
1668 PyObject *py_src_n, *py_src_off, *py_dest_off;
1670 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1671 &src, &py_src_n, &py_src_off,
1672 &dest, &py_dest_off))
1675 PyObject *result = NULL;
1677 unsigned long long src_n, src_off, dest_off;
1678 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1679 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1680 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1681 goto clean_and_return;
1683 unsigned long long src_region_end;
1684 if (!uadd(&src_region_end, src_off, src_n)) {
1685 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1686 goto clean_and_return;
1688 assert(src.len >= 0);
1689 if (src_region_end > (unsigned long long) src.len) {
1690 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1691 goto clean_and_return;
1694 unsigned long long dest_size;
1695 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1696 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1697 goto clean_and_return;
1699 if (dest_off > dest_size) {
1700 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1701 goto clean_and_return;
1705 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1706 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1707 goto clean_and_return;
1709 int rc = mincore((void *)(src.buf + src_off), src_n,
1710 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1712 result = PyErr_SetFromErrno(PyExc_OSError);
1713 goto clean_and_return;
1715 result = Py_BuildValue("O", Py_None);
1718 PyBuffer_Release(&src);
1719 PyBuffer_Release(&dest);
1722 #endif /* def BUP_MINCORE_BUF_TYPE */
1725 static PyObject *tuple_from_cstrs(char **cstrs)
1727 // Assumes list is null terminated
1729 while(cstrs[n] != NULL)
1733 if (!INTEGRAL_ASSIGNMENT_FITS(&sn, n))
1734 return PyErr_Format(PyExc_OverflowError, "string array too large");
1736 PyObject *result = PyTuple_New(sn);
1738 for (i = 0; i < sn; i++)
1740 PyObject *gname = Py_BuildValue(cstr_argf, cstrs[i]);
1746 PyTuple_SET_ITEM(result, i, gname);
1752 static long getpw_buf_size;
1754 static PyObject *pwd_struct_to_py(const struct passwd *pwd, int rc)
1756 // We can check the known (via POSIX) signed and unsigned types at
1757 // compile time, but not (easily) the unspecified types, so handle
1758 // those via INTEGER_TO_PY().
1760 return Py_BuildValue(cstr_argf cstr_argf "OO"
1761 cstr_argf cstr_argf cstr_argf,
1764 INTEGER_TO_PY(pwd->pw_uid),
1765 INTEGER_TO_PY(pwd->pw_gid),
1770 return Py_BuildValue("O", Py_None);
1771 if (rc == EIO || rc == EMFILE || rc == ENFILE)
1772 return PyErr_SetFromErrno(PyExc_IOError);
1774 return PyErr_SetFromErrno(PyExc_OSError);
1778 static PyObject *bup_getpwuid(PyObject *self, PyObject *args)
1781 if (!PyArg_ParseTuple(args, "k", &uid))
1784 struct passwd pwd, *result_pwd;
1785 char *buf = PyMem_Malloc(getpw_buf_size);
1789 int rc = getpwuid_r(uid, &pwd, buf, getpw_buf_size, &result_pwd);
1790 PyObject *result = pwd_struct_to_py(result_pwd, rc);
1795 static PyObject *bup_getpwnam(PyObject *self, PyObject *args)
1798 if (!PyArg_ParseTuple(args, "S", &py_name))
1801 struct passwd pwd, *result_pwd;
1802 char *buf = PyMem_Malloc(getpw_buf_size);
1806 char *name = PyBytes_AS_STRING(py_name);
1807 int rc = getpwnam_r(name, &pwd, buf, getpw_buf_size, &result_pwd);
1808 PyObject *result = pwd_struct_to_py(result_pwd, rc);
1813 static long getgr_buf_size;
1815 static PyObject *grp_struct_to_py(const struct group *grp, int rc)
1817 // We can check the known (via POSIX) signed and unsigned types at
1818 // compile time, but not (easily) the unspecified types, so handle
1819 // those via INTEGER_TO_PY().
1821 PyObject *members = tuple_from_cstrs(grp->gr_mem);
1822 if (members == NULL)
1824 return Py_BuildValue(cstr_argf cstr_argf "OO",
1827 INTEGER_TO_PY(grp->gr_gid),
1831 return Py_BuildValue("O", Py_None);
1833 if (rc == EIO || rc == EMFILE || rc == ENFILE)
1834 return PyErr_SetFromErrno(PyExc_IOError);
1835 return PyErr_SetFromErrno(PyExc_OSError);
1838 static PyObject *bup_getgrgid(PyObject *self, PyObject *args)
1841 if (!PyArg_ParseTuple(args, "k", &gid))
1844 struct group grp, *result_grp;
1845 char *buf = PyMem_Malloc(getgr_buf_size);
1849 int rc = getgrgid_r(gid, &grp, buf, getgr_buf_size, &result_grp);
1850 PyObject *result = grp_struct_to_py(result_grp, rc);
1855 static PyObject *bup_getgrnam(PyObject *self, PyObject *args)
1858 if (!PyArg_ParseTuple(args, "S", &py_name))
1861 struct group grp, *result_grp;
1862 char *buf = PyMem_Malloc(getgr_buf_size);
1866 char *name = PyBytes_AS_STRING(py_name);
1867 int rc = getgrnam_r(name, &grp, buf, getgr_buf_size, &result_grp);
1868 PyObject *result = grp_struct_to_py(result_grp, rc);
1873 static PyObject *bup_gethostname(PyObject *mod, PyObject *ignore)
1875 #ifdef HOST_NAME_MAX
1876 char buf[HOST_NAME_MAX + 1] = {};
1878 /* 'SUSv2 guarantees that "Host names are limited to 255 bytes".' */
1882 if (gethostname(buf, sizeof(buf) - 1))
1883 return PyErr_SetFromErrno(PyExc_IOError);
1884 return PyBytes_FromString(buf);
1888 #ifdef BUP_HAVE_READLINE
1890 static char *cstr_from_bytes(PyObject *bytes)
1894 int rc = PyBytes_AsStringAndSize(bytes, &buf, &length);
1897 char *result = checked_malloc(length, sizeof(char));
1900 memcpy(result, buf, length);
1904 static char **cstrs_from_seq(PyObject *seq)
1906 char **result = NULL;
1907 seq = PySequence_Fast(seq, "Cannot convert sequence items to C strings");
1911 const Py_ssize_t len = PySequence_Fast_GET_SIZE(seq);
1912 if (len > PY_SSIZE_T_MAX - 1) {
1913 PyErr_Format(PyExc_OverflowError,
1914 "Sequence length %zd too large for conversion to C array",
1918 result = checked_malloc(len + 1, sizeof(char *));
1922 for (i = 0; i < len; i++)
1924 PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
1926 goto abandon_result;
1927 result[i] = cstr_from_bytes(item);
1930 goto abandon_result;
1948 static char* our_word_break_chars = NULL;
1951 bup_set_completer_word_break_characters(PyObject *self, PyObject *args)
1954 if (!PyArg_ParseTuple(args, cstr_argf, &bytes))
1956 char *prev = our_word_break_chars;
1957 char *next = strdup(bytes);
1959 return PyErr_NoMemory();
1960 our_word_break_chars = next;
1961 rl_completer_word_break_characters = next;
1968 bup_get_completer_word_break_characters(PyObject *self, PyObject *args)
1970 if (!PyArg_ParseTuple(args, ""))
1972 return PyBytes_FromString(rl_completer_word_break_characters);
1975 static PyObject *bup_get_line_buffer(PyObject *self, PyObject *args)
1977 if (!PyArg_ParseTuple(args, ""))
1979 return PyBytes_FromString(rl_line_buffer);
1983 bup_parse_and_bind(PyObject *self, PyObject *args)
1986 if (!PyArg_ParseTuple(args, cstr_argf ":parse_and_bind", &bytes))
1988 char *tmp = strdup(bytes); // Because it may modify the arg
1990 return PyErr_NoMemory();
1991 int rc = rl_parse_and_bind(tmp);
1994 return PyErr_Format(PyExc_OSError,
1995 "system rl_parse_and_bind failed (%d)", rc);
2000 static PyObject *py_on_attempted_completion;
2001 static char **prev_completions;
2003 static char **on_attempted_completion(const char *text, int start, int end)
2005 if (!py_on_attempted_completion)
2008 char **result = NULL;
2009 PyObject *py_result = PyObject_CallFunction(py_on_attempted_completion,
2014 if (py_result != Py_None) {
2015 result = cstrs_from_seq(py_result);
2016 free(prev_completions);
2017 prev_completions = result;
2019 Py_DECREF(py_result);
2024 bup_set_attempted_completion_function(PyObject *self, PyObject *args)
2026 PyObject *completer;
2027 if (!PyArg_ParseTuple(args, "O", &completer))
2030 PyObject *prev = py_on_attempted_completion;
2031 if (completer == Py_None)
2033 py_on_attempted_completion = NULL;
2034 rl_attempted_completion_function = NULL;
2036 py_on_attempted_completion = completer;
2037 rl_attempted_completion_function = on_attempted_completion;
2038 Py_INCREF(completer);
2045 static PyObject *py_on_completion_entry;
2047 static char *on_completion_entry(const char *text, int state)
2049 if (!py_on_completion_entry)
2052 PyObject *py_result = PyObject_CallFunction(py_on_completion_entry,
2053 cstr_argf "i", text, state);
2056 char *result = (py_result == Py_None) ? NULL : cstr_from_bytes(py_result);
2057 Py_DECREF(py_result);
2062 bup_set_completion_entry_function(PyObject *self, PyObject *args)
2064 PyObject *completer;
2065 if (!PyArg_ParseTuple(args, "O", &completer))
2068 PyObject *prev = py_on_completion_entry;
2069 if (completer == Py_None) {
2070 py_on_completion_entry = NULL;
2071 rl_completion_entry_function = NULL;
2073 py_on_completion_entry = completer;
2074 rl_completion_entry_function = on_completion_entry;
2075 Py_INCREF(completer);
2082 bup_readline(PyObject *self, PyObject *args)
2085 if (!PyArg_ParseTuple(args, cstr_argf, &prompt))
2087 char *line = readline(prompt);
2089 return PyErr_Format(PyExc_EOFError, "readline EOF");
2090 PyObject *result = PyBytes_FromString(line);
2095 #endif // defined BUP_HAVE_READLINE
2097 #if defined(HAVE_SYS_ACL_H) && \
2098 defined(HAVE_ACL_LIBACL_H) && \
2099 defined(HAVE_ACL_EXTENDED_FILE) && \
2100 defined(HAVE_ACL_GET_FILE) && \
2101 defined(HAVE_ACL_TO_ANY_TEXT) && \
2102 defined(HAVE_ACL_FROM_TEXT) && \
2103 defined(HAVE_ACL_SET_FILE)
2104 #define ACL_SUPPORT 1
2105 #include <sys/acl.h>
2106 #include <acl/libacl.h>
2110 // -1 for errors, with python exception set
2111 // -2 for ignored errors (not supported)
2112 static int bup_read_acl_to_text(const char *name, acl_type_t type,
2113 char **txt, char **num)
2117 acl = acl_get_file(name, type);
2119 if (errno == EOPNOTSUPP || errno == ENOSYS)
2121 PyErr_SetFromErrno(PyExc_IOError);
2126 *txt = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE);
2128 *num = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE | TEXT_NUMERIC_IDS);
2133 if (errno == ENOMEM)
2136 PyErr_SetFromErrno(PyExc_IOError);
2139 acl_free((acl_t)*txt);
2141 acl_free((acl_t)*num);
2146 static PyObject *bup_read_acl(PyObject *self, PyObject *args)
2150 PyObject *ret = NULL;
2151 char *acl_txt = NULL, *acl_num = NULL;
2153 if (!PyArg_ParseTuple(args, cstr_argf "i", &name, &isdir))
2156 if (!acl_extended_file(name))
2159 rv = bup_read_acl_to_text(name, ACL_TYPE_ACCESS, &acl_txt, &acl_num);
2164 char *def_txt = NULL, *def_num = NULL;
2166 rv = bup_read_acl_to_text(name, ACL_TYPE_DEFAULT, &def_txt, &def_num);
2170 ret = Py_BuildValue("[" cstr_argf cstr_argf cstr_argf cstr_argf "]",
2171 acl_txt, acl_num, def_txt, def_num);
2174 acl_free((acl_t)def_txt);
2176 acl_free((acl_t)def_num);
2178 ret = Py_BuildValue("[" cstr_argf cstr_argf "]",
2184 acl_free((acl_t)acl_txt);
2186 acl_free((acl_t)acl_num);
2192 static int bup_apply_acl_string(const char *name, const char *s)
2194 acl_t acl = acl_from_text(s);
2198 PyErr_SetFromErrno(PyExc_IOError);
2202 if (acl_set_file(name, ACL_TYPE_ACCESS, acl)) {
2203 PyErr_SetFromErrno(PyExc_IOError);
2212 static PyObject *bup_apply_acl(PyObject *self, PyObject *args)
2214 char *name, *acl, *def = NULL;
2216 if (!PyArg_ParseTuple(args, cstr_argf cstr_argf "|" cstr_argf, &name, &acl, &def))
2219 if (bup_apply_acl_string(name, acl))
2222 if (def && bup_apply_acl_string(name, def))
2229 static PyMethodDef helper_methods[] = {
2230 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
2231 "Write buf excepting zeros at the end. Return trailing zero count." },
2232 { "selftest", selftest, METH_VARARGS,
2233 "Check that the rolling checksum rolls correctly (for unit tests)." },
2234 { "blobbits", blobbits, METH_VARARGS,
2235 "Return the number of bits in the rolling checksum." },
2236 { "splitbuf", splitbuf, METH_VARARGS,
2237 "Split a list of strings based on a rolling checksum." },
2238 { "bitmatch", bitmatch, METH_VARARGS,
2239 "Count the number of matching prefix bits between two strings." },
2240 { "firstword", firstword, METH_VARARGS,
2241 "Return an int corresponding to the first 32 bits of buf." },
2242 { "bloom_contains", bloom_contains, METH_VARARGS,
2243 "Check if a bloom filter of 2^nbits bytes contains an object" },
2244 { "bloom_add", bloom_add, METH_VARARGS,
2245 "Add an object to a bloom filter of 2^nbits bytes" },
2246 { "extract_bits", extract_bits, METH_VARARGS,
2247 "Take the first 'nbits' bits from 'buf' and return them as an int." },
2248 { "merge_into", merge_into, METH_VARARGS,
2249 "Merges a bunch of idx and midx files into a single midx." },
2250 { "write_idx", write_idx, METH_VARARGS,
2251 "Write a PackIdxV2 file from an idx list of lists of tuples" },
2252 { "write_random", write_random, METH_VARARGS,
2253 "Write random bytes to the given file descriptor" },
2254 { "random_sha", random_sha, METH_VARARGS,
2255 "Return a random 20-byte string" },
2256 { "open_noatime", open_noatime, METH_VARARGS,
2257 "open() the given filename for read with O_NOATIME if possible" },
2258 { "fadvise_done", fadvise_done, METH_VARARGS,
2259 "Inform the kernel that we're finished with earlier parts of a file" },
2260 #ifdef BUP_HAVE_FILE_ATTRS
2261 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
2262 "Return the Linux attributes for the given file." },
2264 #ifdef BUP_HAVE_FILE_ATTRS
2265 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
2266 "Set the Linux attributes for the given file." },
2268 #ifdef HAVE_UTIMENSAT
2269 { "bup_utimensat", bup_utimensat, METH_VARARGS,
2270 "Change path timestamps with nanosecond precision (POSIX)." },
2273 { "bup_utimes", bup_utimes, METH_VARARGS,
2274 "Change path timestamps with microsecond precision." },
2277 { "bup_lutimes", bup_lutimes, METH_VARARGS,
2278 "Change path timestamps with microsecond precision;"
2279 " don't follow symlinks." },
2281 { "stat", bup_stat, METH_VARARGS,
2282 "Extended version of stat." },
2283 { "lstat", bup_lstat, METH_VARARGS,
2284 "Extended version of lstat." },
2285 { "fstat", bup_fstat, METH_VARARGS,
2286 "Extended version of fstat." },
2287 #ifdef HAVE_TM_TM_GMTOFF
2288 { "localtime", bup_localtime, METH_VARARGS,
2289 "Return struct_time elements plus the timezone offset and name." },
2291 { "bytescmp", bup_bytescmp, METH_VARARGS,
2292 "Return a negative value if x < y, zero if equal, positive otherwise."},
2293 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
2294 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
2295 #ifdef BUP_MINCORE_BUF_TYPE
2296 { "mincore", bup_mincore, METH_VARARGS,
2297 "For mincore(src, src_n, src_off, dest, dest_off)"
2298 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
2300 { "getpwuid", bup_getpwuid, METH_VARARGS,
2301 "Return the password database entry for the given numeric user id,"
2302 " as a tuple with all C strings as bytes(), or None if the user does"
2304 { "getpwnam", bup_getpwnam, METH_VARARGS,
2305 "Return the password database entry for the given user name,"
2306 " as a tuple with all C strings as bytes(), or None if the user does"
2308 { "getgrgid", bup_getgrgid, METH_VARARGS,
2309 "Return the group database entry for the given numeric group id,"
2310 " as a tuple with all C strings as bytes(), or None if the group does"
2312 { "getgrnam", bup_getgrnam, METH_VARARGS,
2313 "Return the group database entry for the given group name,"
2314 " as a tuple with all C strings as bytes(), or None if the group does"
2316 { "gethostname", bup_gethostname, METH_NOARGS,
2317 "Return the current hostname (as bytes)" },
2318 #ifdef BUP_HAVE_READLINE
2319 { "set_completion_entry_function", bup_set_completion_entry_function, METH_VARARGS,
2320 "Set rl_completion_entry_function. Called as f(text, state)." },
2321 { "set_attempted_completion_function", bup_set_attempted_completion_function, METH_VARARGS,
2322 "Set rl_attempted_completion_function. Called as f(text, start, end)." },
2323 { "parse_and_bind", bup_parse_and_bind, METH_VARARGS,
2324 "Call rl_parse_and_bind." },
2325 { "get_line_buffer", bup_get_line_buffer, METH_NOARGS,
2326 "Return rl_line_buffer." },
2327 { "get_completer_word_break_characters", bup_get_completer_word_break_characters, METH_NOARGS,
2328 "Return rl_completer_word_break_characters." },
2329 { "set_completer_word_break_characters", bup_set_completer_word_break_characters, METH_VARARGS,
2330 "Set rl_completer_word_break_characters." },
2331 { "readline", bup_readline, METH_VARARGS,
2332 "Call readline(prompt)." },
2333 #endif // defined BUP_HAVE_READLINE
2335 { "read_acl", bup_read_acl, METH_VARARGS,
2336 "read_acl(name, isdir)\n\n"
2337 "Read ACLs for the given file/dirname and return the correctly encoded"
2338 " list [txt, num, def_tx, def_num] (the def_* being empty bytestrings"
2339 " unless the second argument 'isdir' is True)." },
2340 { "apply_acl", bup_apply_acl, METH_VARARGS,
2341 "apply_acl(name, acl, def=None)\n\n"
2342 "Given a file/dirname (bytes) and the ACLs to restore, do that." },
2343 #endif /* HAVE_ACLS */
2344 { NULL, NULL, 0, NULL }, // sentinel
2347 static void test_integral_assignment_fits(void)
2349 assert(sizeof(signed short) == sizeof(unsigned short));
2350 assert(sizeof(signed short) < sizeof(signed long long));
2351 assert(sizeof(signed short) < sizeof(unsigned long long));
2352 assert(sizeof(unsigned short) < sizeof(signed long long));
2353 assert(sizeof(unsigned short) < sizeof(unsigned long long));
2354 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
2356 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
2357 unsigned short us, usmax = USHRT_MAX;
2358 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
2359 unsigned long long ullmax = ULLONG_MAX;
2361 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
2362 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
2363 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
2364 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
2365 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
2366 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
2368 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
2369 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
2370 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
2371 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
2372 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
2376 static int setup_module(PyObject *m)
2378 // FIXME: migrate these tests to configure, or at least don't
2379 // possibly crash the whole application. Check against the type
2380 // we're going to use when passing to python. Other stat types
2381 // are tested at runtime.
2382 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
2383 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
2384 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
2385 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
2386 // Just be sure (relevant when passing timestamps back to Python above).
2387 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
2388 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
2390 test_integral_assignment_fits();
2392 // Originally required by append_sparse_region()
2395 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
2397 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
2403 #pragma clang diagnostic push
2404 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
2407 value = INTEGER_TO_PY(INT_MAX);
2408 PyObject_SetAttrString(m, "INT_MAX", value);
2410 value = INTEGER_TO_PY(UINT_MAX);
2411 PyObject_SetAttrString(m, "UINT_MAX", value);
2414 #ifdef HAVE_UTIMENSAT
2417 value = INTEGER_TO_PY(AT_FDCWD);
2418 PyObject_SetAttrString(m, "AT_FDCWD", value);
2420 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
2421 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
2423 value = INTEGER_TO_PY(UTIME_NOW);
2424 PyObject_SetAttrString(m, "UTIME_NOW", value);
2428 #ifdef BUP_HAVE_MINCORE_INCORE
2431 value = INTEGER_TO_PY(MINCORE_INCORE);
2432 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
2436 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
2438 getpw_buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
2439 if (getpw_buf_size == -1)
2440 getpw_buf_size = 16384;
2442 getgr_buf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
2443 if (getgr_buf_size == -1)
2444 getgr_buf_size = 16384;
2446 e = getenv("BUP_FORCE_TTY");
2447 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
2453 #if PY_MAJOR_VERSION < 3
2455 PyMODINIT_FUNC init_helpers(void)
2457 PyObject *m = Py_InitModule("_helpers", helper_methods);
2461 if (!setup_module(m))
2468 # else // PY_MAJOR_VERSION >= 3
2470 static struct PyModuleDef helpers_def = {
2471 PyModuleDef_HEAD_INIT,
2477 NULL, // helpers_traverse,
2478 NULL, // helpers_clear,
2482 PyMODINIT_FUNC PyInit__helpers(void)
2484 PyObject *module = PyModule_Create(&helpers_def);
2487 if (!setup_module(module))
2495 #endif // PY_MAJOR_VERSION >= 3