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
51 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
52 #define BUP_HAVE_FILE_ATTRS 1
56 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
57 * pretend we don't have it.
59 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
64 // Of course, this assumes it's a bitfield value.
69 typedef unsigned char byte;
76 // cstr_argf: for byte vectors without null characters (e.g. paths)
77 // rbuf_argf: for read-only byte vectors
78 // wbuf_argf: for mutable byte vectors
80 #if PY_MAJOR_VERSION < 3
82 # define get_state(x) (&state)
83 # define cstr_argf "s"
84 # define rbuf_argf "s#"
85 # define wbuf_argf "s*"
87 # define get_state(x) ((state_t *) PyModule_GetState(x))
88 # define cstr_argf "y"
89 # define rbuf_argf "y#"
90 # define wbuf_argf "y*"
91 #endif // PY_MAJOR_VERSION >= 3
94 static void *checked_calloc(size_t n, size_t size)
96 void *result = calloc(n, size);
102 #ifndef BUP_HAVE_BUILTIN_MUL_OVERFLOW
104 #define checked_malloc checked_calloc
106 #else // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
108 static void *checked_malloc(size_t n, size_t size)
111 if (__builtin_mul_overflow(n, size, &total))
113 PyErr_Format(PyExc_OverflowError,
114 "request to allocate %lu items of size %lu is too large",
118 void *result = malloc(total);
120 return PyErr_NoMemory();
124 #endif // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
128 // This function should technically be macro'd out if it's going to be used
129 // more than ocasionally. As of this writing, it'll actually never be called
130 // in real world bup scenarios (because our packs are < MAX_INT bytes).
131 static uint64_t htonll(uint64_t value)
133 static const int endian_test = 42;
135 if (*(char *)&endian_test == endian_test) // LSB-MSB
136 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
137 return value; // already in network byte order MSB-LSB
142 // Disabling sign-compare here should be fine since we're explicitly
143 // checking for a sign mismatch, i.e. if the signs don't match, then
144 // it doesn't matter what the value comparison says.
145 // FIXME: ... so should we reverse the order?
146 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
148 _Pragma("GCC diagnostic push"); \
149 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
151 int result = *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
152 _Pragma("GCC diagnostic pop"); \
157 // At the moment any code that calls INTEGER_TO_PY() will have to
158 // disable -Wtautological-compare for clang. See below.
160 #define INTEGER_TO_PY(x) \
161 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
165 #if PY_MAJOR_VERSION < 3
166 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
169 const long tmp = PyInt_AsLong(py);
170 if (tmp == -1 && PyErr_Occurred())
172 if (PyErr_ExceptionMatches(PyExc_OverflowError))
173 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
179 PyErr_Format(PyExc_OverflowError,
180 "negative %s cannot be converted to unsigned long", name);
189 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
191 #if PY_MAJOR_VERSION < 3
193 return bup_ulong_from_pyint(x, py, name);
196 if (!PyLong_Check(py))
198 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
202 const unsigned long tmp = PyLong_AsUnsignedLong(py);
203 if (PyErr_Occurred())
205 if (PyErr_ExceptionMatches(PyExc_OverflowError))
206 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
215 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
218 if (!bup_ulong_from_py(&tmp, py, name))
223 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
230 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
233 #if PY_MAJOR_VERSION < 3
237 if (bup_ulong_from_pyint(&tmp, py, name))
246 if (!PyLong_Check(py))
248 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
252 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
253 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
255 if (PyErr_ExceptionMatches(PyExc_OverflowError))
256 PyErr_Format(PyExc_OverflowError,
257 "%s too big for unsigned long long", name);
265 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
267 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
268 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
271 Py_ssize_t s1_len, s2_len;
272 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
274 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
276 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
277 const int cmp = memcmp(s1, s2, n);
279 return PyLong_FromLong(cmp);
280 if (s1_len == s2_len)
281 return PyLong_FromLong(0);;
282 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
286 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
288 unsigned char *bufx = NULL, *bufy = NULL;
289 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
290 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
291 if (!PyArg_ParseTuple(args,
294 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
295 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
298 return PyErr_Format(PyExc_ValueError, "negative x offset");
300 return PyErr_Format(PyExc_ValueError, "negative x extent");
301 if (bufx_ofs > bufx_len)
302 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
303 if (bufx_n > bufx_len - bufx_ofs)
304 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
307 return PyErr_Format(PyExc_ValueError, "negative y offset");
309 return PyErr_Format(PyExc_ValueError, "negative y extent");
310 if (bufy_ofs > bufy_len)
311 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
312 if (bufy_n > bufy_len - bufy_ofs)
313 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
315 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
316 return PyErr_Format(PyExc_OverflowError, "result length too long");
318 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
320 return PyErr_NoMemory();
321 char *buf = PyBytes_AS_STRING(result);
322 memcpy(buf, bufx + bufx_ofs, bufx_n);
323 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
329 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
330 #if __WIN32__ || __CYGWIN__
332 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
333 static void unpythonize_argv(void) { }
335 #else // not __WIN32__
337 // For some reason this isn't declared in Python.h
338 extern void Py_GetArgcArgv(int *argc, char ***argv);
340 static void unpythonize_argv(void)
345 Py_GetArgcArgv(&argc, &argv);
347 for (i = 0; i < argc-1; i++)
349 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
351 // The argv block doesn't work the way we expected; it's unsafe
357 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
359 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
363 p = strrchr(argv[1], '/');
369 memmove(argv[0], p, len);
370 memset(arge - diff, 0, diff);
371 for (i = 0; i < argc; i++)
372 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
377 #endif // not __WIN32__ or __CYGWIN__
380 static int write_all(int fd, const void *buf, const size_t count)
383 while (written < count)
385 const ssize_t rc = write(fd, buf + written, count - written);
394 static int uadd(unsigned long long *dest,
395 const unsigned long long x,
396 const unsigned long long y)
398 const unsigned long long result = x + y;
399 if (result < x || result < y)
406 static PyObject *append_sparse_region(const int fd, unsigned long long n)
411 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
413 const off_t off = lseek(fd, new_off, SEEK_CUR);
414 if (off == (off_t) -1)
415 return PyErr_SetFromErrno(PyExc_IOError);
422 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
424 unsigned long long prev_pending,
425 const unsigned long long count)
427 // Add count additional sparse zeros to prev_pending and store the
428 // result in new_pending, or if the total won't fit in
429 // new_pending, write some of the zeros to fd sparsely, and store
430 // the remaining sum in new_pending.
431 if (!uadd(new_pending, prev_pending, count))
433 PyObject *err = append_sparse_region(fd, prev_pending);
436 *new_pending = count;
442 static byte* find_not_zero(const byte * const start, const byte * const end)
444 // Return a pointer to first non-zero byte between start and end,
445 // or end if there isn't one.
446 assert(start <= end);
447 const unsigned char *cur = start;
448 while (cur < end && *cur == 0)
454 static byte* find_trailing_zeros(const byte * const start,
455 const byte * const end)
457 // Return a pointer to the start of any trailing run of zeros, or
458 // end if there isn't one.
459 assert(start <= end);
462 const byte * cur = end;
463 while (cur > start && *--cur == 0) {}
467 return (byte *) (cur + 1);
471 static byte *find_non_sparse_end(const byte * const start,
472 const byte * const end,
473 const ptrdiff_t min_len)
475 // Return the first pointer to a min_len sparse block in [start,
476 // end) if there is one, otherwise a pointer to the start of any
477 // trailing run of zeros. If there are no trailing zeros, return
483 // Probe in min_len jumps, searching backward from the jump
484 // destination for a non-zero byte. If such a byte is found, move
485 // just past it and try again.
486 const byte *candidate = start;
487 // End of any run of zeros, starting at candidate, that we've already seen
488 const byte *end_of_known_zeros = candidate;
489 while (end - candidate >= min_len) // Handle all min_len candidate blocks
491 const byte * const probe_end = candidate + min_len;
492 const byte * const trailing_zeros =
493 find_trailing_zeros(end_of_known_zeros, probe_end);
494 if (trailing_zeros == probe_end)
495 end_of_known_zeros = candidate = probe_end;
496 else if (trailing_zeros == end_of_known_zeros)
498 assert(candidate >= start);
499 assert(candidate <= end);
500 assert(*candidate == 0);
501 return (byte *) candidate;
505 candidate = trailing_zeros;
506 end_of_known_zeros = probe_end;
510 if (candidate == end)
513 // No min_len sparse run found, search backward from end
514 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
517 if (trailing_zeros == end_of_known_zeros)
519 assert(candidate >= start);
520 assert(candidate < end);
521 assert(*candidate == 0);
522 assert(end - candidate < min_len);
523 return (byte *) candidate;
526 if (trailing_zeros == end)
528 assert(*(end - 1) != 0);
532 assert(end - trailing_zeros < min_len);
533 assert(trailing_zeros >= start);
534 assert(trailing_zeros < end);
535 assert(*trailing_zeros == 0);
536 return (byte *) trailing_zeros;
540 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
543 unsigned char *buf = NULL;
545 PyObject *py_min_sparse_len, *py_prev_sparse_len;
546 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
547 &fd, &buf, &sbuf_len,
548 &py_min_sparse_len, &py_prev_sparse_len))
550 ptrdiff_t min_sparse_len;
551 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
552 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
554 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
555 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
556 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
559 return PyErr_Format(PyExc_ValueError, "negative bufer length");
560 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
561 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
563 const byte * block = buf; // Start of pending block
564 const byte * const end = buf + buf_len;
565 unsigned long long zeros = prev_sparse_len;
568 assert(block <= end);
570 return PyLong_FromUnsignedLongLong(zeros);
574 // Look for the end of block, i.e. the next sparse run of
575 // at least min_sparse_len zeros, or the end of the
577 const byte * const probe = find_non_sparse_end(block + 1, end,
579 // Either at end of block, or end of non-sparse; write pending data
580 PyObject *err = append_sparse_region(fd, zeros);
583 int rc = write_all(fd, block, probe - block);
585 return PyErr_SetFromErrno(PyExc_IOError);
587 if (end - probe < min_sparse_len)
590 zeros = min_sparse_len;
591 block = probe + zeros;
595 // Should be in the first loop iteration, a sparse run of
596 // zeros, or nearly at the end of the block (within
598 const byte * const zeros_end = find_not_zero(block, end);
599 PyObject *err = record_sparse_zeros(&zeros, fd,
600 zeros, zeros_end - block);
603 assert(block <= zeros_end);
610 static PyObject *selftest(PyObject *self, PyObject *args)
612 if (!PyArg_ParseTuple(args, ""))
615 return Py_BuildValue("i", !bupsplit_selftest());
619 static PyObject *blobbits(PyObject *self, PyObject *args)
621 if (!PyArg_ParseTuple(args, ""))
623 return Py_BuildValue("i", BUP_BLOBBITS);
627 static PyObject *splitbuf(PyObject *self, PyObject *args)
629 // We stick to buffers in python 2 because they appear to be
630 // substantially smaller than memoryviews, and because
631 // zlib.compress() in python 2 can't accept a memoryview
632 // (cf. hashsplit.py).
633 int out = 0, bits = -1;
634 if (PY_MAJOR_VERSION > 2)
637 if (!PyArg_ParseTuple(args, "y*", &buf))
639 assert(buf.len <= INT_MAX);
640 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
641 PyBuffer_Release(&buf);
645 unsigned char *buf = NULL;
647 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
649 assert(len <= INT_MAX);
650 out = bupsplit_find_ofs(buf, len, &bits);
652 if (out) assert(bits >= BUP_BLOBBITS);
653 return Py_BuildValue("ii", out, bits);
657 static PyObject *bitmatch(PyObject *self, PyObject *args)
659 unsigned char *buf1 = NULL, *buf2 = NULL;
660 Py_ssize_t len1 = 0, len2 = 0;
664 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
668 for (byte = 0; byte < len1 && byte < len2; byte++)
670 int b1 = buf1[byte], b2 = buf2[byte];
673 for (bit = 0; bit < 8; bit++)
674 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
680 assert(byte <= (INT_MAX >> 3));
681 return Py_BuildValue("i", byte*8 + bit);
685 static PyObject *firstword(PyObject *self, PyObject *args)
687 unsigned char *buf = NULL;
691 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
697 v = ntohl(*(uint32_t *)buf);
698 return PyLong_FromUnsignedLong(v);
702 #define BLOOM2_HEADERLEN 16
704 static void to_bloom_address_bitmask4(const unsigned char *buf,
705 const int nbits, uint64_t *v, unsigned char *bitmask)
711 memcpy(&high, buf, 4);
712 mask = (1<<nbits) - 1;
713 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
714 bit = (raw >> (37-nbits)) & 0x7;
715 *v = (raw >> (40-nbits)) & mask;
719 static void to_bloom_address_bitmask5(const unsigned char *buf,
720 const int nbits, uint32_t *v, unsigned char *bitmask)
726 memcpy(&high, buf, 4);
727 mask = (1<<nbits) - 1;
729 bit = (raw >> (29-nbits)) & 0x7;
730 *v = (raw >> (32-nbits)) & mask;
734 #define BLOOM_SET_BIT(name, address, otype) \
735 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
737 unsigned char bitmask;\
739 address(buf, nbits, &v, &bitmask);\
740 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
742 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
743 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
746 #define BLOOM_GET_BIT(name, address, otype) \
747 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
749 unsigned char bitmask;\
751 address(buf, nbits, &v, &bitmask);\
752 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
754 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
755 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
758 static PyObject *bloom_add(PyObject *self, PyObject *args)
760 Py_buffer bloom, sha;
761 int nbits = 0, k = 0;
762 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
763 &bloom, &sha, &nbits, &k))
766 PyObject *result = NULL;
768 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
769 goto clean_and_return;
774 goto clean_and_return;
775 unsigned char *cur = sha.buf;
777 for (end = cur + sha.len; cur < end; cur += 20/k)
778 bloom_set_bit5(bloom.buf, cur, nbits);
783 goto clean_and_return;
784 unsigned char *cur = sha.buf;
785 unsigned char *end = cur + sha.len;
786 for (; cur < end; cur += 20/k)
787 bloom_set_bit4(bloom.buf, cur, nbits);
790 goto clean_and_return;
792 result = Py_BuildValue("n", sha.len / 20);
795 PyBuffer_Release(&bloom);
796 PyBuffer_Release(&sha);
800 static PyObject *bloom_contains(PyObject *self, PyObject *args)
803 unsigned char *sha = NULL;
805 int nbits = 0, k = 0;
806 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
807 &bloom, &sha, &len, &nbits, &k))
810 PyObject *result = NULL;
813 goto clean_and_return;
818 goto clean_and_return;
821 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
822 if (!bloom_get_bit5(bloom.buf, sha, nbits))
824 result = Py_BuildValue("Oi", Py_None, steps);
825 goto clean_and_return;
831 goto clean_and_return;
834 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
835 if (!bloom_get_bit4(bloom.buf, sha, nbits))
837 result = Py_BuildValue("Oi", Py_None, steps);
838 goto clean_and_return;
842 goto clean_and_return;
844 result = Py_BuildValue("ii", 1, k);
847 PyBuffer_Release(&bloom);
852 static uint32_t _extract_bits(unsigned char *buf, int nbits)
856 mask = (1<<nbits) - 1;
857 v = ntohl(*(uint32_t *)buf);
858 v = (v >> (32-nbits)) & mask;
863 static PyObject *extract_bits(PyObject *self, PyObject *args)
865 unsigned char *buf = NULL;
869 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
875 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
880 unsigned char bytes[20];
883 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
885 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
898 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
901 int low, mid, high, c = 0;
904 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
906 idxs[*last_i] = NULL;
919 mid = (low + high) / 2;
920 c = _cmp_sha(idx->cur, idxs[mid]->cur);
932 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
937 static uint32_t _get_idx_i(struct idx *idx)
939 if (idx->cur_name == NULL)
940 return idx->name_base;
941 return ntohl(*idx->cur_name) + idx->name_base;
944 #define MIDX4_HEADERLEN 12
946 static PyObject *merge_into(PyObject *self, PyObject *args)
948 struct sha *sha_ptr, *sha_start = NULL;
949 uint32_t *table_ptr, *name_ptr, *name_start;
952 uint32_t count, prefix;
957 PyObject *py_total, *ilist = NULL;
958 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
959 &fmap, &bits, &py_total, &ilist))
962 PyObject *result = NULL;
963 struct idx **idxs = NULL;
964 Py_ssize_t num_i = 0;
965 int *idx_buf_init = NULL;
966 Py_buffer *idx_buf = NULL;
968 if (!bup_uint_from_py(&total, py_total, "total"))
969 goto clean_and_return;
971 num_i = PyList_Size(ilist);
973 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
974 goto clean_and_return;
975 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
976 goto clean_and_return;
977 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
978 goto clean_and_return;
980 for (i = 0; i < num_i; i++)
982 long len, sha_ofs, name_map_ofs;
983 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
984 goto clean_and_return;
985 PyObject *itup = PyList_GetItem(ilist, i);
986 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
987 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
988 &idxs[i]->name_base))
991 idxs[i]->map = idx_buf[i].buf;
992 idxs[i]->bytes = idx_buf[i].len;
993 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
994 idxs[i]->end = &idxs[i]->cur[len];
996 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
998 idxs[i]->cur_name = NULL;
1000 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
1001 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
1002 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
1004 Py_ssize_t last_i = num_i - 1;
1010 uint32_t new_prefix;
1011 if (count % 102424 == 0 && get_state(self)->istty2)
1012 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
1013 count*100.0/total, count, total);
1015 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
1016 while (prefix < new_prefix)
1017 table_ptr[prefix++] = htonl(count);
1018 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
1019 *name_ptr++ = htonl(_get_idx_i(idx));
1021 if (idx->cur_name != NULL)
1023 _fix_idx_order(idxs, &last_i);
1026 while (prefix < ((uint32_t) 1 << bits))
1027 table_ptr[prefix++] = htonl(count);
1028 assert(count == total);
1029 assert(prefix == ((uint32_t) 1 << bits));
1030 assert(sha_ptr == sha_start+count);
1031 assert(name_ptr == name_start+count);
1033 result = PyLong_FromUnsignedLong(count);
1038 for (i = 0; i < num_i; i++)
1039 if (idx_buf_init[i])
1040 PyBuffer_Release(&(idx_buf[i]));
1046 for (i = 0; i < num_i; i++)
1050 PyBuffer_Release(&fmap);
1054 #define FAN_ENTRIES 256
1056 static PyObject *write_idx(PyObject *self, PyObject *args)
1058 char *filename = NULL;
1059 PyObject *py_total, *idx = NULL;
1061 unsigned int total = 0;
1063 int i, j, ofs64_count;
1064 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1065 uint64_t *ofs64_ptr;
1066 struct sha *sha_ptr;
1069 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1070 &filename, &fmap, &idx, &py_total))
1073 PyObject *result = NULL;
1075 if (!bup_uint_from_py(&total, py_total, "total"))
1076 goto clean_and_return;
1078 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1080 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1082 goto clean_and_return;
1085 const char idx_header[] = "\377tOc\0\0\0\002";
1086 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1088 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1089 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1090 crc_ptr = (uint32_t *)&sha_ptr[total];
1091 ofs_ptr = (uint32_t *)&crc_ptr[total];
1092 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1096 for (i = 0; i < FAN_ENTRIES; ++i)
1099 part = PyList_GET_ITEM(idx, i);
1101 plen = PyList_GET_SIZE(part);
1103 *fan_ptr++ = htonl(count);
1104 for (j = 0; j < plen; ++j)
1106 unsigned char *sha = NULL;
1107 Py_ssize_t sha_len = 0;
1108 PyObject *crc_py, *ofs_py;
1110 unsigned PY_LONG_LONG ofs_ull;
1112 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1113 &sha, &sha_len, &crc_py, &ofs_py))
1114 goto clean_and_return;
1115 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1116 goto clean_and_return;
1117 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1118 goto clean_and_return;
1119 assert(crc <= UINT32_MAX);
1120 assert(ofs_ull <= UINT64_MAX);
1122 if (sha_len != sizeof(struct sha))
1123 goto clean_and_return;
1124 memcpy(sha_ptr++, sha, sizeof(struct sha));
1125 *crc_ptr++ = htonl(crc);
1126 if (ofs > 0x7fffffff)
1128 *ofs64_ptr++ = htonll(ofs);
1129 ofs = 0x80000000 | ofs64_count++;
1131 *ofs_ptr++ = htonl((uint32_t)ofs);
1135 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1138 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1139 goto clean_and_return;
1142 result = PyLong_FromUnsignedLong(count);
1145 PyBuffer_Release(&fmap);
1150 // I would have made this a lower-level function that just fills in a buffer
1151 // with random values, and then written those values from python. But that's
1152 // about 20% slower in my tests, and since we typically generate random
1153 // numbers for benchmarking other parts of bup, any slowness in generating
1154 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1155 // pseudorandom bytes much except for this anyway.
1156 static PyObject *write_random(PyObject *self, PyObject *args)
1158 uint32_t buf[1024/4];
1159 int fd = -1, seed = 0, verbose = 0;
1161 long long len = 0, kbytes = 0, written = 0;
1163 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1168 for (kbytes = 0; kbytes < len/1024; kbytes++)
1171 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1173 ret = write(fd, buf, sizeof(buf));
1177 if (ret < (int)sizeof(buf))
1179 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1180 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1183 // handle non-multiples of 1024
1187 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1189 ret = write(fd, buf, len % 1024);
1195 if (kbytes/1024 > 0)
1196 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1197 return Py_BuildValue("L", written);
1201 static PyObject *random_sha(PyObject *self, PyObject *args)
1203 static int seeded = 0;
1204 uint32_t shabuf[20/4];
1209 assert(sizeof(shabuf) == 20);
1210 srandom(time(NULL));
1214 if (!PyArg_ParseTuple(args, ""))
1217 memset(shabuf, 0, sizeof(shabuf));
1218 for (i=0; i < 20/4; i++)
1219 shabuf[i] = random();
1220 return Py_BuildValue(rbuf_argf, shabuf, 20);
1224 static int _open_noatime(const char *filename, int attrs)
1226 int attrs_noatime, fd;
1229 attrs |= O_NOFOLLOW;
1232 attrs |= O_LARGEFILE;
1234 attrs_noatime = attrs;
1236 attrs_noatime |= O_NOATIME;
1238 fd = open(filename, attrs_noatime);
1239 if (fd < 0 && errno == EPERM)
1241 // older Linux kernels would return EPERM if you used O_NOATIME
1242 // and weren't the file's owner. This pointless restriction was
1243 // relaxed eventually, but we have to handle it anyway.
1244 // (VERY old kernels didn't recognized O_NOATIME, but they would
1245 // just harmlessly ignore it, so this branch won't trigger)
1246 fd = open(filename, attrs);
1252 static PyObject *open_noatime(PyObject *self, PyObject *args)
1254 char *filename = NULL;
1256 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1258 fd = _open_noatime(filename, 0);
1260 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1261 return Py_BuildValue("i", fd);
1265 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1268 long long llofs, lllen = 0;
1269 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1272 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1273 return PyErr_Format(PyExc_OverflowError,
1274 "fadvise offset overflows off_t");
1275 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1276 return PyErr_Format(PyExc_OverflowError,
1277 "fadvise length overflows off_t");
1278 #ifdef POSIX_FADV_DONTNEED
1279 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1281 return Py_BuildValue("");
1285 // Currently the Linux kernel and FUSE disagree over the type for
1286 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1287 // but FUSE chose long (matching the declaration in linux/fs.h). So
1288 // if you use int, and then traverse a FUSE filesystem, you may
1289 // corrupt the stack. But if you use long, then you may get invalid
1290 // results on big-endian systems.
1292 // For now, we just use long, and then disable Linux attrs entirely
1293 // (with a warning) in helpers.py on systems that are affected.
1295 #ifdef BUP_HAVE_FILE_ATTRS
1296 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1303 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1306 fd = _open_noatime(path, O_NONBLOCK);
1308 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1310 attr = 0; // Handle int/long mismatch (see above)
1311 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1315 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1318 assert(attr <= UINT_MAX); // Kernel type is actually int
1319 return PyLong_FromUnsignedLong(attr);
1321 #endif /* def BUP_HAVE_FILE_ATTRS */
1325 #ifdef BUP_HAVE_FILE_ATTRS
1326 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1329 unsigned long orig_attr;
1335 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1338 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1341 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1343 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1345 // Restrict attr to modifiable flags acdeijstuADST -- see
1346 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1347 // in pf.c flags_array[].
1348 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1349 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1350 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1351 | FS_TOPDIR_FL | FS_NOCOW_FL;
1353 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1354 orig_attr = 0; // Handle int/long mismatch (see above)
1355 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1359 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1361 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1362 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1364 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1368 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1372 return Py_BuildValue("O", Py_None);
1374 #endif /* def BUP_HAVE_FILE_ATTRS */
1377 #ifndef HAVE_UTIMENSAT
1379 #error "cannot find utimensat or utimes()"
1381 #ifndef HAVE_LUTIMES
1382 #error "cannot find utimensat or lutimes()"
1386 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1390 const long long lltmp = PyLong_AsLongLong(pylong); \
1391 if (lltmp == -1 && PyErr_Occurred()) \
1393 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1395 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1396 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1398 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1404 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1412 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1421 #ifdef HAVE_UTIMENSAT
1423 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1428 PyObject *access_py, *modification_py;
1429 struct timespec ts[2];
1431 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1434 &access_py, &(ts[0].tv_nsec),
1435 &modification_py, &(ts[1].tv_nsec),
1440 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1443 PyErr_SetString(PyExc_ValueError,
1444 "unable to convert access time seconds for utimensat");
1447 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1450 PyErr_SetString(PyExc_ValueError,
1451 "unable to convert modification time seconds for utimensat");
1454 rc = utimensat(fd, path, ts, flag);
1456 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1458 return Py_BuildValue("O", Py_None);
1461 #endif /* def HAVE_UTIMENSAT */
1464 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1466 static int bup_parse_xutimes_args(char **path,
1467 struct timeval tv[2],
1470 PyObject *access_py, *modification_py;
1471 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1473 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1475 &access_py, &access_us,
1476 &modification_py, &modification_us))
1480 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1483 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1486 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1488 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1491 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1494 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1497 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1499 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1505 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1509 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1512 struct timeval tv[2];
1513 if (!bup_parse_xutimes_args(&path, tv, args))
1515 int rc = utimes(path, tv);
1517 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1518 return Py_BuildValue("O", Py_None);
1520 #endif /* def HAVE_UTIMES */
1524 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1527 struct timeval tv[2];
1528 if (!bup_parse_xutimes_args(&path, tv, args))
1530 int rc = lutimes(path, tv);
1532 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1534 return Py_BuildValue("O", Py_None);
1536 #endif /* def HAVE_LUTIMES */
1539 #ifdef HAVE_STAT_ST_ATIM
1540 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1541 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1542 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1543 #elif defined HAVE_STAT_ST_ATIMENSEC
1544 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1545 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1546 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1548 # define BUP_STAT_ATIME_NS(st) 0
1549 # define BUP_STAT_MTIME_NS(st) 0
1550 # define BUP_STAT_CTIME_NS(st) 0
1554 #pragma clang diagnostic push
1555 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1557 static PyObject *stat_struct_to_py(const struct stat *st,
1558 const char *filename,
1561 // We can check the known (via POSIX) signed and unsigned types at
1562 // compile time, but not (easily) the unspecified types, so handle
1563 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1565 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1566 INTEGER_TO_PY(st->st_mode),
1567 (unsigned PY_LONG_LONG) st->st_ino,
1568 INTEGER_TO_PY(st->st_dev),
1569 INTEGER_TO_PY(st->st_nlink),
1570 INTEGER_TO_PY(st->st_uid),
1571 INTEGER_TO_PY(st->st_gid),
1572 INTEGER_TO_PY(st->st_rdev),
1573 (PY_LONG_LONG) st->st_size,
1574 INTEGER_TO_PY(st->st_atime),
1575 (long) BUP_STAT_ATIME_NS(st),
1576 INTEGER_TO_PY(st->st_mtime),
1577 (long) BUP_STAT_MTIME_NS(st),
1578 INTEGER_TO_PY(st->st_ctime),
1579 (long) BUP_STAT_CTIME_NS(st));
1582 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1584 static PyObject *bup_stat(PyObject *self, PyObject *args)
1589 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1593 rc = stat(filename, &st);
1595 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1596 return stat_struct_to_py(&st, filename, 0);
1600 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1605 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1609 rc = lstat(filename, &st);
1611 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1612 return stat_struct_to_py(&st, filename, 0);
1616 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1620 if (!PyArg_ParseTuple(args, "i", &fd))
1624 rc = fstat(fd, &st);
1626 return PyErr_SetFromErrno(PyExc_OSError);
1627 return stat_struct_to_py(&st, NULL, fd);
1631 #ifdef HAVE_TM_TM_GMTOFF
1632 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1636 if (!PyArg_ParseTuple(args, "L", &lltime))
1638 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1639 return PyErr_Format(PyExc_OverflowError, "time value too large");
1643 if(localtime_r(&ttime, &tm) == NULL)
1644 return PyErr_SetFromErrno(PyExc_OSError);
1646 // Match the Python struct_time values.
1647 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1648 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1649 tm.tm_hour, tm.tm_min, tm.tm_sec,
1650 tm.tm_wday, tm.tm_yday + 1,
1651 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1653 #endif /* def HAVE_TM_TM_GMTOFF */
1656 #ifdef BUP_MINCORE_BUF_TYPE
1657 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1659 Py_buffer src, dest;
1660 PyObject *py_src_n, *py_src_off, *py_dest_off;
1662 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1663 &src, &py_src_n, &py_src_off,
1664 &dest, &py_dest_off))
1667 PyObject *result = NULL;
1669 unsigned long long src_n, src_off, dest_off;
1670 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1671 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1672 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1673 goto clean_and_return;
1675 unsigned long long src_region_end;
1676 if (!uadd(&src_region_end, src_off, src_n)) {
1677 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1678 goto clean_and_return;
1680 assert(src.len >= 0);
1681 if (src_region_end > (unsigned long long) src.len) {
1682 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1683 goto clean_and_return;
1686 unsigned long long dest_size;
1687 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1688 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1689 goto clean_and_return;
1691 if (dest_off > dest_size) {
1692 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1693 goto clean_and_return;
1697 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1698 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1699 goto clean_and_return;
1701 int rc = mincore((void *)(src.buf + src_off), src_n,
1702 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1704 result = PyErr_SetFromErrno(PyExc_OSError);
1705 goto clean_and_return;
1707 result = Py_BuildValue("O", Py_None);
1710 PyBuffer_Release(&src);
1711 PyBuffer_Release(&dest);
1714 #endif /* def BUP_MINCORE_BUF_TYPE */
1717 static PyObject *tuple_from_cstrs(char **cstrs)
1719 // Assumes list is null terminated
1721 while(cstrs[n] != NULL)
1725 if (!INTEGRAL_ASSIGNMENT_FITS(&sn, n))
1726 return PyErr_Format(PyExc_OverflowError, "string array too large");
1728 PyObject *result = PyTuple_New(sn);
1730 for (i = 0; i < sn; i++)
1732 PyObject *gname = Py_BuildValue(cstr_argf, cstrs[i]);
1738 PyTuple_SET_ITEM(result, i, gname);
1743 static long getpw_buf_size;
1745 static PyObject *pwd_struct_to_py(const struct passwd *pwd, int rc)
1747 // We can check the known (via POSIX) signed and unsigned types at
1748 // compile time, but not (easily) the unspecified types, so handle
1749 // those via INTEGER_TO_PY().
1751 return Py_BuildValue(cstr_argf cstr_argf "OO"
1752 cstr_argf cstr_argf cstr_argf,
1755 INTEGER_TO_PY(pwd->pw_uid),
1756 INTEGER_TO_PY(pwd->pw_gid),
1761 return Py_BuildValue("O", Py_None);
1762 if (rc == EIO || rc == EMFILE || rc == ENFILE)
1763 return PyErr_SetFromErrno(PyExc_IOError);
1765 return PyErr_SetFromErrno(PyExc_OSError);
1769 static PyObject *bup_getpwuid(PyObject *self, PyObject *args)
1772 if (!PyArg_ParseTuple(args, "k", &uid))
1775 struct passwd pwd, *result_pwd;
1776 char *buf = PyMem_Malloc(getpw_buf_size);
1780 int rc = getpwuid_r(uid, &pwd, buf, getpw_buf_size, &result_pwd);
1781 PyObject *result = pwd_struct_to_py(result_pwd, rc);
1786 static PyObject *bup_getpwnam(PyObject *self, PyObject *args)
1789 if (!PyArg_ParseTuple(args, "S", &py_name))
1792 struct passwd pwd, *result_pwd;
1793 char *buf = PyMem_Malloc(getpw_buf_size);
1797 char *name = PyBytes_AS_STRING(py_name);
1798 int rc = getpwnam_r(name, &pwd, buf, getpw_buf_size, &result_pwd);
1799 PyObject *result = pwd_struct_to_py(result_pwd, rc);
1804 static long getgr_buf_size;
1806 static PyObject *grp_struct_to_py(const struct group *grp, int rc)
1808 // We can check the known (via POSIX) signed and unsigned types at
1809 // compile time, but not (easily) the unspecified types, so handle
1810 // those via INTEGER_TO_PY().
1812 PyObject *members = tuple_from_cstrs(grp->gr_mem);
1813 if (members == NULL)
1815 return Py_BuildValue(cstr_argf cstr_argf "OO",
1818 INTEGER_TO_PY(grp->gr_gid),
1822 return Py_BuildValue("O", Py_None);
1823 if (rc == EIO || rc == EMFILE || rc == ENFILE)
1824 return PyErr_SetFromErrno(PyExc_IOError);
1826 return PyErr_SetFromErrno(PyExc_OSError);
1830 static PyObject *bup_getgrgid(PyObject *self, PyObject *args)
1833 if (!PyArg_ParseTuple(args, "k", &gid))
1836 struct group grp, *result_grp;
1837 char *buf = PyMem_Malloc(getgr_buf_size);
1841 int rc = getgrgid_r(gid, &grp, buf, getgr_buf_size, &result_grp);
1842 PyObject *result = grp_struct_to_py(result_grp, rc);
1847 static PyObject *bup_getgrnam(PyObject *self, PyObject *args)
1850 if (!PyArg_ParseTuple(args, "S", &py_name))
1853 struct group grp, *result_grp;
1854 char *buf = PyMem_Malloc(getgr_buf_size);
1858 char *name = PyBytes_AS_STRING(py_name);
1859 int rc = getgrnam_r(name, &grp, buf, getgr_buf_size, &result_grp);
1860 PyObject *result = grp_struct_to_py(result_grp, rc);
1865 static PyObject *bup_gethostname(PyObject *mod, PyObject *ignore)
1867 #ifdef HOST_NAME_MAX
1868 char buf[HOST_NAME_MAX + 1] = {};
1870 /* 'SUSv2 guarantees that "Host names are limited to 255 bytes".' */
1874 if (gethostname(buf, sizeof(buf) - 1))
1875 return PyErr_SetFromErrno(PyExc_IOError);
1876 return PyBytes_FromString(buf);
1879 static PyMethodDef helper_methods[] = {
1880 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1881 "Write buf excepting zeros at the end. Return trailing zero count." },
1882 { "selftest", selftest, METH_VARARGS,
1883 "Check that the rolling checksum rolls correctly (for unit tests)." },
1884 { "blobbits", blobbits, METH_VARARGS,
1885 "Return the number of bits in the rolling checksum." },
1886 { "splitbuf", splitbuf, METH_VARARGS,
1887 "Split a list of strings based on a rolling checksum." },
1888 { "bitmatch", bitmatch, METH_VARARGS,
1889 "Count the number of matching prefix bits between two strings." },
1890 { "firstword", firstword, METH_VARARGS,
1891 "Return an int corresponding to the first 32 bits of buf." },
1892 { "bloom_contains", bloom_contains, METH_VARARGS,
1893 "Check if a bloom filter of 2^nbits bytes contains an object" },
1894 { "bloom_add", bloom_add, METH_VARARGS,
1895 "Add an object to a bloom filter of 2^nbits bytes" },
1896 { "extract_bits", extract_bits, METH_VARARGS,
1897 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1898 { "merge_into", merge_into, METH_VARARGS,
1899 "Merges a bunch of idx and midx files into a single midx." },
1900 { "write_idx", write_idx, METH_VARARGS,
1901 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1902 { "write_random", write_random, METH_VARARGS,
1903 "Write random bytes to the given file descriptor" },
1904 { "random_sha", random_sha, METH_VARARGS,
1905 "Return a random 20-byte string" },
1906 { "open_noatime", open_noatime, METH_VARARGS,
1907 "open() the given filename for read with O_NOATIME if possible" },
1908 { "fadvise_done", fadvise_done, METH_VARARGS,
1909 "Inform the kernel that we're finished with earlier parts of a file" },
1910 #ifdef BUP_HAVE_FILE_ATTRS
1911 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1912 "Return the Linux attributes for the given file." },
1914 #ifdef BUP_HAVE_FILE_ATTRS
1915 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1916 "Set the Linux attributes for the given file." },
1918 #ifdef HAVE_UTIMENSAT
1919 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1920 "Change path timestamps with nanosecond precision (POSIX)." },
1923 { "bup_utimes", bup_utimes, METH_VARARGS,
1924 "Change path timestamps with microsecond precision." },
1927 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1928 "Change path timestamps with microsecond precision;"
1929 " don't follow symlinks." },
1931 { "stat", bup_stat, METH_VARARGS,
1932 "Extended version of stat." },
1933 { "lstat", bup_lstat, METH_VARARGS,
1934 "Extended version of lstat." },
1935 { "fstat", bup_fstat, METH_VARARGS,
1936 "Extended version of fstat." },
1937 #ifdef HAVE_TM_TM_GMTOFF
1938 { "localtime", bup_localtime, METH_VARARGS,
1939 "Return struct_time elements plus the timezone offset and name." },
1941 { "bytescmp", bup_bytescmp, METH_VARARGS,
1942 "Return a negative value if x < y, zero if equal, positive otherwise."},
1943 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
1944 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
1945 #ifdef BUP_MINCORE_BUF_TYPE
1946 { "mincore", bup_mincore, METH_VARARGS,
1947 "For mincore(src, src_n, src_off, dest, dest_off)"
1948 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1950 { "getpwuid", bup_getpwuid, METH_VARARGS,
1951 "Return the password database entry for the given numeric user id,"
1952 " as a tuple with all C strings as bytes(), or None if the user does"
1954 { "getpwnam", bup_getpwnam, METH_VARARGS,
1955 "Return the password database entry for the given user name,"
1956 " as a tuple with all C strings as bytes(), or None if the user does"
1958 { "getgrgid", bup_getgrgid, METH_VARARGS,
1959 "Return the group database entry for the given numeric group id,"
1960 " as a tuple with all C strings as bytes(), or None if the group does"
1962 { "getgrnam", bup_getgrnam, METH_VARARGS,
1963 "Return the group database entry for the given group name,"
1964 " as a tuple with all C strings as bytes(), or None if the group does"
1966 { "gethostname", bup_gethostname, METH_NOARGS,
1967 "Return the current hostname (as bytes)" },
1968 { NULL, NULL, 0, NULL }, // sentinel
1971 static void test_integral_assignment_fits(void)
1973 assert(sizeof(signed short) == sizeof(unsigned short));
1974 assert(sizeof(signed short) < sizeof(signed long long));
1975 assert(sizeof(signed short) < sizeof(unsigned long long));
1976 assert(sizeof(unsigned short) < sizeof(signed long long));
1977 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1978 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
1980 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1981 unsigned short us, usmax = USHRT_MAX;
1982 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1983 unsigned long long ullmax = ULLONG_MAX;
1985 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1986 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1987 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1988 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1989 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1990 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1992 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1993 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1994 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1995 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1996 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
2000 static int setup_module(PyObject *m)
2002 // FIXME: migrate these tests to configure, or at least don't
2003 // possibly crash the whole application. Check against the type
2004 // we're going to use when passing to python. Other stat types
2005 // are tested at runtime.
2006 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
2007 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
2008 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
2009 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
2010 // Just be sure (relevant when passing timestamps back to Python above).
2011 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
2012 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
2014 test_integral_assignment_fits();
2016 // Originally required by append_sparse_region()
2019 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
2021 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
2027 #pragma clang diagnostic push
2028 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
2031 value = INTEGER_TO_PY(INT_MAX);
2032 PyObject_SetAttrString(m, "INT_MAX", value);
2034 value = INTEGER_TO_PY(UINT_MAX);
2035 PyObject_SetAttrString(m, "UINT_MAX", value);
2038 #ifdef HAVE_UTIMENSAT
2041 value = INTEGER_TO_PY(AT_FDCWD);
2042 PyObject_SetAttrString(m, "AT_FDCWD", value);
2044 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
2045 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
2047 value = INTEGER_TO_PY(UTIME_NOW);
2048 PyObject_SetAttrString(m, "UTIME_NOW", value);
2052 #ifdef BUP_HAVE_MINCORE_INCORE
2055 value = INTEGER_TO_PY(MINCORE_INCORE);
2056 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
2060 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
2062 getpw_buf_size = sysconf(_SC_GETPW_R_SIZE_MAX);
2063 if (getpw_buf_size == -1)
2064 getpw_buf_size = 16384;
2066 getgr_buf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
2067 if (getgr_buf_size == -1)
2068 getgr_buf_size = 16384;
2070 e = getenv("BUP_FORCE_TTY");
2071 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
2077 #if PY_MAJOR_VERSION < 3
2079 PyMODINIT_FUNC init_helpers(void)
2081 PyObject *m = Py_InitModule("_helpers", helper_methods);
2085 if (!setup_module(m))
2092 # else // PY_MAJOR_VERSION >= 3
2094 static struct PyModuleDef helpers_def = {
2095 PyModuleDef_HEAD_INIT,
2101 NULL, // helpers_traverse,
2102 NULL, // helpers_clear,
2106 PyMODINIT_FUNC PyInit__helpers(void)
2108 PyObject *module = PyModule_Create(&helpers_def);
2111 if (!setup_module(module))
2119 #endif // PY_MAJOR_VERSION >= 3