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
13 #include <arpa/inet.h>
20 #ifdef HAVE_SYS_MMAN_H
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
26 #ifdef HAVE_SYS_STAT_H
33 #ifdef HAVE_LINUX_FS_H
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
40 #ifdef HAVE_TM_TM_GMTOFF
46 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
47 #define BUP_HAVE_FILE_ATTRS 1
51 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
52 * pretend we don't have it.
54 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
59 // Of course, this assumes it's a bitfield value.
64 typedef unsigned char byte;
71 #if PY_MAJOR_VERSION < 3
73 # define get_state(x) (&state)
75 # define get_state(x) ((state_t *) PyModule_GetState(x))
76 #endif // PY_MAJOR_VERSION >= 3
80 // This function should technically be macro'd out if it's going to be used
81 // more than ocasionally. As of this writing, it'll actually never be called
82 // in real world bup scenarios (because our packs are < MAX_INT bytes).
83 static uint64_t htonll(uint64_t value)
85 static const int endian_test = 42;
87 if (*(char *)&endian_test == endian_test) // LSB-MSB
88 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
89 return value; // already in network byte order MSB-LSB
94 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
97 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
101 // At the moment any code that calls INTGER_TO_PY() will have to
102 // disable -Wtautological-compare for clang. See below.
104 #define INTEGER_TO_PY(x) \
105 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
109 #if PY_MAJOR_VERSION < 3
110 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
113 const long tmp = PyInt_AsLong(py);
114 if (tmp == -1 && PyErr_Occurred())
116 if (PyErr_ExceptionMatches(PyExc_OverflowError))
117 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
123 PyErr_Format(PyExc_OverflowError,
124 "negative %s cannot be converted to unsigned long", name);
133 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
135 #if PY_MAJOR_VERSION < 3
137 return bup_ulong_from_pyint(x, py, name);
140 if (!PyLong_Check(py))
142 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
146 const unsigned long tmp = PyLong_AsUnsignedLong(py);
147 if (PyErr_Occurred())
149 if (PyErr_ExceptionMatches(PyExc_OverflowError))
150 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
159 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
162 if (!bup_ulong_from_py(&tmp, py, name))
167 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
174 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
177 #if PY_MAJOR_VERSION < 3
181 if (bup_ulong_from_pyint(&tmp, py, name))
190 if (!PyLong_Check(py))
192 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
196 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
197 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
199 if (PyErr_ExceptionMatches(PyExc_OverflowError))
200 PyErr_Format(PyExc_OverflowError,
201 "%s too big for unsigned long long", name);
209 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
211 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
212 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
215 Py_ssize_t s1_len, s2_len;
216 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
218 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
220 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
221 const int cmp = memcmp(s1, s2, n);
223 return PyLong_FromLong(cmp);
224 if (s1_len == s2_len)
225 return PyLong_FromLong(0);;
226 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
230 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
231 #if __WIN32__ || __CYGWIN__
233 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
234 static void unpythonize_argv(void) { }
236 #else // not __WIN32__
238 // For some reason this isn't declared in Python.h
239 extern void Py_GetArgcArgv(int *argc, char ***argv);
241 static void unpythonize_argv(void)
246 Py_GetArgcArgv(&argc, &argv);
248 for (i = 0; i < argc-1; i++)
250 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
252 // The argv block doesn't work the way we expected; it's unsafe
258 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
260 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
264 p = strrchr(argv[1], '/');
270 memmove(argv[0], p, len);
271 memset(arge - diff, 0, diff);
272 for (i = 0; i < argc; i++)
273 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
278 #endif // not __WIN32__ or __CYGWIN__
281 static int write_all(int fd, const void *buf, const size_t count)
284 while (written < count)
286 const ssize_t rc = write(fd, buf + written, count - written);
295 static int uadd(unsigned long long *dest,
296 const unsigned long long x,
297 const unsigned long long y)
299 const unsigned long long result = x + y;
300 if (result < x || result < y)
307 static PyObject *append_sparse_region(const int fd, unsigned long long n)
312 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
314 const off_t off = lseek(fd, new_off, SEEK_CUR);
315 if (off == (off_t) -1)
316 return PyErr_SetFromErrno(PyExc_IOError);
323 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
325 unsigned long long prev_pending,
326 const unsigned long long count)
328 // Add count additional sparse zeros to prev_pending and store the
329 // result in new_pending, or if the total won't fit in
330 // new_pending, write some of the zeros to fd sparsely, and store
331 // the remaining sum in new_pending.
332 if (!uadd(new_pending, prev_pending, count))
334 PyObject *err = append_sparse_region(fd, prev_pending);
337 *new_pending = count;
343 static byte* find_not_zero(const byte * const start, const byte * const end)
345 // Return a pointer to first non-zero byte between start and end,
346 // or end if there isn't one.
347 assert(start <= end);
348 const unsigned char *cur = start;
349 while (cur < end && *cur == 0)
355 static byte* find_trailing_zeros(const byte * const start,
356 const byte * const end)
358 // Return a pointer to the start of any trailing run of zeros, or
359 // end if there isn't one.
360 assert(start <= end);
363 const byte * cur = end;
364 while (cur > start && *--cur == 0) {}
368 return (byte *) (cur + 1);
372 static byte *find_non_sparse_end(const byte * const start,
373 const byte * const end,
374 const unsigned long long min_len)
376 // Return the first pointer to a min_len sparse block in [start,
377 // end) if there is one, otherwise a pointer to the start of any
378 // trailing run of zeros. If there are no trailing zeros, return
384 // Probe in min_len jumps, searching backward from the jump
385 // destination for a non-zero byte. If such a byte is found, move
386 // just past it and try again.
387 const byte *candidate = start;
388 // End of any run of zeros, starting at candidate, that we've already seen
389 const byte *end_of_known_zeros = candidate;
390 while (end - candidate >= min_len) // Handle all min_len candidate blocks
392 const byte * const probe_end = candidate + min_len;
393 const byte * const trailing_zeros =
394 find_trailing_zeros(end_of_known_zeros, probe_end);
395 if (trailing_zeros == probe_end)
396 end_of_known_zeros = candidate = probe_end;
397 else if (trailing_zeros == end_of_known_zeros)
399 assert(candidate >= start);
400 assert(candidate <= end);
401 assert(*candidate == 0);
402 return (byte *) candidate;
406 candidate = trailing_zeros;
407 end_of_known_zeros = probe_end;
411 if (candidate == end)
414 // No min_len sparse run found, search backward from end
415 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
418 if (trailing_zeros == end_of_known_zeros)
420 assert(candidate >= start);
421 assert(candidate < end);
422 assert(*candidate == 0);
423 assert(end - candidate < min_len);
424 return (byte *) candidate;
427 if (trailing_zeros == end)
429 assert(*(end - 1) != 0);
433 assert(end - trailing_zeros < min_len);
434 assert(trailing_zeros >= start);
435 assert(trailing_zeros < end);
436 assert(*trailing_zeros == 0);
437 return (byte *) trailing_zeros;
441 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
444 unsigned char *buf = NULL;
446 PyObject *py_min_sparse_len, *py_prev_sparse_len;
447 if (!PyArg_ParseTuple(args, "it#OO",
448 &fd, &buf, &sbuf_len,
449 &py_min_sparse_len, &py_prev_sparse_len))
451 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
452 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
454 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
457 return PyErr_Format(PyExc_ValueError, "negative bufer length");
458 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
459 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
461 const byte * block = buf; // Start of pending block
462 const byte * const end = buf + buf_len;
463 unsigned long long zeros = prev_sparse_len;
466 assert(block <= end);
468 return PyLong_FromUnsignedLongLong(zeros);
472 // Look for the end of block, i.e. the next sparse run of
473 // at least min_sparse_len zeros, or the end of the
475 const byte * const probe = find_non_sparse_end(block + 1, end,
477 // Either at end of block, or end of non-sparse; write pending data
478 PyObject *err = append_sparse_region(fd, zeros);
481 int rc = write_all(fd, block, probe - block);
483 return PyErr_SetFromErrno(PyExc_IOError);
485 if (end - probe < min_sparse_len)
488 zeros = min_sparse_len;
489 block = probe + zeros;
493 // Should be in the first loop iteration, a sparse run of
494 // zeros, or nearly at the end of the block (within
496 const byte * const zeros_end = find_not_zero(block, end);
497 PyObject *err = record_sparse_zeros(&zeros, fd,
498 zeros, zeros_end - block);
501 assert(block <= zeros_end);
508 static PyObject *selftest(PyObject *self, PyObject *args)
510 if (!PyArg_ParseTuple(args, ""))
513 return Py_BuildValue("i", !bupsplit_selftest());
517 static PyObject *blobbits(PyObject *self, PyObject *args)
519 if (!PyArg_ParseTuple(args, ""))
521 return Py_BuildValue("i", BUP_BLOBBITS);
525 static PyObject *splitbuf(PyObject *self, PyObject *args)
527 unsigned char *buf = NULL;
529 int out = 0, bits = -1;
531 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
533 assert(len <= INT_MAX);
534 out = bupsplit_find_ofs(buf, len, &bits);
535 if (out) assert(bits >= BUP_BLOBBITS);
536 return Py_BuildValue("ii", out, bits);
540 static PyObject *bitmatch(PyObject *self, PyObject *args)
542 unsigned char *buf1 = NULL, *buf2 = NULL;
543 Py_ssize_t len1 = 0, len2 = 0;
547 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
551 for (byte = 0; byte < len1 && byte < len2; byte++)
553 int b1 = buf1[byte], b2 = buf2[byte];
556 for (bit = 0; bit < 8; bit++)
557 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
563 assert(byte <= (INT_MAX >> 3));
564 return Py_BuildValue("i", byte*8 + bit);
568 static PyObject *firstword(PyObject *self, PyObject *args)
570 unsigned char *buf = NULL;
574 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
580 v = ntohl(*(uint32_t *)buf);
581 return PyLong_FromUnsignedLong(v);
585 #define BLOOM2_HEADERLEN 16
587 static void to_bloom_address_bitmask4(const unsigned char *buf,
588 const int nbits, uint64_t *v, unsigned char *bitmask)
594 memcpy(&high, buf, 4);
595 mask = (1<<nbits) - 1;
596 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
597 bit = (raw >> (37-nbits)) & 0x7;
598 *v = (raw >> (40-nbits)) & mask;
602 static void to_bloom_address_bitmask5(const unsigned char *buf,
603 const int nbits, uint32_t *v, unsigned char *bitmask)
609 memcpy(&high, buf, 4);
610 mask = (1<<nbits) - 1;
612 bit = (raw >> (29-nbits)) & 0x7;
613 *v = (raw >> (32-nbits)) & mask;
617 #define BLOOM_SET_BIT(name, address, otype) \
618 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
620 unsigned char bitmask;\
622 address(buf, nbits, &v, &bitmask);\
623 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
625 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
626 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
629 #define BLOOM_GET_BIT(name, address, otype) \
630 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
632 unsigned char bitmask;\
634 address(buf, nbits, &v, &bitmask);\
635 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
637 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
638 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
641 static PyObject *bloom_add(PyObject *self, PyObject *args)
643 unsigned char *sha = NULL, *bloom = NULL;
645 Py_ssize_t len = 0, blen = 0;
646 int nbits = 0, k = 0;
648 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
651 if (blen < 16+(1<<nbits) || len % 20 != 0)
658 for (end = sha + len; sha < end; sha += 20/k)
659 bloom_set_bit5(bloom, sha, nbits);
665 for (end = sha + len; sha < end; sha += 20/k)
666 bloom_set_bit4(bloom, sha, nbits);
672 return Py_BuildValue("n", len/20);
675 static PyObject *bloom_contains(PyObject *self, PyObject *args)
677 unsigned char *sha = NULL, *bloom = NULL;
678 Py_ssize_t len = 0, blen = 0;
679 int nbits = 0, k = 0;
683 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
693 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
694 if (!bloom_get_bit5(bloom, sha, nbits))
695 return Py_BuildValue("Oi", Py_None, steps);
701 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
702 if (!bloom_get_bit4(bloom, sha, nbits))
703 return Py_BuildValue("Oi", Py_None, steps);
708 return Py_BuildValue("ii", 1, k);
712 static uint32_t _extract_bits(unsigned char *buf, int nbits)
716 mask = (1<<nbits) - 1;
717 v = ntohl(*(uint32_t *)buf);
718 v = (v >> (32-nbits)) & mask;
723 static PyObject *extract_bits(PyObject *self, PyObject *args)
725 unsigned char *buf = NULL;
729 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
735 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
740 unsigned char bytes[20];
754 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
757 for (i = 0; i < sizeof(struct sha); i++)
758 if (sha1->bytes[i] != sha2->bytes[i])
759 return sha1->bytes[i] - sha2->bytes[i];
764 static void _fix_idx_order(struct idx **idxs, int *last_i)
767 int low, mid, high, c = 0;
770 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
772 idxs[*last_i] = NULL;
785 mid = (low + high) / 2;
786 c = _cmp_sha(idx->cur, idxs[mid]->cur);
798 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
803 static uint32_t _get_idx_i(struct idx *idx)
805 if (idx->cur_name == NULL)
806 return idx->name_base;
807 return ntohl(*idx->cur_name) + idx->name_base;
810 #define MIDX4_HEADERLEN 12
812 static PyObject *merge_into(PyObject *self, PyObject *args)
814 PyObject *py_total, *ilist = NULL;
815 unsigned char *fmap = NULL;
816 struct sha *sha_ptr, *sha_start = NULL;
817 uint32_t *table_ptr, *name_ptr, *name_start;
818 struct idx **idxs = NULL;
822 uint32_t count, prefix;
826 if (!PyArg_ParseTuple(args, "w#iOO",
827 &fmap, &flen, &bits, &py_total, &ilist))
830 if (!bup_uint_from_py(&total, py_total, "total"))
833 num_i = PyList_Size(ilist);
834 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
836 for (i = 0; i < num_i; i++)
838 long len, sha_ofs, name_map_ofs;
839 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
840 PyObject *itup = PyList_GetItem(ilist, i);
841 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
842 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
844 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
845 idxs[i]->end = &idxs[i]->cur[len];
847 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
849 idxs[i]->cur_name = NULL;
851 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
852 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
853 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
862 if (count % 102424 == 0 && get_state(self)->istty2)
863 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
864 count*100.0/total, count, total);
866 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
867 while (prefix < new_prefix)
868 table_ptr[prefix++] = htonl(count);
869 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
870 *name_ptr++ = htonl(_get_idx_i(idx));
872 if (idx->cur_name != NULL)
874 _fix_idx_order(idxs, &last_i);
877 while (prefix < (1<<bits))
878 table_ptr[prefix++] = htonl(count);
879 assert(count == total);
880 assert(prefix == (1<<bits));
881 assert(sha_ptr == sha_start+count);
882 assert(name_ptr == name_start+count);
885 return PyLong_FromUnsignedLong(count);
888 #define FAN_ENTRIES 256
890 static PyObject *write_idx(PyObject *self, PyObject *args)
892 char *filename = NULL;
893 PyObject *py_total, *idx = NULL;
895 unsigned char *fmap = NULL;
897 unsigned int total = 0;
899 int i, j, ofs64_count;
900 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
904 if (!PyArg_ParseTuple(args, "sw#OO",
905 &filename, &fmap, &flen, &idx, &py_total))
908 if (!bup_uint_from_py(&total, py_total, "total"))
911 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
912 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
915 const char idx_header[] = "\377tOc\0\0\0\002";
916 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
918 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
919 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
920 crc_ptr = (uint32_t *)&sha_ptr[total];
921 ofs_ptr = (uint32_t *)&crc_ptr[total];
922 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
926 for (i = 0; i < FAN_ENTRIES; ++i)
929 part = PyList_GET_ITEM(idx, i);
931 plen = PyList_GET_SIZE(part);
933 *fan_ptr++ = htonl(count);
934 for (j = 0; j < plen; ++j)
936 unsigned char *sha = NULL;
937 Py_ssize_t sha_len = 0;
938 PyObject *crc_py, *ofs_py;
940 unsigned PY_LONG_LONG ofs_ull;
942 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
943 &sha, &sha_len, &crc_py, &ofs_py))
945 if(!bup_uint_from_py(&crc, crc_py, "crc"))
947 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
949 assert(crc <= UINT32_MAX);
950 assert(ofs_ull <= UINT64_MAX);
952 if (sha_len != sizeof(struct sha))
954 memcpy(sha_ptr++, sha, sizeof(struct sha));
955 *crc_ptr++ = htonl(crc);
956 if (ofs > 0x7fffffff)
958 *ofs64_ptr++ = htonll(ofs);
959 ofs = 0x80000000 | ofs64_count++;
961 *ofs_ptr++ = htonl((uint32_t)ofs);
965 int rc = msync(fmap, flen, MS_ASYNC);
967 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
969 return PyLong_FromUnsignedLong(count);
973 // I would have made this a lower-level function that just fills in a buffer
974 // with random values, and then written those values from python. But that's
975 // about 20% slower in my tests, and since we typically generate random
976 // numbers for benchmarking other parts of bup, any slowness in generating
977 // random bytes will make our benchmarks inaccurate. Plus nobody wants
978 // pseudorandom bytes much except for this anyway.
979 static PyObject *write_random(PyObject *self, PyObject *args)
981 uint32_t buf[1024/4];
982 int fd = -1, seed = 0, verbose = 0;
984 long long len = 0, kbytes = 0, written = 0;
986 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
991 for (kbytes = 0; kbytes < len/1024; kbytes++)
994 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
996 ret = write(fd, buf, sizeof(buf));
1000 if (ret < (int)sizeof(buf))
1002 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1003 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1006 // handle non-multiples of 1024
1010 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1012 ret = write(fd, buf, len % 1024);
1018 if (kbytes/1024 > 0)
1019 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1020 return Py_BuildValue("L", written);
1024 static PyObject *random_sha(PyObject *self, PyObject *args)
1026 static int seeded = 0;
1027 uint32_t shabuf[20/4];
1032 assert(sizeof(shabuf) == 20);
1033 srandom(time(NULL));
1037 if (!PyArg_ParseTuple(args, ""))
1040 memset(shabuf, 0, sizeof(shabuf));
1041 for (i=0; i < 20/4; i++)
1042 shabuf[i] = random();
1043 return Py_BuildValue("s#", shabuf, 20);
1047 static int _open_noatime(const char *filename, int attrs)
1049 int attrs_noatime, fd;
1052 attrs |= O_NOFOLLOW;
1055 attrs |= O_LARGEFILE;
1057 attrs_noatime = attrs;
1059 attrs_noatime |= O_NOATIME;
1061 fd = open(filename, attrs_noatime);
1062 if (fd < 0 && errno == EPERM)
1064 // older Linux kernels would return EPERM if you used O_NOATIME
1065 // and weren't the file's owner. This pointless restriction was
1066 // relaxed eventually, but we have to handle it anyway.
1067 // (VERY old kernels didn't recognized O_NOATIME, but they would
1068 // just harmlessly ignore it, so this branch won't trigger)
1069 fd = open(filename, attrs);
1075 static PyObject *open_noatime(PyObject *self, PyObject *args)
1077 char *filename = NULL;
1079 if (!PyArg_ParseTuple(args, "s", &filename))
1081 fd = _open_noatime(filename, 0);
1083 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1084 return Py_BuildValue("i", fd);
1088 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1091 long long llofs, lllen = 0;
1092 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1095 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1096 return PyErr_Format(PyExc_OverflowError,
1097 "fadvise offset overflows off_t");
1098 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1099 return PyErr_Format(PyExc_OverflowError,
1100 "fadvise length overflows off_t");
1101 #ifdef POSIX_FADV_DONTNEED
1102 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1104 return Py_BuildValue("");
1108 // Currently the Linux kernel and FUSE disagree over the type for
1109 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1110 // but FUSE chose long (matching the declaration in linux/fs.h). So
1111 // if you use int, and then traverse a FUSE filesystem, you may
1112 // corrupt the stack. But if you use long, then you may get invalid
1113 // results on big-endian systems.
1115 // For now, we just use long, and then disable Linux attrs entirely
1116 // (with a warning) in helpers.py on systems that are affected.
1118 #ifdef BUP_HAVE_FILE_ATTRS
1119 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1126 if (!PyArg_ParseTuple(args, "s", &path))
1129 fd = _open_noatime(path, O_NONBLOCK);
1131 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1133 attr = 0; // Handle int/long mismatch (see above)
1134 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1138 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1141 assert(attr <= UINT_MAX); // Kernel type is actually int
1142 return PyLong_FromUnsignedLong(attr);
1144 #endif /* def BUP_HAVE_FILE_ATTRS */
1148 #ifdef BUP_HAVE_FILE_ATTRS
1149 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1152 unsigned long orig_attr;
1158 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1161 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1164 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1166 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1168 // Restrict attr to modifiable flags acdeijstuADST -- see
1169 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1170 // in pf.c flags_array[].
1171 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1172 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1173 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1174 | FS_TOPDIR_FL | FS_NOCOW_FL;
1176 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1177 orig_attr = 0; // Handle int/long mismatch (see above)
1178 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1182 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1184 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1185 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1187 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1191 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1195 return Py_BuildValue("O", Py_None);
1197 #endif /* def BUP_HAVE_FILE_ATTRS */
1200 #ifndef HAVE_UTIMENSAT
1202 #error "cannot find utimensat or utimes()"
1204 #ifndef HAVE_LUTIMES
1205 #error "cannot find utimensat or lutimes()"
1209 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1213 const long long lltmp = PyLong_AsLongLong(pylong); \
1214 if (lltmp == -1 && PyErr_Occurred()) \
1216 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1218 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1219 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1221 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1227 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1235 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1244 #ifdef HAVE_UTIMENSAT
1246 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1251 PyObject *access_py, *modification_py;
1252 struct timespec ts[2];
1254 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1257 &access_py, &(ts[0].tv_nsec),
1258 &modification_py, &(ts[1].tv_nsec),
1263 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1266 PyErr_SetString(PyExc_ValueError,
1267 "unable to convert access time seconds for utimensat");
1270 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1273 PyErr_SetString(PyExc_ValueError,
1274 "unable to convert modification time seconds for utimensat");
1277 rc = utimensat(fd, path, ts, flag);
1279 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1281 return Py_BuildValue("O", Py_None);
1284 #endif /* def HAVE_UTIMENSAT */
1287 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1289 static int bup_parse_xutimes_args(char **path,
1290 struct timeval tv[2],
1293 PyObject *access_py, *modification_py;
1294 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1296 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1298 &access_py, &access_us,
1299 &modification_py, &modification_us))
1303 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1306 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1309 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1311 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1314 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1317 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1320 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1322 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1328 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1332 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1335 struct timeval tv[2];
1336 if (!bup_parse_xutimes_args(&path, tv, args))
1338 int rc = utimes(path, tv);
1340 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1341 return Py_BuildValue("O", Py_None);
1343 #endif /* def HAVE_UTIMES */
1347 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1350 struct timeval tv[2];
1351 if (!bup_parse_xutimes_args(&path, tv, args))
1353 int rc = lutimes(path, tv);
1355 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1357 return Py_BuildValue("O", Py_None);
1359 #endif /* def HAVE_LUTIMES */
1362 #ifdef HAVE_STAT_ST_ATIM
1363 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1364 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1365 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1366 #elif defined HAVE_STAT_ST_ATIMENSEC
1367 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1368 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1369 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1371 # define BUP_STAT_ATIME_NS(st) 0
1372 # define BUP_STAT_MTIME_NS(st) 0
1373 # define BUP_STAT_CTIME_NS(st) 0
1377 #pragma clang diagnostic push
1378 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1380 static PyObject *stat_struct_to_py(const struct stat *st,
1381 const char *filename,
1384 // We can check the known (via POSIX) signed and unsigned types at
1385 // compile time, but not (easily) the unspecified types, so handle
1386 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1388 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1389 INTEGER_TO_PY(st->st_mode),
1390 (unsigned PY_LONG_LONG) st->st_ino,
1391 INTEGER_TO_PY(st->st_dev),
1392 INTEGER_TO_PY(st->st_nlink),
1393 INTEGER_TO_PY(st->st_uid),
1394 INTEGER_TO_PY(st->st_gid),
1395 INTEGER_TO_PY(st->st_rdev),
1396 (PY_LONG_LONG) st->st_size,
1397 INTEGER_TO_PY(st->st_atime),
1398 (long) BUP_STAT_ATIME_NS(st),
1399 INTEGER_TO_PY(st->st_mtime),
1400 (long) BUP_STAT_MTIME_NS(st),
1401 INTEGER_TO_PY(st->st_ctime),
1402 (long) BUP_STAT_CTIME_NS(st));
1405 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1407 static PyObject *bup_stat(PyObject *self, PyObject *args)
1412 if (!PyArg_ParseTuple(args, "s", &filename))
1416 rc = stat(filename, &st);
1418 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1419 return stat_struct_to_py(&st, filename, 0);
1423 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1428 if (!PyArg_ParseTuple(args, "s", &filename))
1432 rc = lstat(filename, &st);
1434 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1435 return stat_struct_to_py(&st, filename, 0);
1439 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1443 if (!PyArg_ParseTuple(args, "i", &fd))
1447 rc = fstat(fd, &st);
1449 return PyErr_SetFromErrno(PyExc_OSError);
1450 return stat_struct_to_py(&st, NULL, fd);
1454 #ifdef HAVE_TM_TM_GMTOFF
1455 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1459 if (!PyArg_ParseTuple(args, "L", &lltime))
1461 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1462 return PyErr_Format(PyExc_OverflowError, "time value too large");
1466 if(localtime_r(&ttime, &tm) == NULL)
1467 return PyErr_SetFromErrno(PyExc_OSError);
1469 // Match the Python struct_time values.
1470 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1471 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1472 tm.tm_hour, tm.tm_min, tm.tm_sec,
1473 tm.tm_wday, tm.tm_yday + 1,
1474 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1476 #endif /* def HAVE_TM_TM_GMTOFF */
1479 #ifdef BUP_MINCORE_BUF_TYPE
1480 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1483 Py_ssize_t src_ssize;
1485 PyObject *py_src_n, *py_src_off, *py_dest_off;
1486 if (!PyArg_ParseTuple(args, "s#OOw*O",
1487 &src, &src_ssize, &py_src_n, &py_src_off,
1488 &dest, &py_dest_off))
1491 unsigned long long src_size, src_n, src_off, dest_size, dest_off;
1492 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1493 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1494 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1497 if (!INTEGRAL_ASSIGNMENT_FITS(&src_size, src_ssize))
1498 return PyErr_Format(PyExc_OverflowError, "invalid src size");
1499 unsigned long long src_region_end;
1501 if (!uadd(&src_region_end, src_off, src_n))
1502 return PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1503 if (src_region_end > src_size)
1504 return PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1506 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len))
1507 return PyErr_Format(PyExc_OverflowError, "invalid dest size");
1508 if (dest_off > dest_size)
1509 return PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1512 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n))
1513 return PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1514 int rc = mincore((void *)(src + src_off), src_n,
1515 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1517 return PyErr_SetFromErrno(PyExc_OSError);
1518 return Py_BuildValue("O", Py_None);
1520 #endif /* def BUP_MINCORE_BUF_TYPE */
1523 static PyMethodDef helper_methods[] = {
1524 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1525 "Write buf excepting zeros at the end. Return trailing zero count." },
1526 { "selftest", selftest, METH_VARARGS,
1527 "Check that the rolling checksum rolls correctly (for unit tests)." },
1528 { "blobbits", blobbits, METH_VARARGS,
1529 "Return the number of bits in the rolling checksum." },
1530 { "splitbuf", splitbuf, METH_VARARGS,
1531 "Split a list of strings based on a rolling checksum." },
1532 { "bitmatch", bitmatch, METH_VARARGS,
1533 "Count the number of matching prefix bits between two strings." },
1534 { "firstword", firstword, METH_VARARGS,
1535 "Return an int corresponding to the first 32 bits of buf." },
1536 { "bloom_contains", bloom_contains, METH_VARARGS,
1537 "Check if a bloom filter of 2^nbits bytes contains an object" },
1538 { "bloom_add", bloom_add, METH_VARARGS,
1539 "Add an object to a bloom filter of 2^nbits bytes" },
1540 { "extract_bits", extract_bits, METH_VARARGS,
1541 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1542 { "merge_into", merge_into, METH_VARARGS,
1543 "Merges a bunch of idx and midx files into a single midx." },
1544 { "write_idx", write_idx, METH_VARARGS,
1545 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1546 { "write_random", write_random, METH_VARARGS,
1547 "Write random bytes to the given file descriptor" },
1548 { "random_sha", random_sha, METH_VARARGS,
1549 "Return a random 20-byte string" },
1550 { "open_noatime", open_noatime, METH_VARARGS,
1551 "open() the given filename for read with O_NOATIME if possible" },
1552 { "fadvise_done", fadvise_done, METH_VARARGS,
1553 "Inform the kernel that we're finished with earlier parts of a file" },
1554 #ifdef BUP_HAVE_FILE_ATTRS
1555 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1556 "Return the Linux attributes for the given file." },
1558 #ifdef BUP_HAVE_FILE_ATTRS
1559 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1560 "Set the Linux attributes for the given file." },
1562 #ifdef HAVE_UTIMENSAT
1563 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1564 "Change path timestamps with nanosecond precision (POSIX)." },
1567 { "bup_utimes", bup_utimes, METH_VARARGS,
1568 "Change path timestamps with microsecond precision." },
1571 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1572 "Change path timestamps with microsecond precision;"
1573 " don't follow symlinks." },
1575 { "stat", bup_stat, METH_VARARGS,
1576 "Extended version of stat." },
1577 { "lstat", bup_lstat, METH_VARARGS,
1578 "Extended version of lstat." },
1579 { "fstat", bup_fstat, METH_VARARGS,
1580 "Extended version of fstat." },
1581 #ifdef HAVE_TM_TM_GMTOFF
1582 { "localtime", bup_localtime, METH_VARARGS,
1583 "Return struct_time elements plus the timezone offset and name." },
1585 { "bytescmp", bup_bytescmp, METH_VARARGS,
1586 "Return a negative value if x < y, zero if equal, positive otherwise."},
1587 #ifdef BUP_MINCORE_BUF_TYPE
1588 { "mincore", bup_mincore, METH_VARARGS,
1589 "For mincore(src, src_n, src_off, dest, dest_off)"
1590 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1592 { NULL, NULL, 0, NULL }, // sentinel
1595 static int setup_module(PyObject *m)
1597 // FIXME: migrate these tests to configure, or at least don't
1598 // possibly crash the whole application. Check against the type
1599 // we're going to use when passing to python. Other stat types
1600 // are tested at runtime.
1601 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1602 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1603 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1604 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1605 // Just be sure (relevant when passing timestamps back to Python above).
1606 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1607 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1609 // Originally required by append_sparse_region()
1612 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1614 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1620 #pragma clang diagnostic push
1621 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1624 value = INTEGER_TO_PY(INT_MAX);
1625 PyObject_SetAttrString(m, "INT_MAX", value);
1627 value = INTEGER_TO_PY(UINT_MAX);
1628 PyObject_SetAttrString(m, "UINT_MAX", value);
1631 #ifdef HAVE_UTIMENSAT
1634 value = INTEGER_TO_PY(AT_FDCWD);
1635 PyObject_SetAttrString(m, "AT_FDCWD", value);
1637 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1638 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1640 value = INTEGER_TO_PY(UTIME_NOW);
1641 PyObject_SetAttrString(m, "UTIME_NOW", value);
1645 #ifdef BUP_HAVE_MINCORE_INCORE
1648 value = INTEGER_TO_PY(MINCORE_INCORE);
1649 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1653 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1655 e = getenv("BUP_FORCE_TTY");
1656 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1662 #if PY_MAJOR_VERSION < 3
1664 PyMODINIT_FUNC init_helpers(void)
1666 PyObject *m = Py_InitModule("_helpers", helper_methods);
1670 if (!setup_module(m))
1677 # else // PY_MAJOR_VERSION >= 3
1679 static struct PyModuleDef helpers_def = {
1680 PyModuleDef_HEAD_INIT,
1686 NULL, // helpers_traverse,
1687 NULL, // helpers_clear,
1691 PyMODINIT_FUNC PyInit__helpers(void)
1693 PyObject *module = PyModule_Create(&helpers_def);
1696 if (!setup_module(module))
1704 #endif // PY_MAJOR_VERSION >= 3