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;
66 static int istty2 = 0;
70 // This function should technically be macro'd out if it's going to be used
71 // more than ocasionally. As of this writing, it'll actually never be called
72 // in real world bup scenarios (because our packs are < MAX_INT bytes).
73 static uint64_t htonll(uint64_t value)
75 static const int endian_test = 42;
77 if (*(char *)&endian_test == endian_test) // LSB-MSB
78 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
79 return value; // already in network byte order MSB-LSB
84 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
87 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
91 // At the moment any code that calls INTGER_TO_PY() will have to
92 // disable -Wtautological-compare for clang. See below.
94 #define INTEGER_TO_PY(x) \
95 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
98 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
101 const long tmp = PyInt_AsLong(py);
102 if (tmp == -1 && PyErr_Occurred())
104 if (PyErr_ExceptionMatches(PyExc_OverflowError))
105 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
111 PyErr_Format(PyExc_OverflowError,
112 "negative %s cannot be converted to unsigned long", name);
120 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
123 return bup_ulong_from_pyint(x, py, name);
125 if (!PyLong_Check(py))
127 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
131 const unsigned long tmp = PyLong_AsUnsignedLong(py);
132 if (PyErr_Occurred())
134 if (PyErr_ExceptionMatches(PyExc_OverflowError))
135 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
144 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
147 if (!bup_ulong_from_py(&tmp, py, name))
152 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
159 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
165 if (bup_ulong_from_pyint(&tmp, py, name))
173 if (!PyLong_Check(py))
175 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
179 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
180 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
182 if (PyErr_ExceptionMatches(PyExc_OverflowError))
183 PyErr_Format(PyExc_OverflowError,
184 "%s too big for unsigned long long", name);
192 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
194 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
195 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
198 Py_ssize_t s1_len, s2_len;
199 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
201 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
203 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
204 const int cmp = memcmp(s1, s2, n);
206 return PyLong_FromLong(cmp);
207 if (s1_len == s2_len)
208 return PyLong_FromLong(0);;
209 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
213 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
214 #if __WIN32__ || __CYGWIN__
216 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
217 static void unpythonize_argv(void) { }
219 #else // not __WIN32__
221 // For some reason this isn't declared in Python.h
222 extern void Py_GetArgcArgv(int *argc, char ***argv);
224 static void unpythonize_argv(void)
229 Py_GetArgcArgv(&argc, &argv);
231 for (i = 0; i < argc-1; i++)
233 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
235 // The argv block doesn't work the way we expected; it's unsafe
241 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
243 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
247 p = strrchr(argv[1], '/');
253 memmove(argv[0], p, len);
254 memset(arge - diff, 0, diff);
255 for (i = 0; i < argc; i++)
256 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
261 #endif // not __WIN32__ or __CYGWIN__
264 static int write_all(int fd, const void *buf, const size_t count)
267 while (written < count)
269 const ssize_t rc = write(fd, buf + written, count - written);
278 static int uadd(unsigned long long *dest,
279 const unsigned long long x,
280 const unsigned long long y)
282 const unsigned long long result = x + y;
283 if (result < x || result < y)
290 static PyObject *append_sparse_region(const int fd, unsigned long long n)
295 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
297 const off_t off = lseek(fd, new_off, SEEK_CUR);
298 if (off == (off_t) -1)
299 return PyErr_SetFromErrno(PyExc_IOError);
306 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
308 unsigned long long prev_pending,
309 const unsigned long long count)
311 // Add count additional sparse zeros to prev_pending and store the
312 // result in new_pending, or if the total won't fit in
313 // new_pending, write some of the zeros to fd sparsely, and store
314 // the remaining sum in new_pending.
315 if (!uadd(new_pending, prev_pending, count))
317 PyObject *err = append_sparse_region(fd, prev_pending);
320 *new_pending = count;
326 static byte* find_not_zero(const byte * const start, const byte * const end)
328 // Return a pointer to first non-zero byte between start and end,
329 // or end if there isn't one.
330 assert(start <= end);
331 const unsigned char *cur = start;
332 while (cur < end && *cur == 0)
338 static byte* find_trailing_zeros(const byte * const start,
339 const byte * const end)
341 // Return a pointer to the start of any trailing run of zeros, or
342 // end if there isn't one.
343 assert(start <= end);
346 const byte * cur = end;
347 while (cur > start && *--cur == 0) {}
351 return (byte *) (cur + 1);
355 static byte *find_non_sparse_end(const byte * const start,
356 const byte * const end,
357 const unsigned long long min_len)
359 // Return the first pointer to a min_len sparse block in [start,
360 // end) if there is one, otherwise a pointer to the start of any
361 // trailing run of zeros. If there are no trailing zeros, return
367 // Probe in min_len jumps, searching backward from the jump
368 // destination for a non-zero byte. If such a byte is found, move
369 // just past it and try again.
370 const byte *candidate = start;
371 // End of any run of zeros, starting at candidate, that we've already seen
372 const byte *end_of_known_zeros = candidate;
373 while (end - candidate >= min_len) // Handle all min_len candidate blocks
375 const byte * const probe_end = candidate + min_len;
376 const byte * const trailing_zeros =
377 find_trailing_zeros(end_of_known_zeros, probe_end);
378 if (trailing_zeros == probe_end)
379 end_of_known_zeros = candidate = probe_end;
380 else if (trailing_zeros == end_of_known_zeros)
382 assert(candidate >= start);
383 assert(candidate <= end);
384 assert(*candidate == 0);
385 return (byte *) candidate;
389 candidate = trailing_zeros;
390 end_of_known_zeros = probe_end;
394 if (candidate == end)
397 // No min_len sparse run found, search backward from end
398 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
401 if (trailing_zeros == end_of_known_zeros)
403 assert(candidate >= start);
404 assert(candidate < end);
405 assert(*candidate == 0);
406 assert(end - candidate < min_len);
407 return (byte *) candidate;
410 if (trailing_zeros == end)
412 assert(*(end - 1) != 0);
416 assert(end - trailing_zeros < min_len);
417 assert(trailing_zeros >= start);
418 assert(trailing_zeros < end);
419 assert(*trailing_zeros == 0);
420 return (byte *) trailing_zeros;
424 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
427 unsigned char *buf = NULL;
429 PyObject *py_min_sparse_len, *py_prev_sparse_len;
430 if (!PyArg_ParseTuple(args, "it#OO",
431 &fd, &buf, &sbuf_len,
432 &py_min_sparse_len, &py_prev_sparse_len))
434 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
435 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
437 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
440 return PyErr_Format(PyExc_ValueError, "negative bufer length");
441 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
442 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
444 const byte * block = buf; // Start of pending block
445 const byte * const end = buf + buf_len;
446 unsigned long long zeros = prev_sparse_len;
449 assert(block <= end);
451 return PyLong_FromUnsignedLongLong(zeros);
455 // Look for the end of block, i.e. the next sparse run of
456 // at least min_sparse_len zeros, or the end of the
458 const byte * const probe = find_non_sparse_end(block + 1, end,
460 // Either at end of block, or end of non-sparse; write pending data
461 PyObject *err = append_sparse_region(fd, zeros);
464 int rc = write_all(fd, block, probe - block);
466 return PyErr_SetFromErrno(PyExc_IOError);
468 if (end - probe < min_sparse_len)
471 zeros = min_sparse_len;
472 block = probe + zeros;
476 // Should be in the first loop iteration, a sparse run of
477 // zeros, or nearly at the end of the block (within
479 const byte * const zeros_end = find_not_zero(block, end);
480 PyObject *err = record_sparse_zeros(&zeros, fd,
481 zeros, zeros_end - block);
484 assert(block <= zeros_end);
491 static PyObject *selftest(PyObject *self, PyObject *args)
493 if (!PyArg_ParseTuple(args, ""))
496 return Py_BuildValue("i", !bupsplit_selftest());
500 static PyObject *blobbits(PyObject *self, PyObject *args)
502 if (!PyArg_ParseTuple(args, ""))
504 return Py_BuildValue("i", BUP_BLOBBITS);
508 static PyObject *splitbuf(PyObject *self, PyObject *args)
510 unsigned char *buf = NULL;
512 int out = 0, bits = -1;
514 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
516 assert(len <= INT_MAX);
517 out = bupsplit_find_ofs(buf, len, &bits);
518 if (out) assert(bits >= BUP_BLOBBITS);
519 return Py_BuildValue("ii", out, bits);
523 static PyObject *bitmatch(PyObject *self, PyObject *args)
525 unsigned char *buf1 = NULL, *buf2 = NULL;
526 Py_ssize_t len1 = 0, len2 = 0;
530 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
534 for (byte = 0; byte < len1 && byte < len2; byte++)
536 int b1 = buf1[byte], b2 = buf2[byte];
539 for (bit = 0; bit < 8; bit++)
540 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
546 assert(byte <= (INT_MAX >> 3));
547 return Py_BuildValue("i", byte*8 + bit);
551 static PyObject *firstword(PyObject *self, PyObject *args)
553 unsigned char *buf = NULL;
557 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
563 v = ntohl(*(uint32_t *)buf);
564 return PyLong_FromUnsignedLong(v);
568 #define BLOOM2_HEADERLEN 16
570 static void to_bloom_address_bitmask4(const unsigned char *buf,
571 const int nbits, uint64_t *v, unsigned char *bitmask)
577 memcpy(&high, buf, 4);
578 mask = (1<<nbits) - 1;
579 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
580 bit = (raw >> (37-nbits)) & 0x7;
581 *v = (raw >> (40-nbits)) & mask;
585 static void to_bloom_address_bitmask5(const unsigned char *buf,
586 const int nbits, uint32_t *v, unsigned char *bitmask)
592 memcpy(&high, buf, 4);
593 mask = (1<<nbits) - 1;
595 bit = (raw >> (29-nbits)) & 0x7;
596 *v = (raw >> (32-nbits)) & mask;
600 #define BLOOM_SET_BIT(name, address, otype) \
601 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
603 unsigned char bitmask;\
605 address(buf, nbits, &v, &bitmask);\
606 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
608 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
609 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
612 #define BLOOM_GET_BIT(name, address, otype) \
613 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
615 unsigned char bitmask;\
617 address(buf, nbits, &v, &bitmask);\
618 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
620 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
621 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
624 static PyObject *bloom_add(PyObject *self, PyObject *args)
626 unsigned char *sha = NULL, *bloom = NULL;
628 Py_ssize_t len = 0, blen = 0;
629 int nbits = 0, k = 0;
631 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
634 if (blen < 16+(1<<nbits) || len % 20 != 0)
641 for (end = sha + len; sha < end; sha += 20/k)
642 bloom_set_bit5(bloom, sha, nbits);
648 for (end = sha + len; sha < end; sha += 20/k)
649 bloom_set_bit4(bloom, sha, nbits);
655 return Py_BuildValue("n", len/20);
658 static PyObject *bloom_contains(PyObject *self, PyObject *args)
660 unsigned char *sha = NULL, *bloom = NULL;
661 Py_ssize_t len = 0, blen = 0;
662 int nbits = 0, k = 0;
666 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
676 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
677 if (!bloom_get_bit5(bloom, sha, nbits))
678 return Py_BuildValue("Oi", Py_None, steps);
684 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
685 if (!bloom_get_bit4(bloom, sha, nbits))
686 return Py_BuildValue("Oi", Py_None, steps);
691 return Py_BuildValue("ii", 1, k);
695 static uint32_t _extract_bits(unsigned char *buf, int nbits)
699 mask = (1<<nbits) - 1;
700 v = ntohl(*(uint32_t *)buf);
701 v = (v >> (32-nbits)) & mask;
706 static PyObject *extract_bits(PyObject *self, PyObject *args)
708 unsigned char *buf = NULL;
712 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
718 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
723 unsigned char bytes[20];
737 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
740 for (i = 0; i < sizeof(struct sha); i++)
741 if (sha1->bytes[i] != sha2->bytes[i])
742 return sha1->bytes[i] - sha2->bytes[i];
747 static void _fix_idx_order(struct idx **idxs, int *last_i)
750 int low, mid, high, c = 0;
753 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
755 idxs[*last_i] = NULL;
768 mid = (low + high) / 2;
769 c = _cmp_sha(idx->cur, idxs[mid]->cur);
781 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
786 static uint32_t _get_idx_i(struct idx *idx)
788 if (idx->cur_name == NULL)
789 return idx->name_base;
790 return ntohl(*idx->cur_name) + idx->name_base;
793 #define MIDX4_HEADERLEN 12
795 static PyObject *merge_into(PyObject *self, PyObject *args)
797 PyObject *py_total, *ilist = NULL;
798 unsigned char *fmap = NULL;
799 struct sha *sha_ptr, *sha_start = NULL;
800 uint32_t *table_ptr, *name_ptr, *name_start;
801 struct idx **idxs = NULL;
805 uint32_t count, prefix;
809 if (!PyArg_ParseTuple(args, "w#iOO",
810 &fmap, &flen, &bits, &py_total, &ilist))
813 if (!bup_uint_from_py(&total, py_total, "total"))
816 num_i = PyList_Size(ilist);
817 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
819 for (i = 0; i < num_i; i++)
821 long len, sha_ofs, name_map_ofs;
822 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
823 PyObject *itup = PyList_GetItem(ilist, i);
824 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
825 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
827 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
828 idxs[i]->end = &idxs[i]->cur[len];
830 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
832 idxs[i]->cur_name = NULL;
834 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
835 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
836 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
845 if (count % 102424 == 0 && istty2)
846 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
847 count*100.0/total, count, total);
849 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
850 while (prefix < new_prefix)
851 table_ptr[prefix++] = htonl(count);
852 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
853 *name_ptr++ = htonl(_get_idx_i(idx));
855 if (idx->cur_name != NULL)
857 _fix_idx_order(idxs, &last_i);
860 while (prefix < (1<<bits))
861 table_ptr[prefix++] = htonl(count);
862 assert(count == total);
863 assert(prefix == (1<<bits));
864 assert(sha_ptr == sha_start+count);
865 assert(name_ptr == name_start+count);
868 return PyLong_FromUnsignedLong(count);
871 #define FAN_ENTRIES 256
873 static PyObject *write_idx(PyObject *self, PyObject *args)
875 char *filename = NULL;
876 PyObject *py_total, *idx = NULL;
878 unsigned char *fmap = NULL;
880 unsigned int total = 0;
882 int i, j, ofs64_count;
883 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
887 if (!PyArg_ParseTuple(args, "sw#OO",
888 &filename, &fmap, &flen, &idx, &py_total))
891 if (!bup_uint_from_py(&total, py_total, "total"))
894 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
895 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
898 const char idx_header[] = "\377tOc\0\0\0\002";
899 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
901 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
902 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
903 crc_ptr = (uint32_t *)&sha_ptr[total];
904 ofs_ptr = (uint32_t *)&crc_ptr[total];
905 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
909 for (i = 0; i < FAN_ENTRIES; ++i)
912 part = PyList_GET_ITEM(idx, i);
914 plen = PyList_GET_SIZE(part);
916 *fan_ptr++ = htonl(count);
917 for (j = 0; j < plen; ++j)
919 unsigned char *sha = NULL;
920 Py_ssize_t sha_len = 0;
921 PyObject *crc_py, *ofs_py;
923 unsigned PY_LONG_LONG ofs_ull;
925 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
926 &sha, &sha_len, &crc_py, &ofs_py))
928 if(!bup_uint_from_py(&crc, crc_py, "crc"))
930 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
932 assert(crc <= UINT32_MAX);
933 assert(ofs_ull <= UINT64_MAX);
935 if (sha_len != sizeof(struct sha))
937 memcpy(sha_ptr++, sha, sizeof(struct sha));
938 *crc_ptr++ = htonl(crc);
939 if (ofs > 0x7fffffff)
941 *ofs64_ptr++ = htonll(ofs);
942 ofs = 0x80000000 | ofs64_count++;
944 *ofs_ptr++ = htonl((uint32_t)ofs);
948 int rc = msync(fmap, flen, MS_ASYNC);
950 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
952 return PyLong_FromUnsignedLong(count);
956 // I would have made this a lower-level function that just fills in a buffer
957 // with random values, and then written those values from python. But that's
958 // about 20% slower in my tests, and since we typically generate random
959 // numbers for benchmarking other parts of bup, any slowness in generating
960 // random bytes will make our benchmarks inaccurate. Plus nobody wants
961 // pseudorandom bytes much except for this anyway.
962 static PyObject *write_random(PyObject *self, PyObject *args)
964 uint32_t buf[1024/4];
965 int fd = -1, seed = 0, verbose = 0;
967 long long len = 0, kbytes = 0, written = 0;
969 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
974 for (kbytes = 0; kbytes < len/1024; kbytes++)
977 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
979 ret = write(fd, buf, sizeof(buf));
983 if (ret < (int)sizeof(buf))
985 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
986 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
989 // handle non-multiples of 1024
993 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
995 ret = write(fd, buf, len % 1024);
1001 if (kbytes/1024 > 0)
1002 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1003 return Py_BuildValue("L", written);
1007 static PyObject *random_sha(PyObject *self, PyObject *args)
1009 static int seeded = 0;
1010 uint32_t shabuf[20/4];
1015 assert(sizeof(shabuf) == 20);
1016 srandom(time(NULL));
1020 if (!PyArg_ParseTuple(args, ""))
1023 memset(shabuf, 0, sizeof(shabuf));
1024 for (i=0; i < 20/4; i++)
1025 shabuf[i] = random();
1026 return Py_BuildValue("s#", shabuf, 20);
1030 static int _open_noatime(const char *filename, int attrs)
1032 int attrs_noatime, fd;
1035 attrs |= O_NOFOLLOW;
1038 attrs |= O_LARGEFILE;
1040 attrs_noatime = attrs;
1042 attrs_noatime |= O_NOATIME;
1044 fd = open(filename, attrs_noatime);
1045 if (fd < 0 && errno == EPERM)
1047 // older Linux kernels would return EPERM if you used O_NOATIME
1048 // and weren't the file's owner. This pointless restriction was
1049 // relaxed eventually, but we have to handle it anyway.
1050 // (VERY old kernels didn't recognized O_NOATIME, but they would
1051 // just harmlessly ignore it, so this branch won't trigger)
1052 fd = open(filename, attrs);
1058 static PyObject *open_noatime(PyObject *self, PyObject *args)
1060 char *filename = NULL;
1062 if (!PyArg_ParseTuple(args, "s", &filename))
1064 fd = _open_noatime(filename, 0);
1066 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1067 return Py_BuildValue("i", fd);
1071 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1074 long long llofs, lllen = 0;
1075 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1078 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1079 return PyErr_Format(PyExc_OverflowError,
1080 "fadvise offset overflows off_t");
1081 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1082 return PyErr_Format(PyExc_OverflowError,
1083 "fadvise length overflows off_t");
1084 #ifdef POSIX_FADV_DONTNEED
1085 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1087 return Py_BuildValue("");
1091 // Currently the Linux kernel and FUSE disagree over the type for
1092 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1093 // but FUSE chose long (matching the declaration in linux/fs.h). So
1094 // if you use int, and then traverse a FUSE filesystem, you may
1095 // corrupt the stack. But if you use long, then you may get invalid
1096 // results on big-endian systems.
1098 // For now, we just use long, and then disable Linux attrs entirely
1099 // (with a warning) in helpers.py on systems that are affected.
1101 #ifdef BUP_HAVE_FILE_ATTRS
1102 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1109 if (!PyArg_ParseTuple(args, "s", &path))
1112 fd = _open_noatime(path, O_NONBLOCK);
1114 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1116 attr = 0; // Handle int/long mismatch (see above)
1117 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1121 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1124 assert(attr <= UINT_MAX); // Kernel type is actually int
1125 return PyLong_FromUnsignedLong(attr);
1127 #endif /* def BUP_HAVE_FILE_ATTRS */
1131 #ifdef BUP_HAVE_FILE_ATTRS
1132 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1135 unsigned long orig_attr;
1141 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1144 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1147 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1149 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1151 // Restrict attr to modifiable flags acdeijstuADST -- see
1152 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1153 // in pf.c flags_array[].
1154 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1155 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1156 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1157 | FS_TOPDIR_FL | FS_NOCOW_FL;
1159 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1160 orig_attr = 0; // Handle int/long mismatch (see above)
1161 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1165 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1167 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1168 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1170 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1174 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1178 return Py_BuildValue("O", Py_None);
1180 #endif /* def BUP_HAVE_FILE_ATTRS */
1183 #ifndef HAVE_UTIMENSAT
1185 #error "cannot find utimensat or utimes()"
1187 #ifndef HAVE_LUTIMES
1188 #error "cannot find utimensat or lutimes()"
1192 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1196 const long long lltmp = PyLong_AsLongLong(pylong); \
1197 if (lltmp == -1 && PyErr_Occurred()) \
1199 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1201 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1202 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1204 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1210 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1218 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1227 #ifdef HAVE_UTIMENSAT
1229 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1234 PyObject *access_py, *modification_py;
1235 struct timespec ts[2];
1237 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1240 &access_py, &(ts[0].tv_nsec),
1241 &modification_py, &(ts[1].tv_nsec),
1246 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1249 PyErr_SetString(PyExc_ValueError,
1250 "unable to convert access time seconds for utimensat");
1253 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1256 PyErr_SetString(PyExc_ValueError,
1257 "unable to convert modification time seconds for utimensat");
1260 rc = utimensat(fd, path, ts, flag);
1262 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1264 return Py_BuildValue("O", Py_None);
1267 #endif /* def HAVE_UTIMENSAT */
1270 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1272 static int bup_parse_xutimes_args(char **path,
1273 struct timeval tv[2],
1276 PyObject *access_py, *modification_py;
1277 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1279 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1281 &access_py, &access_us,
1282 &modification_py, &modification_us))
1286 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1289 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1292 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1294 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1297 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1300 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1303 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1305 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1311 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1315 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1318 struct timeval tv[2];
1319 if (!bup_parse_xutimes_args(&path, tv, args))
1321 int rc = utimes(path, tv);
1323 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1324 return Py_BuildValue("O", Py_None);
1326 #endif /* def HAVE_UTIMES */
1330 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1333 struct timeval tv[2];
1334 if (!bup_parse_xutimes_args(&path, tv, args))
1336 int rc = lutimes(path, tv);
1338 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1340 return Py_BuildValue("O", Py_None);
1342 #endif /* def HAVE_LUTIMES */
1345 #ifdef HAVE_STAT_ST_ATIM
1346 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1347 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1348 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1349 #elif defined HAVE_STAT_ST_ATIMENSEC
1350 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1351 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1352 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1354 # define BUP_STAT_ATIME_NS(st) 0
1355 # define BUP_STAT_MTIME_NS(st) 0
1356 # define BUP_STAT_CTIME_NS(st) 0
1360 #pragma clang diagnostic push
1361 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1363 static PyObject *stat_struct_to_py(const struct stat *st,
1364 const char *filename,
1367 // We can check the known (via POSIX) signed and unsigned types at
1368 // compile time, but not (easily) the unspecified types, so handle
1369 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1371 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1372 INTEGER_TO_PY(st->st_mode),
1373 (unsigned PY_LONG_LONG) st->st_ino,
1374 INTEGER_TO_PY(st->st_dev),
1375 INTEGER_TO_PY(st->st_nlink),
1376 INTEGER_TO_PY(st->st_uid),
1377 INTEGER_TO_PY(st->st_gid),
1378 INTEGER_TO_PY(st->st_rdev),
1379 (PY_LONG_LONG) st->st_size,
1380 INTEGER_TO_PY(st->st_atime),
1381 (long) BUP_STAT_ATIME_NS(st),
1382 INTEGER_TO_PY(st->st_mtime),
1383 (long) BUP_STAT_MTIME_NS(st),
1384 INTEGER_TO_PY(st->st_ctime),
1385 (long) BUP_STAT_CTIME_NS(st));
1388 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1390 static PyObject *bup_stat(PyObject *self, PyObject *args)
1395 if (!PyArg_ParseTuple(args, "s", &filename))
1399 rc = stat(filename, &st);
1401 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1402 return stat_struct_to_py(&st, filename, 0);
1406 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1411 if (!PyArg_ParseTuple(args, "s", &filename))
1415 rc = lstat(filename, &st);
1417 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1418 return stat_struct_to_py(&st, filename, 0);
1422 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1426 if (!PyArg_ParseTuple(args, "i", &fd))
1430 rc = fstat(fd, &st);
1432 return PyErr_SetFromErrno(PyExc_OSError);
1433 return stat_struct_to_py(&st, NULL, fd);
1437 #ifdef HAVE_TM_TM_GMTOFF
1438 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1442 if (!PyArg_ParseTuple(args, "L", &lltime))
1444 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1445 return PyErr_Format(PyExc_OverflowError, "time value too large");
1449 if(localtime_r(&ttime, &tm) == NULL)
1450 return PyErr_SetFromErrno(PyExc_OSError);
1452 // Match the Python struct_time values.
1453 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1454 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1455 tm.tm_hour, tm.tm_min, tm.tm_sec,
1456 tm.tm_wday, tm.tm_yday + 1,
1457 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1459 #endif /* def HAVE_TM_TM_GMTOFF */
1462 #ifdef BUP_MINCORE_BUF_TYPE
1463 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1466 Py_ssize_t src_ssize;
1468 PyObject *py_src_n, *py_src_off, *py_dest_off;
1469 if (!PyArg_ParseTuple(args, "s#OOw*O",
1470 &src, &src_ssize, &py_src_n, &py_src_off,
1471 &dest, &py_dest_off))
1474 unsigned long long src_size, src_n, src_off, dest_size, dest_off;
1475 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1476 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1477 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1480 if (!INTEGRAL_ASSIGNMENT_FITS(&src_size, src_ssize))
1481 return PyErr_Format(PyExc_OverflowError, "invalid src size");
1482 unsigned long long src_region_end;
1484 if (!uadd(&src_region_end, src_off, src_n))
1485 return PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1486 if (src_region_end > src_size)
1487 return PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1489 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len))
1490 return PyErr_Format(PyExc_OverflowError, "invalid dest size");
1491 if (dest_off > dest_size)
1492 return PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1495 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n))
1496 return PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1497 int rc = mincore((void *)(src + src_off), src_n,
1498 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1500 return PyErr_SetFromErrno(PyExc_OSError);
1501 return Py_BuildValue("O", Py_None);
1503 #endif /* def BUP_MINCORE_BUF_TYPE */
1506 static PyMethodDef helper_methods[] = {
1507 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1508 "Write buf excepting zeros at the end. Return trailing zero count." },
1509 { "selftest", selftest, METH_VARARGS,
1510 "Check that the rolling checksum rolls correctly (for unit tests)." },
1511 { "blobbits", blobbits, METH_VARARGS,
1512 "Return the number of bits in the rolling checksum." },
1513 { "splitbuf", splitbuf, METH_VARARGS,
1514 "Split a list of strings based on a rolling checksum." },
1515 { "bitmatch", bitmatch, METH_VARARGS,
1516 "Count the number of matching prefix bits between two strings." },
1517 { "firstword", firstword, METH_VARARGS,
1518 "Return an int corresponding to the first 32 bits of buf." },
1519 { "bloom_contains", bloom_contains, METH_VARARGS,
1520 "Check if a bloom filter of 2^nbits bytes contains an object" },
1521 { "bloom_add", bloom_add, METH_VARARGS,
1522 "Add an object to a bloom filter of 2^nbits bytes" },
1523 { "extract_bits", extract_bits, METH_VARARGS,
1524 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1525 { "merge_into", merge_into, METH_VARARGS,
1526 "Merges a bunch of idx and midx files into a single midx." },
1527 { "write_idx", write_idx, METH_VARARGS,
1528 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1529 { "write_random", write_random, METH_VARARGS,
1530 "Write random bytes to the given file descriptor" },
1531 { "random_sha", random_sha, METH_VARARGS,
1532 "Return a random 20-byte string" },
1533 { "open_noatime", open_noatime, METH_VARARGS,
1534 "open() the given filename for read with O_NOATIME if possible" },
1535 { "fadvise_done", fadvise_done, METH_VARARGS,
1536 "Inform the kernel that we're finished with earlier parts of a file" },
1537 #ifdef BUP_HAVE_FILE_ATTRS
1538 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1539 "Return the Linux attributes for the given file." },
1541 #ifdef BUP_HAVE_FILE_ATTRS
1542 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1543 "Set the Linux attributes for the given file." },
1545 #ifdef HAVE_UTIMENSAT
1546 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1547 "Change path timestamps with nanosecond precision (POSIX)." },
1550 { "bup_utimes", bup_utimes, METH_VARARGS,
1551 "Change path timestamps with microsecond precision." },
1554 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1555 "Change path timestamps with microsecond precision;"
1556 " don't follow symlinks." },
1558 { "stat", bup_stat, METH_VARARGS,
1559 "Extended version of stat." },
1560 { "lstat", bup_lstat, METH_VARARGS,
1561 "Extended version of lstat." },
1562 { "fstat", bup_fstat, METH_VARARGS,
1563 "Extended version of fstat." },
1564 #ifdef HAVE_TM_TM_GMTOFF
1565 { "localtime", bup_localtime, METH_VARARGS,
1566 "Return struct_time elements plus the timezone offset and name." },
1568 { "bytescmp", bup_bytescmp, METH_VARARGS,
1569 "Return a negative value if x < y, zero if equal, positive otherwise."},
1570 #ifdef BUP_MINCORE_BUF_TYPE
1571 { "mincore", bup_mincore, METH_VARARGS,
1572 "For mincore(src, src_n, src_off, dest, dest_off)"
1573 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1575 { NULL, NULL, 0, NULL }, // sentinel
1579 PyMODINIT_FUNC init_helpers(void)
1581 // FIXME: migrate these tests to configure. Check against the
1582 // type we're going to use when passing to python. Other stat
1583 // types are tested at runtime.
1584 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1585 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1586 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1587 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1588 // Just be sure (relevant when passing timestamps back to Python above).
1589 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1590 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1592 // Originally required by append_sparse_region()
1595 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1597 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1603 PyObject *m = Py_InitModule("_helpers", helper_methods);
1607 #pragma clang diagnostic push
1608 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1611 value = INTEGER_TO_PY(INT_MAX);
1612 PyObject_SetAttrString(m, "INT_MAX", value);
1614 value = INTEGER_TO_PY(UINT_MAX);
1615 PyObject_SetAttrString(m, "UINT_MAX", value);
1618 #ifdef HAVE_UTIMENSAT
1621 value = INTEGER_TO_PY(AT_FDCWD);
1622 PyObject_SetAttrString(m, "AT_FDCWD", value);
1624 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1625 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1627 value = INTEGER_TO_PY(UTIME_NOW);
1628 PyObject_SetAttrString(m, "UTIME_NOW", value);
1632 #ifdef BUP_HAVE_MINCORE_INCORE
1635 value = INTEGER_TO_PY(MINCORE_INCORE);
1636 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1640 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1642 e = getenv("BUP_FORCE_TTY");
1643 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);