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 unsigned char *buf = NULL;
534 int out = 0, bits = -1;
536 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
538 assert(len <= INT_MAX);
539 out = bupsplit_find_ofs(buf, len, &bits);
540 if (out) assert(bits >= BUP_BLOBBITS);
541 return Py_BuildValue("ii", out, bits);
545 static PyObject *bitmatch(PyObject *self, PyObject *args)
547 unsigned char *buf1 = NULL, *buf2 = NULL;
548 Py_ssize_t len1 = 0, len2 = 0;
552 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
556 for (byte = 0; byte < len1 && byte < len2; byte++)
558 int b1 = buf1[byte], b2 = buf2[byte];
561 for (bit = 0; bit < 8; bit++)
562 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
568 assert(byte <= (INT_MAX >> 3));
569 return Py_BuildValue("i", byte*8 + bit);
573 static PyObject *firstword(PyObject *self, PyObject *args)
575 unsigned char *buf = NULL;
579 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
585 v = ntohl(*(uint32_t *)buf);
586 return PyLong_FromUnsignedLong(v);
590 #define BLOOM2_HEADERLEN 16
592 static void to_bloom_address_bitmask4(const unsigned char *buf,
593 const int nbits, uint64_t *v, unsigned char *bitmask)
599 memcpy(&high, buf, 4);
600 mask = (1<<nbits) - 1;
601 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
602 bit = (raw >> (37-nbits)) & 0x7;
603 *v = (raw >> (40-nbits)) & mask;
607 static void to_bloom_address_bitmask5(const unsigned char *buf,
608 const int nbits, uint32_t *v, unsigned char *bitmask)
614 memcpy(&high, buf, 4);
615 mask = (1<<nbits) - 1;
617 bit = (raw >> (29-nbits)) & 0x7;
618 *v = (raw >> (32-nbits)) & mask;
622 #define BLOOM_SET_BIT(name, address, otype) \
623 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
625 unsigned char bitmask;\
627 address(buf, nbits, &v, &bitmask);\
628 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
630 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
631 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
634 #define BLOOM_GET_BIT(name, address, otype) \
635 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
637 unsigned char bitmask;\
639 address(buf, nbits, &v, &bitmask);\
640 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
642 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
643 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
646 static PyObject *bloom_add(PyObject *self, PyObject *args)
648 unsigned char *sha = NULL, *bloom = NULL;
650 Py_ssize_t len = 0, blen = 0;
651 int nbits = 0, k = 0;
653 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
656 if (blen < 16+(1<<nbits) || len % 20 != 0)
663 for (end = sha + len; sha < end; sha += 20/k)
664 bloom_set_bit5(bloom, sha, nbits);
670 for (end = sha + len; sha < end; sha += 20/k)
671 bloom_set_bit4(bloom, sha, nbits);
677 return Py_BuildValue("n", len/20);
680 static PyObject *bloom_contains(PyObject *self, PyObject *args)
682 unsigned char *sha = NULL, *bloom = NULL;
683 Py_ssize_t len = 0, blen = 0;
684 int nbits = 0, k = 0;
688 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
698 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
699 if (!bloom_get_bit5(bloom, sha, nbits))
700 return Py_BuildValue("Oi", Py_None, steps);
706 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
707 if (!bloom_get_bit4(bloom, sha, nbits))
708 return Py_BuildValue("Oi", Py_None, steps);
713 return Py_BuildValue("ii", 1, k);
717 static uint32_t _extract_bits(unsigned char *buf, int nbits)
721 mask = (1<<nbits) - 1;
722 v = ntohl(*(uint32_t *)buf);
723 v = (v >> (32-nbits)) & mask;
728 static PyObject *extract_bits(PyObject *self, PyObject *args)
730 unsigned char *buf = NULL;
734 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
740 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
745 unsigned char bytes[20];
748 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
750 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
763 static void _fix_idx_order(struct idx **idxs, int *last_i)
766 int low, mid, high, c = 0;
769 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
771 idxs[*last_i] = NULL;
784 mid = (low + high) / 2;
785 c = _cmp_sha(idx->cur, idxs[mid]->cur);
797 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
802 static uint32_t _get_idx_i(struct idx *idx)
804 if (idx->cur_name == NULL)
805 return idx->name_base;
806 return ntohl(*idx->cur_name) + idx->name_base;
809 #define MIDX4_HEADERLEN 12
811 static PyObject *merge_into(PyObject *self, PyObject *args)
813 PyObject *py_total, *ilist = NULL;
814 unsigned char *fmap = NULL;
815 struct sha *sha_ptr, *sha_start = NULL;
816 uint32_t *table_ptr, *name_ptr, *name_start;
817 struct idx **idxs = NULL;
821 uint32_t count, prefix;
825 if (!PyArg_ParseTuple(args, "w#iOO",
826 &fmap, &flen, &bits, &py_total, &ilist))
829 if (!bup_uint_from_py(&total, py_total, "total"))
832 num_i = PyList_Size(ilist);
833 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
835 for (i = 0; i < num_i; i++)
837 long len, sha_ofs, name_map_ofs;
838 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
839 PyObject *itup = PyList_GetItem(ilist, i);
840 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
841 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
843 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
844 idxs[i]->end = &idxs[i]->cur[len];
846 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
848 idxs[i]->cur_name = NULL;
850 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
851 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
852 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
861 if (count % 102424 == 0 && get_state(self)->istty2)
862 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
863 count*100.0/total, count, total);
865 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
866 while (prefix < new_prefix)
867 table_ptr[prefix++] = htonl(count);
868 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
869 *name_ptr++ = htonl(_get_idx_i(idx));
871 if (idx->cur_name != NULL)
873 _fix_idx_order(idxs, &last_i);
876 while (prefix < (1<<bits))
877 table_ptr[prefix++] = htonl(count);
878 assert(count == total);
879 assert(prefix == (1<<bits));
880 assert(sha_ptr == sha_start+count);
881 assert(name_ptr == name_start+count);
884 return PyLong_FromUnsignedLong(count);
887 #define FAN_ENTRIES 256
889 static PyObject *write_idx(PyObject *self, PyObject *args)
891 char *filename = NULL;
892 PyObject *py_total, *idx = NULL;
894 unsigned char *fmap = NULL;
896 unsigned int total = 0;
898 int i, j, ofs64_count;
899 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
903 if (!PyArg_ParseTuple(args, "sw#OO",
904 &filename, &fmap, &flen, &idx, &py_total))
907 if (!bup_uint_from_py(&total, py_total, "total"))
910 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
911 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
914 const char idx_header[] = "\377tOc\0\0\0\002";
915 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
917 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
918 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
919 crc_ptr = (uint32_t *)&sha_ptr[total];
920 ofs_ptr = (uint32_t *)&crc_ptr[total];
921 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
925 for (i = 0; i < FAN_ENTRIES; ++i)
928 part = PyList_GET_ITEM(idx, i);
930 plen = PyList_GET_SIZE(part);
932 *fan_ptr++ = htonl(count);
933 for (j = 0; j < plen; ++j)
935 unsigned char *sha = NULL;
936 Py_ssize_t sha_len = 0;
937 PyObject *crc_py, *ofs_py;
939 unsigned PY_LONG_LONG ofs_ull;
941 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
942 &sha, &sha_len, &crc_py, &ofs_py))
944 if(!bup_uint_from_py(&crc, crc_py, "crc"))
946 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
948 assert(crc <= UINT32_MAX);
949 assert(ofs_ull <= UINT64_MAX);
951 if (sha_len != sizeof(struct sha))
953 memcpy(sha_ptr++, sha, sizeof(struct sha));
954 *crc_ptr++ = htonl(crc);
955 if (ofs > 0x7fffffff)
957 *ofs64_ptr++ = htonll(ofs);
958 ofs = 0x80000000 | ofs64_count++;
960 *ofs_ptr++ = htonl((uint32_t)ofs);
964 int rc = msync(fmap, flen, MS_ASYNC);
966 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
968 return PyLong_FromUnsignedLong(count);
972 // I would have made this a lower-level function that just fills in a buffer
973 // with random values, and then written those values from python. But that's
974 // about 20% slower in my tests, and since we typically generate random
975 // numbers for benchmarking other parts of bup, any slowness in generating
976 // random bytes will make our benchmarks inaccurate. Plus nobody wants
977 // pseudorandom bytes much except for this anyway.
978 static PyObject *write_random(PyObject *self, PyObject *args)
980 uint32_t buf[1024/4];
981 int fd = -1, seed = 0, verbose = 0;
983 long long len = 0, kbytes = 0, written = 0;
985 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
990 for (kbytes = 0; kbytes < len/1024; kbytes++)
993 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
995 ret = write(fd, buf, sizeof(buf));
999 if (ret < (int)sizeof(buf))
1001 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1002 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1005 // handle non-multiples of 1024
1009 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1011 ret = write(fd, buf, len % 1024);
1017 if (kbytes/1024 > 0)
1018 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1019 return Py_BuildValue("L", written);
1023 static PyObject *random_sha(PyObject *self, PyObject *args)
1025 static int seeded = 0;
1026 uint32_t shabuf[20/4];
1031 assert(sizeof(shabuf) == 20);
1032 srandom(time(NULL));
1036 if (!PyArg_ParseTuple(args, ""))
1039 memset(shabuf, 0, sizeof(shabuf));
1040 for (i=0; i < 20/4; i++)
1041 shabuf[i] = random();
1042 return Py_BuildValue("s#", shabuf, 20);
1046 static int _open_noatime(const char *filename, int attrs)
1048 int attrs_noatime, fd;
1051 attrs |= O_NOFOLLOW;
1054 attrs |= O_LARGEFILE;
1056 attrs_noatime = attrs;
1058 attrs_noatime |= O_NOATIME;
1060 fd = open(filename, attrs_noatime);
1061 if (fd < 0 && errno == EPERM)
1063 // older Linux kernels would return EPERM if you used O_NOATIME
1064 // and weren't the file's owner. This pointless restriction was
1065 // relaxed eventually, but we have to handle it anyway.
1066 // (VERY old kernels didn't recognized O_NOATIME, but they would
1067 // just harmlessly ignore it, so this branch won't trigger)
1068 fd = open(filename, attrs);
1074 static PyObject *open_noatime(PyObject *self, PyObject *args)
1076 char *filename = NULL;
1078 if (!PyArg_ParseTuple(args, "s", &filename))
1080 fd = _open_noatime(filename, 0);
1082 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1083 return Py_BuildValue("i", fd);
1087 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1090 long long llofs, lllen = 0;
1091 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1094 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1095 return PyErr_Format(PyExc_OverflowError,
1096 "fadvise offset overflows off_t");
1097 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1098 return PyErr_Format(PyExc_OverflowError,
1099 "fadvise length overflows off_t");
1100 #ifdef POSIX_FADV_DONTNEED
1101 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1103 return Py_BuildValue("");
1107 // Currently the Linux kernel and FUSE disagree over the type for
1108 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1109 // but FUSE chose long (matching the declaration in linux/fs.h). So
1110 // if you use int, and then traverse a FUSE filesystem, you may
1111 // corrupt the stack. But if you use long, then you may get invalid
1112 // results on big-endian systems.
1114 // For now, we just use long, and then disable Linux attrs entirely
1115 // (with a warning) in helpers.py on systems that are affected.
1117 #ifdef BUP_HAVE_FILE_ATTRS
1118 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1125 if (!PyArg_ParseTuple(args, "s", &path))
1128 fd = _open_noatime(path, O_NONBLOCK);
1130 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1132 attr = 0; // Handle int/long mismatch (see above)
1133 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1137 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1140 assert(attr <= UINT_MAX); // Kernel type is actually int
1141 return PyLong_FromUnsignedLong(attr);
1143 #endif /* def BUP_HAVE_FILE_ATTRS */
1147 #ifdef BUP_HAVE_FILE_ATTRS
1148 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1151 unsigned long orig_attr;
1157 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1160 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1163 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1165 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1167 // Restrict attr to modifiable flags acdeijstuADST -- see
1168 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1169 // in pf.c flags_array[].
1170 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1171 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1172 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1173 | FS_TOPDIR_FL | FS_NOCOW_FL;
1175 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1176 orig_attr = 0; // Handle int/long mismatch (see above)
1177 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1181 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1183 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1184 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1186 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1190 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1194 return Py_BuildValue("O", Py_None);
1196 #endif /* def BUP_HAVE_FILE_ATTRS */
1199 #ifndef HAVE_UTIMENSAT
1201 #error "cannot find utimensat or utimes()"
1203 #ifndef HAVE_LUTIMES
1204 #error "cannot find utimensat or lutimes()"
1208 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1212 const long long lltmp = PyLong_AsLongLong(pylong); \
1213 if (lltmp == -1 && PyErr_Occurred()) \
1215 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1217 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1218 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1220 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1226 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1234 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1243 #ifdef HAVE_UTIMENSAT
1245 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1250 PyObject *access_py, *modification_py;
1251 struct timespec ts[2];
1253 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1256 &access_py, &(ts[0].tv_nsec),
1257 &modification_py, &(ts[1].tv_nsec),
1262 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1265 PyErr_SetString(PyExc_ValueError,
1266 "unable to convert access time seconds for utimensat");
1269 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1272 PyErr_SetString(PyExc_ValueError,
1273 "unable to convert modification time seconds for utimensat");
1276 rc = utimensat(fd, path, ts, flag);
1278 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1280 return Py_BuildValue("O", Py_None);
1283 #endif /* def HAVE_UTIMENSAT */
1286 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1288 static int bup_parse_xutimes_args(char **path,
1289 struct timeval tv[2],
1292 PyObject *access_py, *modification_py;
1293 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1295 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1297 &access_py, &access_us,
1298 &modification_py, &modification_us))
1302 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1305 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1308 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1310 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1313 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1316 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1319 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1321 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1327 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1331 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1334 struct timeval tv[2];
1335 if (!bup_parse_xutimes_args(&path, tv, args))
1337 int rc = utimes(path, tv);
1339 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1340 return Py_BuildValue("O", Py_None);
1342 #endif /* def HAVE_UTIMES */
1346 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1349 struct timeval tv[2];
1350 if (!bup_parse_xutimes_args(&path, tv, args))
1352 int rc = lutimes(path, tv);
1354 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1356 return Py_BuildValue("O", Py_None);
1358 #endif /* def HAVE_LUTIMES */
1361 #ifdef HAVE_STAT_ST_ATIM
1362 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1363 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1364 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1365 #elif defined HAVE_STAT_ST_ATIMENSEC
1366 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1367 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1368 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1370 # define BUP_STAT_ATIME_NS(st) 0
1371 # define BUP_STAT_MTIME_NS(st) 0
1372 # define BUP_STAT_CTIME_NS(st) 0
1376 #pragma clang diagnostic push
1377 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1379 static PyObject *stat_struct_to_py(const struct stat *st,
1380 const char *filename,
1383 // We can check the known (via POSIX) signed and unsigned types at
1384 // compile time, but not (easily) the unspecified types, so handle
1385 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1387 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1388 INTEGER_TO_PY(st->st_mode),
1389 (unsigned PY_LONG_LONG) st->st_ino,
1390 INTEGER_TO_PY(st->st_dev),
1391 INTEGER_TO_PY(st->st_nlink),
1392 INTEGER_TO_PY(st->st_uid),
1393 INTEGER_TO_PY(st->st_gid),
1394 INTEGER_TO_PY(st->st_rdev),
1395 (PY_LONG_LONG) st->st_size,
1396 INTEGER_TO_PY(st->st_atime),
1397 (long) BUP_STAT_ATIME_NS(st),
1398 INTEGER_TO_PY(st->st_mtime),
1399 (long) BUP_STAT_MTIME_NS(st),
1400 INTEGER_TO_PY(st->st_ctime),
1401 (long) BUP_STAT_CTIME_NS(st));
1404 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1406 static PyObject *bup_stat(PyObject *self, PyObject *args)
1411 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1415 rc = stat(filename, &st);
1417 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1418 return stat_struct_to_py(&st, filename, 0);
1422 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1427 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1431 rc = lstat(filename, &st);
1433 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1434 return stat_struct_to_py(&st, filename, 0);
1438 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1442 if (!PyArg_ParseTuple(args, "i", &fd))
1446 rc = fstat(fd, &st);
1448 return PyErr_SetFromErrno(PyExc_OSError);
1449 return stat_struct_to_py(&st, NULL, fd);
1453 #ifdef HAVE_TM_TM_GMTOFF
1454 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1458 if (!PyArg_ParseTuple(args, "L", &lltime))
1460 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1461 return PyErr_Format(PyExc_OverflowError, "time value too large");
1465 if(localtime_r(&ttime, &tm) == NULL)
1466 return PyErr_SetFromErrno(PyExc_OSError);
1468 // Match the Python struct_time values.
1469 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1470 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1471 tm.tm_hour, tm.tm_min, tm.tm_sec,
1472 tm.tm_wday, tm.tm_yday + 1,
1473 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1475 #endif /* def HAVE_TM_TM_GMTOFF */
1478 #ifdef BUP_MINCORE_BUF_TYPE
1479 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1481 Py_buffer src, dest;
1482 PyObject *py_src_n, *py_src_off, *py_dest_off;
1484 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1485 &src, &py_src_n, &py_src_off,
1486 &dest, &py_dest_off))
1489 PyObject *result = NULL;
1491 unsigned long long src_n, src_off, 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")))
1495 goto clean_and_return;
1497 unsigned long long src_region_end;
1498 if (!uadd(&src_region_end, src_off, src_n)) {
1499 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1500 goto clean_and_return;
1502 if (src_region_end > src.len) {
1503 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1504 goto clean_and_return;
1507 unsigned long long dest_size;
1508 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1509 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1510 goto clean_and_return;
1512 if (dest_off > dest_size) {
1513 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1514 goto clean_and_return;
1518 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1519 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1520 goto clean_and_return;
1522 int rc = mincore((void *)(src.buf + src_off), src_n,
1523 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1525 result = PyErr_SetFromErrno(PyExc_OSError);
1526 goto clean_and_return;
1528 result = Py_BuildValue("O", Py_None);
1531 PyBuffer_Release(&src);
1532 PyBuffer_Release(&dest);
1535 #endif /* def BUP_MINCORE_BUF_TYPE */
1538 static PyMethodDef helper_methods[] = {
1539 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1540 "Write buf excepting zeros at the end. Return trailing zero count." },
1541 { "selftest", selftest, METH_VARARGS,
1542 "Check that the rolling checksum rolls correctly (for unit tests)." },
1543 { "blobbits", blobbits, METH_VARARGS,
1544 "Return the number of bits in the rolling checksum." },
1545 { "splitbuf", splitbuf, METH_VARARGS,
1546 "Split a list of strings based on a rolling checksum." },
1547 { "bitmatch", bitmatch, METH_VARARGS,
1548 "Count the number of matching prefix bits between two strings." },
1549 { "firstword", firstword, METH_VARARGS,
1550 "Return an int corresponding to the first 32 bits of buf." },
1551 { "bloom_contains", bloom_contains, METH_VARARGS,
1552 "Check if a bloom filter of 2^nbits bytes contains an object" },
1553 { "bloom_add", bloom_add, METH_VARARGS,
1554 "Add an object to a bloom filter of 2^nbits bytes" },
1555 { "extract_bits", extract_bits, METH_VARARGS,
1556 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1557 { "merge_into", merge_into, METH_VARARGS,
1558 "Merges a bunch of idx and midx files into a single midx." },
1559 { "write_idx", write_idx, METH_VARARGS,
1560 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1561 { "write_random", write_random, METH_VARARGS,
1562 "Write random bytes to the given file descriptor" },
1563 { "random_sha", random_sha, METH_VARARGS,
1564 "Return a random 20-byte string" },
1565 { "open_noatime", open_noatime, METH_VARARGS,
1566 "open() the given filename for read with O_NOATIME if possible" },
1567 { "fadvise_done", fadvise_done, METH_VARARGS,
1568 "Inform the kernel that we're finished with earlier parts of a file" },
1569 #ifdef BUP_HAVE_FILE_ATTRS
1570 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1571 "Return the Linux attributes for the given file." },
1573 #ifdef BUP_HAVE_FILE_ATTRS
1574 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1575 "Set the Linux attributes for the given file." },
1577 #ifdef HAVE_UTIMENSAT
1578 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1579 "Change path timestamps with nanosecond precision (POSIX)." },
1582 { "bup_utimes", bup_utimes, METH_VARARGS,
1583 "Change path timestamps with microsecond precision." },
1586 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1587 "Change path timestamps with microsecond precision;"
1588 " don't follow symlinks." },
1590 { "stat", bup_stat, METH_VARARGS,
1591 "Extended version of stat." },
1592 { "lstat", bup_lstat, METH_VARARGS,
1593 "Extended version of lstat." },
1594 { "fstat", bup_fstat, METH_VARARGS,
1595 "Extended version of fstat." },
1596 #ifdef HAVE_TM_TM_GMTOFF
1597 { "localtime", bup_localtime, METH_VARARGS,
1598 "Return struct_time elements plus the timezone offset and name." },
1600 { "bytescmp", bup_bytescmp, METH_VARARGS,
1601 "Return a negative value if x < y, zero if equal, positive otherwise."},
1602 #ifdef BUP_MINCORE_BUF_TYPE
1603 { "mincore", bup_mincore, METH_VARARGS,
1604 "For mincore(src, src_n, src_off, dest, dest_off)"
1605 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1607 { NULL, NULL, 0, NULL }, // sentinel
1610 static int setup_module(PyObject *m)
1612 // FIXME: migrate these tests to configure, or at least don't
1613 // possibly crash the whole application. Check against the type
1614 // we're going to use when passing to python. Other stat types
1615 // are tested at runtime.
1616 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1617 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1618 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1619 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1620 // Just be sure (relevant when passing timestamps back to Python above).
1621 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1622 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1624 // Originally required by append_sparse_region()
1627 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1629 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1635 #pragma clang diagnostic push
1636 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1639 value = INTEGER_TO_PY(INT_MAX);
1640 PyObject_SetAttrString(m, "INT_MAX", value);
1642 value = INTEGER_TO_PY(UINT_MAX);
1643 PyObject_SetAttrString(m, "UINT_MAX", value);
1646 #ifdef HAVE_UTIMENSAT
1649 value = INTEGER_TO_PY(AT_FDCWD);
1650 PyObject_SetAttrString(m, "AT_FDCWD", value);
1652 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1653 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1655 value = INTEGER_TO_PY(UTIME_NOW);
1656 PyObject_SetAttrString(m, "UTIME_NOW", value);
1660 #ifdef BUP_HAVE_MINCORE_INCORE
1663 value = INTEGER_TO_PY(MINCORE_INCORE);
1664 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1668 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1670 e = getenv("BUP_FORCE_TTY");
1671 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1677 #if PY_MAJOR_VERSION < 3
1679 PyMODINIT_FUNC init_helpers(void)
1681 PyObject *m = Py_InitModule("_helpers", helper_methods);
1685 if (!setup_module(m))
1692 # else // PY_MAJOR_VERSION >= 3
1694 static struct PyModuleDef helpers_def = {
1695 PyModuleDef_HEAD_INIT,
1701 NULL, // helpers_traverse,
1702 NULL, // helpers_clear,
1706 PyMODINIT_FUNC PyInit__helpers(void)
1708 PyObject *module = PyModule_Create(&helpers_def);
1711 if (!setup_module(module))
1719 #endif // PY_MAJOR_VERSION >= 3