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
32 #ifdef HAVE_SYS_TIME_H
36 #ifdef HAVE_LINUX_FS_H
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
43 #ifdef HAVE_TM_TM_GMTOFF
49 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
50 #define BUP_HAVE_FILE_ATTRS 1
54 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
55 * pretend we don't have it.
57 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
62 // Of course, this assumes it's a bitfield value.
67 typedef unsigned char byte;
74 #if PY_MAJOR_VERSION < 3
76 # define get_state(x) (&state)
77 # define cstr_argf "s"
79 # define get_state(x) ((state_t *) PyModule_GetState(x))
80 # define cstr_argf "y"
81 #endif // PY_MAJOR_VERSION >= 3
85 // This function should technically be macro'd out if it's going to be used
86 // more than ocasionally. As of this writing, it'll actually never be called
87 // in real world bup scenarios (because our packs are < MAX_INT bytes).
88 static uint64_t htonll(uint64_t value)
90 static const int endian_test = 42;
92 if (*(char *)&endian_test == endian_test) // LSB-MSB
93 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
94 return value; // already in network byte order MSB-LSB
99 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
102 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
106 // At the moment any code that calls INTGER_TO_PY() will have to
107 // disable -Wtautological-compare for clang. See below.
109 #define INTEGER_TO_PY(x) \
110 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
114 #if PY_MAJOR_VERSION < 3
115 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
118 const long tmp = PyInt_AsLong(py);
119 if (tmp == -1 && PyErr_Occurred())
121 if (PyErr_ExceptionMatches(PyExc_OverflowError))
122 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
128 PyErr_Format(PyExc_OverflowError,
129 "negative %s cannot be converted to unsigned long", name);
138 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
140 #if PY_MAJOR_VERSION < 3
142 return bup_ulong_from_pyint(x, py, name);
145 if (!PyLong_Check(py))
147 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
151 const unsigned long tmp = PyLong_AsUnsignedLong(py);
152 if (PyErr_Occurred())
154 if (PyErr_ExceptionMatches(PyExc_OverflowError))
155 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
164 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
167 if (!bup_ulong_from_py(&tmp, py, name))
172 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
179 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
182 #if PY_MAJOR_VERSION < 3
186 if (bup_ulong_from_pyint(&tmp, py, name))
195 if (!PyLong_Check(py))
197 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
201 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
202 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
204 if (PyErr_ExceptionMatches(PyExc_OverflowError))
205 PyErr_Format(PyExc_OverflowError,
206 "%s too big for unsigned long long", name);
214 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
216 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
217 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
220 Py_ssize_t s1_len, s2_len;
221 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
223 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
225 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
226 const int cmp = memcmp(s1, s2, n);
228 return PyLong_FromLong(cmp);
229 if (s1_len == s2_len)
230 return PyLong_FromLong(0);;
231 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
235 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
236 #if __WIN32__ || __CYGWIN__
238 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
239 static void unpythonize_argv(void) { }
241 #else // not __WIN32__
243 // For some reason this isn't declared in Python.h
244 extern void Py_GetArgcArgv(int *argc, char ***argv);
246 static void unpythonize_argv(void)
251 Py_GetArgcArgv(&argc, &argv);
253 for (i = 0; i < argc-1; i++)
255 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
257 // The argv block doesn't work the way we expected; it's unsafe
263 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
265 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
269 p = strrchr(argv[1], '/');
275 memmove(argv[0], p, len);
276 memset(arge - diff, 0, diff);
277 for (i = 0; i < argc; i++)
278 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
283 #endif // not __WIN32__ or __CYGWIN__
286 static int write_all(int fd, const void *buf, const size_t count)
289 while (written < count)
291 const ssize_t rc = write(fd, buf + written, count - written);
300 static int uadd(unsigned long long *dest,
301 const unsigned long long x,
302 const unsigned long long y)
304 const unsigned long long result = x + y;
305 if (result < x || result < y)
312 static PyObject *append_sparse_region(const int fd, unsigned long long n)
317 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
319 const off_t off = lseek(fd, new_off, SEEK_CUR);
320 if (off == (off_t) -1)
321 return PyErr_SetFromErrno(PyExc_IOError);
328 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
330 unsigned long long prev_pending,
331 const unsigned long long count)
333 // Add count additional sparse zeros to prev_pending and store the
334 // result in new_pending, or if the total won't fit in
335 // new_pending, write some of the zeros to fd sparsely, and store
336 // the remaining sum in new_pending.
337 if (!uadd(new_pending, prev_pending, count))
339 PyObject *err = append_sparse_region(fd, prev_pending);
342 *new_pending = count;
348 static byte* find_not_zero(const byte * const start, const byte * const end)
350 // Return a pointer to first non-zero byte between start and end,
351 // or end if there isn't one.
352 assert(start <= end);
353 const unsigned char *cur = start;
354 while (cur < end && *cur == 0)
360 static byte* find_trailing_zeros(const byte * const start,
361 const byte * const end)
363 // Return a pointer to the start of any trailing run of zeros, or
364 // end if there isn't one.
365 assert(start <= end);
368 const byte * cur = end;
369 while (cur > start && *--cur == 0) {}
373 return (byte *) (cur + 1);
377 static byte *find_non_sparse_end(const byte * const start,
378 const byte * const end,
379 const unsigned long long min_len)
381 // Return the first pointer to a min_len sparse block in [start,
382 // end) if there is one, otherwise a pointer to the start of any
383 // trailing run of zeros. If there are no trailing zeros, return
389 // Probe in min_len jumps, searching backward from the jump
390 // destination for a non-zero byte. If such a byte is found, move
391 // just past it and try again.
392 const byte *candidate = start;
393 // End of any run of zeros, starting at candidate, that we've already seen
394 const byte *end_of_known_zeros = candidate;
395 while (end - candidate >= min_len) // Handle all min_len candidate blocks
397 const byte * const probe_end = candidate + min_len;
398 const byte * const trailing_zeros =
399 find_trailing_zeros(end_of_known_zeros, probe_end);
400 if (trailing_zeros == probe_end)
401 end_of_known_zeros = candidate = probe_end;
402 else if (trailing_zeros == end_of_known_zeros)
404 assert(candidate >= start);
405 assert(candidate <= end);
406 assert(*candidate == 0);
407 return (byte *) candidate;
411 candidate = trailing_zeros;
412 end_of_known_zeros = probe_end;
416 if (candidate == end)
419 // No min_len sparse run found, search backward from end
420 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
423 if (trailing_zeros == end_of_known_zeros)
425 assert(candidate >= start);
426 assert(candidate < end);
427 assert(*candidate == 0);
428 assert(end - candidate < min_len);
429 return (byte *) candidate;
432 if (trailing_zeros == end)
434 assert(*(end - 1) != 0);
438 assert(end - trailing_zeros < min_len);
439 assert(trailing_zeros >= start);
440 assert(trailing_zeros < end);
441 assert(*trailing_zeros == 0);
442 return (byte *) trailing_zeros;
446 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
449 unsigned char *buf = NULL;
451 PyObject *py_min_sparse_len, *py_prev_sparse_len;
452 if (!PyArg_ParseTuple(args, "it#OO",
453 &fd, &buf, &sbuf_len,
454 &py_min_sparse_len, &py_prev_sparse_len))
456 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
457 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
459 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
462 return PyErr_Format(PyExc_ValueError, "negative bufer length");
463 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
464 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
466 const byte * block = buf; // Start of pending block
467 const byte * const end = buf + buf_len;
468 unsigned long long zeros = prev_sparse_len;
471 assert(block <= end);
473 return PyLong_FromUnsignedLongLong(zeros);
477 // Look for the end of block, i.e. the next sparse run of
478 // at least min_sparse_len zeros, or the end of the
480 const byte * const probe = find_non_sparse_end(block + 1, end,
482 // Either at end of block, or end of non-sparse; write pending data
483 PyObject *err = append_sparse_region(fd, zeros);
486 int rc = write_all(fd, block, probe - block);
488 return PyErr_SetFromErrno(PyExc_IOError);
490 if (end - probe < min_sparse_len)
493 zeros = min_sparse_len;
494 block = probe + zeros;
498 // Should be in the first loop iteration, a sparse run of
499 // zeros, or nearly at the end of the block (within
501 const byte * const zeros_end = find_not_zero(block, end);
502 PyObject *err = record_sparse_zeros(&zeros, fd,
503 zeros, zeros_end - block);
506 assert(block <= zeros_end);
513 static PyObject *selftest(PyObject *self, PyObject *args)
515 if (!PyArg_ParseTuple(args, ""))
518 return Py_BuildValue("i", !bupsplit_selftest());
522 static PyObject *blobbits(PyObject *self, PyObject *args)
524 if (!PyArg_ParseTuple(args, ""))
526 return Py_BuildValue("i", BUP_BLOBBITS);
530 static PyObject *splitbuf(PyObject *self, PyObject *args)
532 // We stick to buffers in python 2 because they appear to be
533 // substantially smaller than memoryviews, and because
534 // zlib.compress() in python 2 can't accept a memoryview
535 // (cf. hashsplit.py).
536 int out = 0, bits = -1;
537 if (PY_MAJOR_VERSION > 2)
540 if (!PyArg_ParseTuple(args, "y*", &buf))
542 assert(buf.len <= INT_MAX);
543 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
544 PyBuffer_Release(&buf);
548 unsigned char *buf = NULL;
550 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
552 assert(len <= INT_MAX);
553 out = bupsplit_find_ofs(buf, len, &bits);
555 if (out) assert(bits >= BUP_BLOBBITS);
556 return Py_BuildValue("ii", out, bits);
560 static PyObject *bitmatch(PyObject *self, PyObject *args)
562 unsigned char *buf1 = NULL, *buf2 = NULL;
563 Py_ssize_t len1 = 0, len2 = 0;
567 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
571 for (byte = 0; byte < len1 && byte < len2; byte++)
573 int b1 = buf1[byte], b2 = buf2[byte];
576 for (bit = 0; bit < 8; bit++)
577 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
583 assert(byte <= (INT_MAX >> 3));
584 return Py_BuildValue("i", byte*8 + bit);
588 static PyObject *firstword(PyObject *self, PyObject *args)
590 unsigned char *buf = NULL;
594 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
600 v = ntohl(*(uint32_t *)buf);
601 return PyLong_FromUnsignedLong(v);
605 #define BLOOM2_HEADERLEN 16
607 static void to_bloom_address_bitmask4(const unsigned char *buf,
608 const int nbits, uint64_t *v, unsigned char *bitmask)
614 memcpy(&high, buf, 4);
615 mask = (1<<nbits) - 1;
616 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
617 bit = (raw >> (37-nbits)) & 0x7;
618 *v = (raw >> (40-nbits)) & mask;
622 static void to_bloom_address_bitmask5(const unsigned char *buf,
623 const int nbits, uint32_t *v, unsigned char *bitmask)
629 memcpy(&high, buf, 4);
630 mask = (1<<nbits) - 1;
632 bit = (raw >> (29-nbits)) & 0x7;
633 *v = (raw >> (32-nbits)) & mask;
637 #define BLOOM_SET_BIT(name, address, otype) \
638 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
640 unsigned char bitmask;\
642 address(buf, nbits, &v, &bitmask);\
643 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
645 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
646 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
649 #define BLOOM_GET_BIT(name, address, otype) \
650 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
652 unsigned char bitmask;\
654 address(buf, nbits, &v, &bitmask);\
655 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
657 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
658 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
661 static PyObject *bloom_add(PyObject *self, PyObject *args)
663 unsigned char *sha = NULL, *bloom = NULL;
665 Py_ssize_t len = 0, blen = 0;
666 int nbits = 0, k = 0;
668 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
671 if (blen < 16+(1<<nbits) || len % 20 != 0)
678 for (end = sha + len; sha < end; sha += 20/k)
679 bloom_set_bit5(bloom, sha, nbits);
685 for (end = sha + len; sha < end; sha += 20/k)
686 bloom_set_bit4(bloom, sha, nbits);
692 return Py_BuildValue("n", len/20);
695 static PyObject *bloom_contains(PyObject *self, PyObject *args)
697 unsigned char *sha = NULL, *bloom = NULL;
698 Py_ssize_t len = 0, blen = 0;
699 int nbits = 0, k = 0;
703 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
713 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
714 if (!bloom_get_bit5(bloom, sha, nbits))
715 return Py_BuildValue("Oi", Py_None, steps);
721 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
722 if (!bloom_get_bit4(bloom, sha, nbits))
723 return Py_BuildValue("Oi", Py_None, steps);
728 return Py_BuildValue("ii", 1, k);
732 static uint32_t _extract_bits(unsigned char *buf, int nbits)
736 mask = (1<<nbits) - 1;
737 v = ntohl(*(uint32_t *)buf);
738 v = (v >> (32-nbits)) & mask;
743 static PyObject *extract_bits(PyObject *self, PyObject *args)
745 unsigned char *buf = NULL;
749 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
755 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
760 unsigned char bytes[20];
763 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
765 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
778 static void _fix_idx_order(struct idx **idxs, int *last_i)
781 int low, mid, high, c = 0;
784 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
786 idxs[*last_i] = NULL;
799 mid = (low + high) / 2;
800 c = _cmp_sha(idx->cur, idxs[mid]->cur);
812 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
817 static uint32_t _get_idx_i(struct idx *idx)
819 if (idx->cur_name == NULL)
820 return idx->name_base;
821 return ntohl(*idx->cur_name) + idx->name_base;
824 #define MIDX4_HEADERLEN 12
826 static PyObject *merge_into(PyObject *self, PyObject *args)
828 PyObject *py_total, *ilist = NULL;
829 unsigned char *fmap = NULL;
830 struct sha *sha_ptr, *sha_start = NULL;
831 uint32_t *table_ptr, *name_ptr, *name_start;
832 struct idx **idxs = NULL;
836 uint32_t count, prefix;
840 if (!PyArg_ParseTuple(args, "w#iOO",
841 &fmap, &flen, &bits, &py_total, &ilist))
844 if (!bup_uint_from_py(&total, py_total, "total"))
847 num_i = PyList_Size(ilist);
848 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
850 for (i = 0; i < num_i; i++)
852 long len, sha_ofs, name_map_ofs;
853 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
854 PyObject *itup = PyList_GetItem(ilist, i);
855 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
856 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
858 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
859 idxs[i]->end = &idxs[i]->cur[len];
861 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
863 idxs[i]->cur_name = NULL;
865 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
866 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
867 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
876 if (count % 102424 == 0 && get_state(self)->istty2)
877 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
878 count*100.0/total, count, total);
880 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
881 while (prefix < new_prefix)
882 table_ptr[prefix++] = htonl(count);
883 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
884 *name_ptr++ = htonl(_get_idx_i(idx));
886 if (idx->cur_name != NULL)
888 _fix_idx_order(idxs, &last_i);
891 while (prefix < (1<<bits))
892 table_ptr[prefix++] = htonl(count);
893 assert(count == total);
894 assert(prefix == (1<<bits));
895 assert(sha_ptr == sha_start+count);
896 assert(name_ptr == name_start+count);
899 return PyLong_FromUnsignedLong(count);
902 #define FAN_ENTRIES 256
904 static PyObject *write_idx(PyObject *self, PyObject *args)
906 char *filename = NULL;
907 PyObject *py_total, *idx = NULL;
909 unsigned char *fmap = NULL;
911 unsigned int total = 0;
913 int i, j, ofs64_count;
914 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
918 if (!PyArg_ParseTuple(args, "sw#OO",
919 &filename, &fmap, &flen, &idx, &py_total))
922 if (!bup_uint_from_py(&total, py_total, "total"))
925 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
926 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
929 const char idx_header[] = "\377tOc\0\0\0\002";
930 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
932 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
933 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
934 crc_ptr = (uint32_t *)&sha_ptr[total];
935 ofs_ptr = (uint32_t *)&crc_ptr[total];
936 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
940 for (i = 0; i < FAN_ENTRIES; ++i)
943 part = PyList_GET_ITEM(idx, i);
945 plen = PyList_GET_SIZE(part);
947 *fan_ptr++ = htonl(count);
948 for (j = 0; j < plen; ++j)
950 unsigned char *sha = NULL;
951 Py_ssize_t sha_len = 0;
952 PyObject *crc_py, *ofs_py;
954 unsigned PY_LONG_LONG ofs_ull;
956 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
957 &sha, &sha_len, &crc_py, &ofs_py))
959 if(!bup_uint_from_py(&crc, crc_py, "crc"))
961 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
963 assert(crc <= UINT32_MAX);
964 assert(ofs_ull <= UINT64_MAX);
966 if (sha_len != sizeof(struct sha))
968 memcpy(sha_ptr++, sha, sizeof(struct sha));
969 *crc_ptr++ = htonl(crc);
970 if (ofs > 0x7fffffff)
972 *ofs64_ptr++ = htonll(ofs);
973 ofs = 0x80000000 | ofs64_count++;
975 *ofs_ptr++ = htonl((uint32_t)ofs);
979 int rc = msync(fmap, flen, MS_ASYNC);
981 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
983 return PyLong_FromUnsignedLong(count);
987 // I would have made this a lower-level function that just fills in a buffer
988 // with random values, and then written those values from python. But that's
989 // about 20% slower in my tests, and since we typically generate random
990 // numbers for benchmarking other parts of bup, any slowness in generating
991 // random bytes will make our benchmarks inaccurate. Plus nobody wants
992 // pseudorandom bytes much except for this anyway.
993 static PyObject *write_random(PyObject *self, PyObject *args)
995 uint32_t buf[1024/4];
996 int fd = -1, seed = 0, verbose = 0;
998 long long len = 0, kbytes = 0, written = 0;
1000 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1005 for (kbytes = 0; kbytes < len/1024; kbytes++)
1008 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1010 ret = write(fd, buf, sizeof(buf));
1014 if (ret < (int)sizeof(buf))
1016 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1017 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1020 // handle non-multiples of 1024
1024 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1026 ret = write(fd, buf, len % 1024);
1032 if (kbytes/1024 > 0)
1033 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1034 return Py_BuildValue("L", written);
1038 static PyObject *random_sha(PyObject *self, PyObject *args)
1040 static int seeded = 0;
1041 uint32_t shabuf[20/4];
1046 assert(sizeof(shabuf) == 20);
1047 srandom(time(NULL));
1051 if (!PyArg_ParseTuple(args, ""))
1054 memset(shabuf, 0, sizeof(shabuf));
1055 for (i=0; i < 20/4; i++)
1056 shabuf[i] = random();
1057 return Py_BuildValue("s#", shabuf, 20);
1061 static int _open_noatime(const char *filename, int attrs)
1063 int attrs_noatime, fd;
1066 attrs |= O_NOFOLLOW;
1069 attrs |= O_LARGEFILE;
1071 attrs_noatime = attrs;
1073 attrs_noatime |= O_NOATIME;
1075 fd = open(filename, attrs_noatime);
1076 if (fd < 0 && errno == EPERM)
1078 // older Linux kernels would return EPERM if you used O_NOATIME
1079 // and weren't the file's owner. This pointless restriction was
1080 // relaxed eventually, but we have to handle it anyway.
1081 // (VERY old kernels didn't recognized O_NOATIME, but they would
1082 // just harmlessly ignore it, so this branch won't trigger)
1083 fd = open(filename, attrs);
1089 static PyObject *open_noatime(PyObject *self, PyObject *args)
1091 char *filename = NULL;
1093 if (!PyArg_ParseTuple(args, "s", &filename))
1095 fd = _open_noatime(filename, 0);
1097 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1098 return Py_BuildValue("i", fd);
1102 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1105 long long llofs, lllen = 0;
1106 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1109 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1110 return PyErr_Format(PyExc_OverflowError,
1111 "fadvise offset overflows off_t");
1112 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1113 return PyErr_Format(PyExc_OverflowError,
1114 "fadvise length overflows off_t");
1115 #ifdef POSIX_FADV_DONTNEED
1116 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1118 return Py_BuildValue("");
1122 // Currently the Linux kernel and FUSE disagree over the type for
1123 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1124 // but FUSE chose long (matching the declaration in linux/fs.h). So
1125 // if you use int, and then traverse a FUSE filesystem, you may
1126 // corrupt the stack. But if you use long, then you may get invalid
1127 // results on big-endian systems.
1129 // For now, we just use long, and then disable Linux attrs entirely
1130 // (with a warning) in helpers.py on systems that are affected.
1132 #ifdef BUP_HAVE_FILE_ATTRS
1133 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1140 if (!PyArg_ParseTuple(args, "s", &path))
1143 fd = _open_noatime(path, O_NONBLOCK);
1145 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1147 attr = 0; // Handle int/long mismatch (see above)
1148 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1152 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1155 assert(attr <= UINT_MAX); // Kernel type is actually int
1156 return PyLong_FromUnsignedLong(attr);
1158 #endif /* def BUP_HAVE_FILE_ATTRS */
1162 #ifdef BUP_HAVE_FILE_ATTRS
1163 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1166 unsigned long orig_attr;
1172 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1175 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1178 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1180 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1182 // Restrict attr to modifiable flags acdeijstuADST -- see
1183 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1184 // in pf.c flags_array[].
1185 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1186 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1187 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1188 | FS_TOPDIR_FL | FS_NOCOW_FL;
1190 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1191 orig_attr = 0; // Handle int/long mismatch (see above)
1192 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1196 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1198 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1199 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1201 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1205 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1209 return Py_BuildValue("O", Py_None);
1211 #endif /* def BUP_HAVE_FILE_ATTRS */
1214 #ifndef HAVE_UTIMENSAT
1216 #error "cannot find utimensat or utimes()"
1218 #ifndef HAVE_LUTIMES
1219 #error "cannot find utimensat or lutimes()"
1223 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1227 const long long lltmp = PyLong_AsLongLong(pylong); \
1228 if (lltmp == -1 && PyErr_Occurred()) \
1230 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1232 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1233 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1235 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1241 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1249 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1258 #ifdef HAVE_UTIMENSAT
1260 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1265 PyObject *access_py, *modification_py;
1266 struct timespec ts[2];
1268 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1271 &access_py, &(ts[0].tv_nsec),
1272 &modification_py, &(ts[1].tv_nsec),
1277 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1280 PyErr_SetString(PyExc_ValueError,
1281 "unable to convert access time seconds for utimensat");
1284 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1287 PyErr_SetString(PyExc_ValueError,
1288 "unable to convert modification time seconds for utimensat");
1291 rc = utimensat(fd, path, ts, flag);
1293 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1295 return Py_BuildValue("O", Py_None);
1298 #endif /* def HAVE_UTIMENSAT */
1301 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1303 static int bup_parse_xutimes_args(char **path,
1304 struct timeval tv[2],
1307 PyObject *access_py, *modification_py;
1308 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1310 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1312 &access_py, &access_us,
1313 &modification_py, &modification_us))
1317 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1320 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1323 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1325 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1328 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1331 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1334 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1336 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1342 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1346 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1349 struct timeval tv[2];
1350 if (!bup_parse_xutimes_args(&path, tv, args))
1352 int rc = utimes(path, tv);
1354 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1355 return Py_BuildValue("O", Py_None);
1357 #endif /* def HAVE_UTIMES */
1361 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1364 struct timeval tv[2];
1365 if (!bup_parse_xutimes_args(&path, tv, args))
1367 int rc = lutimes(path, tv);
1369 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1371 return Py_BuildValue("O", Py_None);
1373 #endif /* def HAVE_LUTIMES */
1376 #ifdef HAVE_STAT_ST_ATIM
1377 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1378 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1379 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1380 #elif defined HAVE_STAT_ST_ATIMENSEC
1381 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1382 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1383 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1385 # define BUP_STAT_ATIME_NS(st) 0
1386 # define BUP_STAT_MTIME_NS(st) 0
1387 # define BUP_STAT_CTIME_NS(st) 0
1391 #pragma clang diagnostic push
1392 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1394 static PyObject *stat_struct_to_py(const struct stat *st,
1395 const char *filename,
1398 // We can check the known (via POSIX) signed and unsigned types at
1399 // compile time, but not (easily) the unspecified types, so handle
1400 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1402 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1403 INTEGER_TO_PY(st->st_mode),
1404 (unsigned PY_LONG_LONG) st->st_ino,
1405 INTEGER_TO_PY(st->st_dev),
1406 INTEGER_TO_PY(st->st_nlink),
1407 INTEGER_TO_PY(st->st_uid),
1408 INTEGER_TO_PY(st->st_gid),
1409 INTEGER_TO_PY(st->st_rdev),
1410 (PY_LONG_LONG) st->st_size,
1411 INTEGER_TO_PY(st->st_atime),
1412 (long) BUP_STAT_ATIME_NS(st),
1413 INTEGER_TO_PY(st->st_mtime),
1414 (long) BUP_STAT_MTIME_NS(st),
1415 INTEGER_TO_PY(st->st_ctime),
1416 (long) BUP_STAT_CTIME_NS(st));
1419 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1421 static PyObject *bup_stat(PyObject *self, PyObject *args)
1426 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1430 rc = stat(filename, &st);
1432 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1433 return stat_struct_to_py(&st, filename, 0);
1437 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1442 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1446 rc = lstat(filename, &st);
1448 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1449 return stat_struct_to_py(&st, filename, 0);
1453 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1457 if (!PyArg_ParseTuple(args, "i", &fd))
1461 rc = fstat(fd, &st);
1463 return PyErr_SetFromErrno(PyExc_OSError);
1464 return stat_struct_to_py(&st, NULL, fd);
1468 #ifdef HAVE_TM_TM_GMTOFF
1469 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1473 if (!PyArg_ParseTuple(args, "L", &lltime))
1475 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1476 return PyErr_Format(PyExc_OverflowError, "time value too large");
1480 if(localtime_r(&ttime, &tm) == NULL)
1481 return PyErr_SetFromErrno(PyExc_OSError);
1483 // Match the Python struct_time values.
1484 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1485 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1486 tm.tm_hour, tm.tm_min, tm.tm_sec,
1487 tm.tm_wday, tm.tm_yday + 1,
1488 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1490 #endif /* def HAVE_TM_TM_GMTOFF */
1493 #ifdef BUP_MINCORE_BUF_TYPE
1494 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1496 Py_buffer src, dest;
1497 PyObject *py_src_n, *py_src_off, *py_dest_off;
1499 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1500 &src, &py_src_n, &py_src_off,
1501 &dest, &py_dest_off))
1504 PyObject *result = NULL;
1506 unsigned long long src_n, src_off, dest_off;
1507 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1508 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1509 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1510 goto clean_and_return;
1512 unsigned long long src_region_end;
1513 if (!uadd(&src_region_end, src_off, src_n)) {
1514 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1515 goto clean_and_return;
1517 if (src_region_end > src.len) {
1518 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1519 goto clean_and_return;
1522 unsigned long long dest_size;
1523 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1524 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1525 goto clean_and_return;
1527 if (dest_off > dest_size) {
1528 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1529 goto clean_and_return;
1533 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1534 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1535 goto clean_and_return;
1537 int rc = mincore((void *)(src.buf + src_off), src_n,
1538 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1540 result = PyErr_SetFromErrno(PyExc_OSError);
1541 goto clean_and_return;
1543 result = Py_BuildValue("O", Py_None);
1546 PyBuffer_Release(&src);
1547 PyBuffer_Release(&dest);
1550 #endif /* def BUP_MINCORE_BUF_TYPE */
1553 static PyMethodDef helper_methods[] = {
1554 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1555 "Write buf excepting zeros at the end. Return trailing zero count." },
1556 { "selftest", selftest, METH_VARARGS,
1557 "Check that the rolling checksum rolls correctly (for unit tests)." },
1558 { "blobbits", blobbits, METH_VARARGS,
1559 "Return the number of bits in the rolling checksum." },
1560 { "splitbuf", splitbuf, METH_VARARGS,
1561 "Split a list of strings based on a rolling checksum." },
1562 { "bitmatch", bitmatch, METH_VARARGS,
1563 "Count the number of matching prefix bits between two strings." },
1564 { "firstword", firstword, METH_VARARGS,
1565 "Return an int corresponding to the first 32 bits of buf." },
1566 { "bloom_contains", bloom_contains, METH_VARARGS,
1567 "Check if a bloom filter of 2^nbits bytes contains an object" },
1568 { "bloom_add", bloom_add, METH_VARARGS,
1569 "Add an object to a bloom filter of 2^nbits bytes" },
1570 { "extract_bits", extract_bits, METH_VARARGS,
1571 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1572 { "merge_into", merge_into, METH_VARARGS,
1573 "Merges a bunch of idx and midx files into a single midx." },
1574 { "write_idx", write_idx, METH_VARARGS,
1575 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1576 { "write_random", write_random, METH_VARARGS,
1577 "Write random bytes to the given file descriptor" },
1578 { "random_sha", random_sha, METH_VARARGS,
1579 "Return a random 20-byte string" },
1580 { "open_noatime", open_noatime, METH_VARARGS,
1581 "open() the given filename for read with O_NOATIME if possible" },
1582 { "fadvise_done", fadvise_done, METH_VARARGS,
1583 "Inform the kernel that we're finished with earlier parts of a file" },
1584 #ifdef BUP_HAVE_FILE_ATTRS
1585 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1586 "Return the Linux attributes for the given file." },
1588 #ifdef BUP_HAVE_FILE_ATTRS
1589 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1590 "Set the Linux attributes for the given file." },
1592 #ifdef HAVE_UTIMENSAT
1593 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1594 "Change path timestamps with nanosecond precision (POSIX)." },
1597 { "bup_utimes", bup_utimes, METH_VARARGS,
1598 "Change path timestamps with microsecond precision." },
1601 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1602 "Change path timestamps with microsecond precision;"
1603 " don't follow symlinks." },
1605 { "stat", bup_stat, METH_VARARGS,
1606 "Extended version of stat." },
1607 { "lstat", bup_lstat, METH_VARARGS,
1608 "Extended version of lstat." },
1609 { "fstat", bup_fstat, METH_VARARGS,
1610 "Extended version of fstat." },
1611 #ifdef HAVE_TM_TM_GMTOFF
1612 { "localtime", bup_localtime, METH_VARARGS,
1613 "Return struct_time elements plus the timezone offset and name." },
1615 { "bytescmp", bup_bytescmp, METH_VARARGS,
1616 "Return a negative value if x < y, zero if equal, positive otherwise."},
1617 #ifdef BUP_MINCORE_BUF_TYPE
1618 { "mincore", bup_mincore, METH_VARARGS,
1619 "For mincore(src, src_n, src_off, dest, dest_off)"
1620 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1622 { NULL, NULL, 0, NULL }, // sentinel
1625 static int setup_module(PyObject *m)
1627 // FIXME: migrate these tests to configure, or at least don't
1628 // possibly crash the whole application. Check against the type
1629 // we're going to use when passing to python. Other stat types
1630 // are tested at runtime.
1631 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1632 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1633 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1634 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1635 // Just be sure (relevant when passing timestamps back to Python above).
1636 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1637 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1639 // Originally required by append_sparse_region()
1642 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1644 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1650 #pragma clang diagnostic push
1651 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1654 value = INTEGER_TO_PY(INT_MAX);
1655 PyObject_SetAttrString(m, "INT_MAX", value);
1657 value = INTEGER_TO_PY(UINT_MAX);
1658 PyObject_SetAttrString(m, "UINT_MAX", value);
1661 #ifdef HAVE_UTIMENSAT
1664 value = INTEGER_TO_PY(AT_FDCWD);
1665 PyObject_SetAttrString(m, "AT_FDCWD", value);
1667 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1668 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1670 value = INTEGER_TO_PY(UTIME_NOW);
1671 PyObject_SetAttrString(m, "UTIME_NOW", value);
1675 #ifdef BUP_HAVE_MINCORE_INCORE
1678 value = INTEGER_TO_PY(MINCORE_INCORE);
1679 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1683 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1685 e = getenv("BUP_FORCE_TTY");
1686 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1692 #if PY_MAJOR_VERSION < 3
1694 PyMODINIT_FUNC init_helpers(void)
1696 PyObject *m = Py_InitModule("_helpers", helper_methods);
1700 if (!setup_module(m))
1707 # else // PY_MAJOR_VERSION >= 3
1709 static struct PyModuleDef helpers_def = {
1710 PyModuleDef_HEAD_INIT,
1716 NULL, // helpers_traverse,
1717 NULL, // helpers_clear,
1721 PyMODINIT_FUNC PyInit__helpers(void)
1723 PyObject *module = PyModule_Create(&helpers_def);
1726 if (!setup_module(module))
1734 #endif // PY_MAJOR_VERSION >= 3