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)
76 # define get_state(x) ((state_t *) PyModule_GetState(x))
78 #endif // PY_MAJOR_VERSION >= 3
82 // This function should technically be macro'd out if it's going to be used
83 // more than ocasionally. As of this writing, it'll actually never be called
84 // in real world bup scenarios (because our packs are < MAX_INT bytes).
85 static uint64_t htonll(uint64_t value)
87 static const int endian_test = 42;
89 if (*(char *)&endian_test == endian_test) // LSB-MSB
90 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
91 return value; // already in network byte order MSB-LSB
96 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
99 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
103 // At the moment any code that calls INTGER_TO_PY() will have to
104 // disable -Wtautological-compare for clang. See below.
106 #define INTEGER_TO_PY(x) \
107 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
111 #if PY_MAJOR_VERSION < 3
112 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
115 const long tmp = PyInt_AsLong(py);
116 if (tmp == -1 && PyErr_Occurred())
118 if (PyErr_ExceptionMatches(PyExc_OverflowError))
119 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
125 PyErr_Format(PyExc_OverflowError,
126 "negative %s cannot be converted to unsigned long", name);
135 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
137 #if PY_MAJOR_VERSION < 3
139 return bup_ulong_from_pyint(x, py, name);
142 if (!PyLong_Check(py))
144 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
148 const unsigned long tmp = PyLong_AsUnsignedLong(py);
149 if (PyErr_Occurred())
151 if (PyErr_ExceptionMatches(PyExc_OverflowError))
152 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
161 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
164 if (!bup_ulong_from_py(&tmp, py, name))
169 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
176 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
179 #if PY_MAJOR_VERSION < 3
183 if (bup_ulong_from_pyint(&tmp, py, name))
192 if (!PyLong_Check(py))
194 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
198 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
199 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
201 if (PyErr_ExceptionMatches(PyExc_OverflowError))
202 PyErr_Format(PyExc_OverflowError,
203 "%s too big for unsigned long long", name);
211 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
213 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
214 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
217 Py_ssize_t s1_len, s2_len;
218 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
220 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
222 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
223 const int cmp = memcmp(s1, s2, n);
225 return PyLong_FromLong(cmp);
226 if (s1_len == s2_len)
227 return PyLong_FromLong(0);;
228 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
232 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
233 #if __WIN32__ || __CYGWIN__
235 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
236 static void unpythonize_argv(void) { }
238 #else // not __WIN32__
240 // For some reason this isn't declared in Python.h
241 extern void Py_GetArgcArgv(int *argc, char ***argv);
243 static void unpythonize_argv(void)
248 Py_GetArgcArgv(&argc, &argv);
250 for (i = 0; i < argc-1; i++)
252 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
254 // The argv block doesn't work the way we expected; it's unsafe
260 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
262 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
266 p = strrchr(argv[1], '/');
272 memmove(argv[0], p, len);
273 memset(arge - diff, 0, diff);
274 for (i = 0; i < argc; i++)
275 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
280 #endif // not __WIN32__ or __CYGWIN__
283 static int write_all(int fd, const void *buf, const size_t count)
286 while (written < count)
288 const ssize_t rc = write(fd, buf + written, count - written);
297 static int uadd(unsigned long long *dest,
298 const unsigned long long x,
299 const unsigned long long y)
301 const unsigned long long result = x + y;
302 if (result < x || result < y)
309 static PyObject *append_sparse_region(const int fd, unsigned long long n)
314 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
316 const off_t off = lseek(fd, new_off, SEEK_CUR);
317 if (off == (off_t) -1)
318 return PyErr_SetFromErrno(PyExc_IOError);
325 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
327 unsigned long long prev_pending,
328 const unsigned long long count)
330 // Add count additional sparse zeros to prev_pending and store the
331 // result in new_pending, or if the total won't fit in
332 // new_pending, write some of the zeros to fd sparsely, and store
333 // the remaining sum in new_pending.
334 if (!uadd(new_pending, prev_pending, count))
336 PyObject *err = append_sparse_region(fd, prev_pending);
339 *new_pending = count;
345 static byte* find_not_zero(const byte * const start, const byte * const end)
347 // Return a pointer to first non-zero byte between start and end,
348 // or end if there isn't one.
349 assert(start <= end);
350 const unsigned char *cur = start;
351 while (cur < end && *cur == 0)
357 static byte* find_trailing_zeros(const byte * const start,
358 const byte * const end)
360 // Return a pointer to the start of any trailing run of zeros, or
361 // end if there isn't one.
362 assert(start <= end);
365 const byte * cur = end;
366 while (cur > start && *--cur == 0) {}
370 return (byte *) (cur + 1);
374 static byte *find_non_sparse_end(const byte * const start,
375 const byte * const end,
376 const unsigned long long min_len)
378 // Return the first pointer to a min_len sparse block in [start,
379 // end) if there is one, otherwise a pointer to the start of any
380 // trailing run of zeros. If there are no trailing zeros, return
386 // Probe in min_len jumps, searching backward from the jump
387 // destination for a non-zero byte. If such a byte is found, move
388 // just past it and try again.
389 const byte *candidate = start;
390 // End of any run of zeros, starting at candidate, that we've already seen
391 const byte *end_of_known_zeros = candidate;
392 while (end - candidate >= min_len) // Handle all min_len candidate blocks
394 const byte * const probe_end = candidate + min_len;
395 const byte * const trailing_zeros =
396 find_trailing_zeros(end_of_known_zeros, probe_end);
397 if (trailing_zeros == probe_end)
398 end_of_known_zeros = candidate = probe_end;
399 else if (trailing_zeros == end_of_known_zeros)
401 assert(candidate >= start);
402 assert(candidate <= end);
403 assert(*candidate == 0);
404 return (byte *) candidate;
408 candidate = trailing_zeros;
409 end_of_known_zeros = probe_end;
413 if (candidate == end)
416 // No min_len sparse run found, search backward from end
417 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
420 if (trailing_zeros == end_of_known_zeros)
422 assert(candidate >= start);
423 assert(candidate < end);
424 assert(*candidate == 0);
425 assert(end - candidate < min_len);
426 return (byte *) candidate;
429 if (trailing_zeros == end)
431 assert(*(end - 1) != 0);
435 assert(end - trailing_zeros < min_len);
436 assert(trailing_zeros >= start);
437 assert(trailing_zeros < end);
438 assert(*trailing_zeros == 0);
439 return (byte *) trailing_zeros;
443 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
446 unsigned char *buf = NULL;
448 PyObject *py_min_sparse_len, *py_prev_sparse_len;
449 if (!PyArg_ParseTuple(args, "it#OO",
450 &fd, &buf, &sbuf_len,
451 &py_min_sparse_len, &py_prev_sparse_len))
453 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
454 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
456 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
459 return PyErr_Format(PyExc_ValueError, "negative bufer length");
460 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
461 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
463 const byte * block = buf; // Start of pending block
464 const byte * const end = buf + buf_len;
465 unsigned long long zeros = prev_sparse_len;
468 assert(block <= end);
470 return PyLong_FromUnsignedLongLong(zeros);
474 // Look for the end of block, i.e. the next sparse run of
475 // at least min_sparse_len zeros, or the end of the
477 const byte * const probe = find_non_sparse_end(block + 1, end,
479 // Either at end of block, or end of non-sparse; write pending data
480 PyObject *err = append_sparse_region(fd, zeros);
483 int rc = write_all(fd, block, probe - block);
485 return PyErr_SetFromErrno(PyExc_IOError);
487 if (end - probe < min_sparse_len)
490 zeros = min_sparse_len;
491 block = probe + zeros;
495 // Should be in the first loop iteration, a sparse run of
496 // zeros, or nearly at the end of the block (within
498 const byte * const zeros_end = find_not_zero(block, end);
499 PyObject *err = record_sparse_zeros(&zeros, fd,
500 zeros, zeros_end - block);
503 assert(block <= zeros_end);
510 static PyObject *selftest(PyObject *self, PyObject *args)
512 if (!PyArg_ParseTuple(args, ""))
515 return Py_BuildValue("i", !bupsplit_selftest());
519 static PyObject *blobbits(PyObject *self, PyObject *args)
521 if (!PyArg_ParseTuple(args, ""))
523 return Py_BuildValue("i", BUP_BLOBBITS);
527 static PyObject *splitbuf(PyObject *self, PyObject *args)
529 unsigned char *buf = NULL;
531 int out = 0, bits = -1;
533 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
535 assert(len <= INT_MAX);
536 out = bupsplit_find_ofs(buf, len, &bits);
537 if (out) assert(bits >= BUP_BLOBBITS);
538 return Py_BuildValue("ii", out, bits);
542 static PyObject *bitmatch(PyObject *self, PyObject *args)
544 unsigned char *buf1 = NULL, *buf2 = NULL;
545 Py_ssize_t len1 = 0, len2 = 0;
549 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
553 for (byte = 0; byte < len1 && byte < len2; byte++)
555 int b1 = buf1[byte], b2 = buf2[byte];
558 for (bit = 0; bit < 8; bit++)
559 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
565 assert(byte <= (INT_MAX >> 3));
566 return Py_BuildValue("i", byte*8 + bit);
570 static PyObject *firstword(PyObject *self, PyObject *args)
572 unsigned char *buf = NULL;
576 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
582 v = ntohl(*(uint32_t *)buf);
583 return PyLong_FromUnsignedLong(v);
587 #define BLOOM2_HEADERLEN 16
589 static void to_bloom_address_bitmask4(const unsigned char *buf,
590 const int nbits, uint64_t *v, unsigned char *bitmask)
596 memcpy(&high, buf, 4);
597 mask = (1<<nbits) - 1;
598 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
599 bit = (raw >> (37-nbits)) & 0x7;
600 *v = (raw >> (40-nbits)) & mask;
604 static void to_bloom_address_bitmask5(const unsigned char *buf,
605 const int nbits, uint32_t *v, unsigned char *bitmask)
611 memcpy(&high, buf, 4);
612 mask = (1<<nbits) - 1;
614 bit = (raw >> (29-nbits)) & 0x7;
615 *v = (raw >> (32-nbits)) & mask;
619 #define BLOOM_SET_BIT(name, address, otype) \
620 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
622 unsigned char bitmask;\
624 address(buf, nbits, &v, &bitmask);\
625 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
627 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
628 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
631 #define BLOOM_GET_BIT(name, address, otype) \
632 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
634 unsigned char bitmask;\
636 address(buf, nbits, &v, &bitmask);\
637 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
639 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
640 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
643 static PyObject *bloom_add(PyObject *self, PyObject *args)
645 unsigned char *sha = NULL, *bloom = NULL;
647 Py_ssize_t len = 0, blen = 0;
648 int nbits = 0, k = 0;
650 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
653 if (blen < 16+(1<<nbits) || len % 20 != 0)
660 for (end = sha + len; sha < end; sha += 20/k)
661 bloom_set_bit5(bloom, sha, nbits);
667 for (end = sha + len; sha < end; sha += 20/k)
668 bloom_set_bit4(bloom, sha, nbits);
674 return Py_BuildValue("n", len/20);
677 static PyObject *bloom_contains(PyObject *self, PyObject *args)
679 unsigned char *sha = NULL, *bloom = NULL;
680 Py_ssize_t len = 0, blen = 0;
681 int nbits = 0, k = 0;
685 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
695 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
696 if (!bloom_get_bit5(bloom, sha, nbits))
697 return Py_BuildValue("Oi", Py_None, steps);
703 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
704 if (!bloom_get_bit4(bloom, sha, nbits))
705 return Py_BuildValue("Oi", Py_None, steps);
710 return Py_BuildValue("ii", 1, k);
714 static uint32_t _extract_bits(unsigned char *buf, int nbits)
718 mask = (1<<nbits) - 1;
719 v = ntohl(*(uint32_t *)buf);
720 v = (v >> (32-nbits)) & mask;
725 static PyObject *extract_bits(PyObject *self, PyObject *args)
727 unsigned char *buf = NULL;
731 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
737 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
742 unsigned char bytes[20];
756 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
759 for (i = 0; i < sizeof(struct sha); i++)
760 if (sha1->bytes[i] != sha2->bytes[i])
761 return sha1->bytes[i] - sha2->bytes[i];
766 static void _fix_idx_order(struct idx **idxs, int *last_i)
769 int low, mid, high, c = 0;
772 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
774 idxs[*last_i] = NULL;
787 mid = (low + high) / 2;
788 c = _cmp_sha(idx->cur, idxs[mid]->cur);
800 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
805 static uint32_t _get_idx_i(struct idx *idx)
807 if (idx->cur_name == NULL)
808 return idx->name_base;
809 return ntohl(*idx->cur_name) + idx->name_base;
812 #define MIDX4_HEADERLEN 12
814 static PyObject *merge_into(PyObject *self, PyObject *args)
816 PyObject *py_total, *ilist = NULL;
817 unsigned char *fmap = NULL;
818 struct sha *sha_ptr, *sha_start = NULL;
819 uint32_t *table_ptr, *name_ptr, *name_start;
820 struct idx **idxs = NULL;
824 uint32_t count, prefix;
828 if (!PyArg_ParseTuple(args, "w#iOO",
829 &fmap, &flen, &bits, &py_total, &ilist))
832 if (!bup_uint_from_py(&total, py_total, "total"))
835 num_i = PyList_Size(ilist);
836 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
838 for (i = 0; i < num_i; i++)
840 long len, sha_ofs, name_map_ofs;
841 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
842 PyObject *itup = PyList_GetItem(ilist, i);
843 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
844 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
846 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
847 idxs[i]->end = &idxs[i]->cur[len];
849 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
851 idxs[i]->cur_name = NULL;
853 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
854 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
855 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
864 if (count % 102424 == 0 && get_state(self)->istty2)
865 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
866 count*100.0/total, count, total);
868 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
869 while (prefix < new_prefix)
870 table_ptr[prefix++] = htonl(count);
871 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
872 *name_ptr++ = htonl(_get_idx_i(idx));
874 if (idx->cur_name != NULL)
876 _fix_idx_order(idxs, &last_i);
879 while (prefix < (1<<bits))
880 table_ptr[prefix++] = htonl(count);
881 assert(count == total);
882 assert(prefix == (1<<bits));
883 assert(sha_ptr == sha_start+count);
884 assert(name_ptr == name_start+count);
887 return PyLong_FromUnsignedLong(count);
890 #define FAN_ENTRIES 256
892 static PyObject *write_idx(PyObject *self, PyObject *args)
894 char *filename = NULL;
895 PyObject *py_total, *idx = NULL;
897 unsigned char *fmap = NULL;
899 unsigned int total = 0;
901 int i, j, ofs64_count;
902 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
906 if (!PyArg_ParseTuple(args, "sw#OO",
907 &filename, &fmap, &flen, &idx, &py_total))
910 if (!bup_uint_from_py(&total, py_total, "total"))
913 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
914 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
917 const char idx_header[] = "\377tOc\0\0\0\002";
918 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
920 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
921 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
922 crc_ptr = (uint32_t *)&sha_ptr[total];
923 ofs_ptr = (uint32_t *)&crc_ptr[total];
924 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
928 for (i = 0; i < FAN_ENTRIES; ++i)
931 part = PyList_GET_ITEM(idx, i);
933 plen = PyList_GET_SIZE(part);
935 *fan_ptr++ = htonl(count);
936 for (j = 0; j < plen; ++j)
938 unsigned char *sha = NULL;
939 Py_ssize_t sha_len = 0;
940 PyObject *crc_py, *ofs_py;
942 unsigned PY_LONG_LONG ofs_ull;
944 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
945 &sha, &sha_len, &crc_py, &ofs_py))
947 if(!bup_uint_from_py(&crc, crc_py, "crc"))
949 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
951 assert(crc <= UINT32_MAX);
952 assert(ofs_ull <= UINT64_MAX);
954 if (sha_len != sizeof(struct sha))
956 memcpy(sha_ptr++, sha, sizeof(struct sha));
957 *crc_ptr++ = htonl(crc);
958 if (ofs > 0x7fffffff)
960 *ofs64_ptr++ = htonll(ofs);
961 ofs = 0x80000000 | ofs64_count++;
963 *ofs_ptr++ = htonl((uint32_t)ofs);
967 int rc = msync(fmap, flen, MS_ASYNC);
969 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
971 return PyLong_FromUnsignedLong(count);
975 // I would have made this a lower-level function that just fills in a buffer
976 // with random values, and then written those values from python. But that's
977 // about 20% slower in my tests, and since we typically generate random
978 // numbers for benchmarking other parts of bup, any slowness in generating
979 // random bytes will make our benchmarks inaccurate. Plus nobody wants
980 // pseudorandom bytes much except for this anyway.
981 static PyObject *write_random(PyObject *self, PyObject *args)
983 uint32_t buf[1024/4];
984 int fd = -1, seed = 0, verbose = 0;
986 long long len = 0, kbytes = 0, written = 0;
988 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
993 for (kbytes = 0; kbytes < len/1024; kbytes++)
996 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
998 ret = write(fd, buf, sizeof(buf));
1002 if (ret < (int)sizeof(buf))
1004 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1005 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1008 // handle non-multiples of 1024
1012 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1014 ret = write(fd, buf, len % 1024);
1020 if (kbytes/1024 > 0)
1021 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1022 return Py_BuildValue("L", written);
1026 static PyObject *random_sha(PyObject *self, PyObject *args)
1028 static int seeded = 0;
1029 uint32_t shabuf[20/4];
1034 assert(sizeof(shabuf) == 20);
1035 srandom(time(NULL));
1039 if (!PyArg_ParseTuple(args, ""))
1042 memset(shabuf, 0, sizeof(shabuf));
1043 for (i=0; i < 20/4; i++)
1044 shabuf[i] = random();
1045 return Py_BuildValue("s#", shabuf, 20);
1049 static int _open_noatime(const char *filename, int attrs)
1051 int attrs_noatime, fd;
1054 attrs |= O_NOFOLLOW;
1057 attrs |= O_LARGEFILE;
1059 attrs_noatime = attrs;
1061 attrs_noatime |= O_NOATIME;
1063 fd = open(filename, attrs_noatime);
1064 if (fd < 0 && errno == EPERM)
1066 // older Linux kernels would return EPERM if you used O_NOATIME
1067 // and weren't the file's owner. This pointless restriction was
1068 // relaxed eventually, but we have to handle it anyway.
1069 // (VERY old kernels didn't recognized O_NOATIME, but they would
1070 // just harmlessly ignore it, so this branch won't trigger)
1071 fd = open(filename, attrs);
1077 static PyObject *open_noatime(PyObject *self, PyObject *args)
1079 char *filename = NULL;
1081 if (!PyArg_ParseTuple(args, "s", &filename))
1083 fd = _open_noatime(filename, 0);
1085 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1086 return Py_BuildValue("i", fd);
1090 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1093 long long llofs, lllen = 0;
1094 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1097 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1098 return PyErr_Format(PyExc_OverflowError,
1099 "fadvise offset overflows off_t");
1100 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1101 return PyErr_Format(PyExc_OverflowError,
1102 "fadvise length overflows off_t");
1103 #ifdef POSIX_FADV_DONTNEED
1104 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1106 return Py_BuildValue("");
1110 // Currently the Linux kernel and FUSE disagree over the type for
1111 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1112 // but FUSE chose long (matching the declaration in linux/fs.h). So
1113 // if you use int, and then traverse a FUSE filesystem, you may
1114 // corrupt the stack. But if you use long, then you may get invalid
1115 // results on big-endian systems.
1117 // For now, we just use long, and then disable Linux attrs entirely
1118 // (with a warning) in helpers.py on systems that are affected.
1120 #ifdef BUP_HAVE_FILE_ATTRS
1121 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1128 if (!PyArg_ParseTuple(args, "s", &path))
1131 fd = _open_noatime(path, O_NONBLOCK);
1133 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1135 attr = 0; // Handle int/long mismatch (see above)
1136 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1140 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1143 assert(attr <= UINT_MAX); // Kernel type is actually int
1144 return PyLong_FromUnsignedLong(attr);
1146 #endif /* def BUP_HAVE_FILE_ATTRS */
1150 #ifdef BUP_HAVE_FILE_ATTRS
1151 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1154 unsigned long orig_attr;
1160 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1163 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1166 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1168 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1170 // Restrict attr to modifiable flags acdeijstuADST -- see
1171 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1172 // in pf.c flags_array[].
1173 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1174 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1175 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1176 | FS_TOPDIR_FL | FS_NOCOW_FL;
1178 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1179 orig_attr = 0; // Handle int/long mismatch (see above)
1180 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1184 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1186 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1187 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1189 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1193 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1197 return Py_BuildValue("O", Py_None);
1199 #endif /* def BUP_HAVE_FILE_ATTRS */
1202 #ifndef HAVE_UTIMENSAT
1204 #error "cannot find utimensat or utimes()"
1206 #ifndef HAVE_LUTIMES
1207 #error "cannot find utimensat or lutimes()"
1211 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1215 const long long lltmp = PyLong_AsLongLong(pylong); \
1216 if (lltmp == -1 && PyErr_Occurred()) \
1218 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1220 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1221 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1223 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1229 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1237 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1246 #ifdef HAVE_UTIMENSAT
1248 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1253 PyObject *access_py, *modification_py;
1254 struct timespec ts[2];
1256 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1259 &access_py, &(ts[0].tv_nsec),
1260 &modification_py, &(ts[1].tv_nsec),
1265 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1268 PyErr_SetString(PyExc_ValueError,
1269 "unable to convert access time seconds for utimensat");
1272 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1275 PyErr_SetString(PyExc_ValueError,
1276 "unable to convert modification time seconds for utimensat");
1279 rc = utimensat(fd, path, ts, flag);
1281 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1283 return Py_BuildValue("O", Py_None);
1286 #endif /* def HAVE_UTIMENSAT */
1289 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1291 static int bup_parse_xutimes_args(char **path,
1292 struct timeval tv[2],
1295 PyObject *access_py, *modification_py;
1296 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1298 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1300 &access_py, &access_us,
1301 &modification_py, &modification_us))
1305 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1308 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1311 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1313 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1316 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1319 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1322 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1324 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1330 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1334 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1337 struct timeval tv[2];
1338 if (!bup_parse_xutimes_args(&path, tv, args))
1340 int rc = utimes(path, tv);
1342 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1343 return Py_BuildValue("O", Py_None);
1345 #endif /* def HAVE_UTIMES */
1349 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1352 struct timeval tv[2];
1353 if (!bup_parse_xutimes_args(&path, tv, args))
1355 int rc = lutimes(path, tv);
1357 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1359 return Py_BuildValue("O", Py_None);
1361 #endif /* def HAVE_LUTIMES */
1364 #ifdef HAVE_STAT_ST_ATIM
1365 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1366 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1367 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1368 #elif defined HAVE_STAT_ST_ATIMENSEC
1369 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1370 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1371 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1373 # define BUP_STAT_ATIME_NS(st) 0
1374 # define BUP_STAT_MTIME_NS(st) 0
1375 # define BUP_STAT_CTIME_NS(st) 0
1379 #pragma clang diagnostic push
1380 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1382 static PyObject *stat_struct_to_py(const struct stat *st,
1383 const char *filename,
1386 // We can check the known (via POSIX) signed and unsigned types at
1387 // compile time, but not (easily) the unspecified types, so handle
1388 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1390 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1391 INTEGER_TO_PY(st->st_mode),
1392 (unsigned PY_LONG_LONG) st->st_ino,
1393 INTEGER_TO_PY(st->st_dev),
1394 INTEGER_TO_PY(st->st_nlink),
1395 INTEGER_TO_PY(st->st_uid),
1396 INTEGER_TO_PY(st->st_gid),
1397 INTEGER_TO_PY(st->st_rdev),
1398 (PY_LONG_LONG) st->st_size,
1399 INTEGER_TO_PY(st->st_atime),
1400 (long) BUP_STAT_ATIME_NS(st),
1401 INTEGER_TO_PY(st->st_mtime),
1402 (long) BUP_STAT_MTIME_NS(st),
1403 INTEGER_TO_PY(st->st_ctime),
1404 (long) BUP_STAT_CTIME_NS(st));
1407 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1409 static PyObject *bup_stat(PyObject *self, PyObject *args)
1414 if (!PyArg_ParseTuple(args, "s", &filename))
1418 rc = stat(filename, &st);
1420 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1421 return stat_struct_to_py(&st, filename, 0);
1425 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1430 if (!PyArg_ParseTuple(args, "s", &filename))
1434 rc = lstat(filename, &st);
1436 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1437 return stat_struct_to_py(&st, filename, 0);
1441 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1445 if (!PyArg_ParseTuple(args, "i", &fd))
1449 rc = fstat(fd, &st);
1451 return PyErr_SetFromErrno(PyExc_OSError);
1452 return stat_struct_to_py(&st, NULL, fd);
1456 #ifdef HAVE_TM_TM_GMTOFF
1457 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1461 if (!PyArg_ParseTuple(args, "L", &lltime))
1463 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1464 return PyErr_Format(PyExc_OverflowError, "time value too large");
1468 if(localtime_r(&ttime, &tm) == NULL)
1469 return PyErr_SetFromErrno(PyExc_OSError);
1471 // Match the Python struct_time values.
1472 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1473 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1474 tm.tm_hour, tm.tm_min, tm.tm_sec,
1475 tm.tm_wday, tm.tm_yday + 1,
1476 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1478 #endif /* def HAVE_TM_TM_GMTOFF */
1481 #ifdef BUP_MINCORE_BUF_TYPE
1482 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1484 Py_buffer src, dest;
1485 PyObject *py_src_n, *py_src_off, *py_dest_off;
1487 if (!PyArg_ParseTuple(args, buf_argf "*OOw*O",
1488 &src, &py_src_n, &py_src_off,
1489 &dest, &py_dest_off))
1492 PyObject *result = NULL;
1494 unsigned long long src_n, src_off, dest_off;
1495 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1496 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1497 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1498 goto clean_and_return;
1500 unsigned long long src_region_end;
1501 if (!uadd(&src_region_end, src_off, src_n)) {
1502 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1503 goto clean_and_return;
1505 if (src_region_end > src.len) {
1506 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1507 goto clean_and_return;
1510 unsigned long long dest_size;
1511 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1512 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1513 goto clean_and_return;
1515 if (dest_off > dest_size) {
1516 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1517 goto clean_and_return;
1521 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1522 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1523 goto clean_and_return;
1525 int rc = mincore((void *)(src.buf + src_off), src_n,
1526 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1528 result = PyErr_SetFromErrno(PyExc_OSError);
1529 goto clean_and_return;
1531 result = Py_BuildValue("O", Py_None);
1534 PyBuffer_Release(&src);
1535 PyBuffer_Release(&dest);
1538 #endif /* def BUP_MINCORE_BUF_TYPE */
1541 static PyMethodDef helper_methods[] = {
1542 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1543 "Write buf excepting zeros at the end. Return trailing zero count." },
1544 { "selftest", selftest, METH_VARARGS,
1545 "Check that the rolling checksum rolls correctly (for unit tests)." },
1546 { "blobbits", blobbits, METH_VARARGS,
1547 "Return the number of bits in the rolling checksum." },
1548 { "splitbuf", splitbuf, METH_VARARGS,
1549 "Split a list of strings based on a rolling checksum." },
1550 { "bitmatch", bitmatch, METH_VARARGS,
1551 "Count the number of matching prefix bits between two strings." },
1552 { "firstword", firstword, METH_VARARGS,
1553 "Return an int corresponding to the first 32 bits of buf." },
1554 { "bloom_contains", bloom_contains, METH_VARARGS,
1555 "Check if a bloom filter of 2^nbits bytes contains an object" },
1556 { "bloom_add", bloom_add, METH_VARARGS,
1557 "Add an object to a bloom filter of 2^nbits bytes" },
1558 { "extract_bits", extract_bits, METH_VARARGS,
1559 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1560 { "merge_into", merge_into, METH_VARARGS,
1561 "Merges a bunch of idx and midx files into a single midx." },
1562 { "write_idx", write_idx, METH_VARARGS,
1563 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1564 { "write_random", write_random, METH_VARARGS,
1565 "Write random bytes to the given file descriptor" },
1566 { "random_sha", random_sha, METH_VARARGS,
1567 "Return a random 20-byte string" },
1568 { "open_noatime", open_noatime, METH_VARARGS,
1569 "open() the given filename for read with O_NOATIME if possible" },
1570 { "fadvise_done", fadvise_done, METH_VARARGS,
1571 "Inform the kernel that we're finished with earlier parts of a file" },
1572 #ifdef BUP_HAVE_FILE_ATTRS
1573 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1574 "Return the Linux attributes for the given file." },
1576 #ifdef BUP_HAVE_FILE_ATTRS
1577 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1578 "Set the Linux attributes for the given file." },
1580 #ifdef HAVE_UTIMENSAT
1581 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1582 "Change path timestamps with nanosecond precision (POSIX)." },
1585 { "bup_utimes", bup_utimes, METH_VARARGS,
1586 "Change path timestamps with microsecond precision." },
1589 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1590 "Change path timestamps with microsecond precision;"
1591 " don't follow symlinks." },
1593 { "stat", bup_stat, METH_VARARGS,
1594 "Extended version of stat." },
1595 { "lstat", bup_lstat, METH_VARARGS,
1596 "Extended version of lstat." },
1597 { "fstat", bup_fstat, METH_VARARGS,
1598 "Extended version of fstat." },
1599 #ifdef HAVE_TM_TM_GMTOFF
1600 { "localtime", bup_localtime, METH_VARARGS,
1601 "Return struct_time elements plus the timezone offset and name." },
1603 { "bytescmp", bup_bytescmp, METH_VARARGS,
1604 "Return a negative value if x < y, zero if equal, positive otherwise."},
1605 #ifdef BUP_MINCORE_BUF_TYPE
1606 { "mincore", bup_mincore, METH_VARARGS,
1607 "For mincore(src, src_n, src_off, dest, dest_off)"
1608 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1610 { NULL, NULL, 0, NULL }, // sentinel
1613 static int setup_module(PyObject *m)
1615 // FIXME: migrate these tests to configure, or at least don't
1616 // possibly crash the whole application. Check against the type
1617 // we're going to use when passing to python. Other stat types
1618 // are tested at runtime.
1619 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1620 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1621 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1622 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1623 // Just be sure (relevant when passing timestamps back to Python above).
1624 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1625 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1627 // Originally required by append_sparse_region()
1630 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1632 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1638 #pragma clang diagnostic push
1639 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1642 value = INTEGER_TO_PY(INT_MAX);
1643 PyObject_SetAttrString(m, "INT_MAX", value);
1645 value = INTEGER_TO_PY(UINT_MAX);
1646 PyObject_SetAttrString(m, "UINT_MAX", value);
1649 #ifdef HAVE_UTIMENSAT
1652 value = INTEGER_TO_PY(AT_FDCWD);
1653 PyObject_SetAttrString(m, "AT_FDCWD", value);
1655 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1656 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1658 value = INTEGER_TO_PY(UTIME_NOW);
1659 PyObject_SetAttrString(m, "UTIME_NOW", value);
1663 #ifdef BUP_HAVE_MINCORE_INCORE
1666 value = INTEGER_TO_PY(MINCORE_INCORE);
1667 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1671 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1673 e = getenv("BUP_FORCE_TTY");
1674 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1680 #if PY_MAJOR_VERSION < 3
1682 PyMODINIT_FUNC init_helpers(void)
1684 PyObject *m = Py_InitModule("_helpers", helper_methods);
1688 if (!setup_module(m))
1695 # else // PY_MAJOR_VERSION >= 3
1697 static struct PyModuleDef helpers_def = {
1698 PyModuleDef_HEAD_INIT,
1704 NULL, // helpers_traverse,
1705 NULL, // helpers_clear,
1709 PyMODINIT_FUNC PyInit__helpers(void)
1711 PyObject *module = PyModule_Create(&helpers_def);
1714 if (!setup_module(module))
1722 #endif // PY_MAJOR_VERSION >= 3