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_TYPES_H
21 #include <sys/types.h>
23 #ifdef HAVE_SYS_STAT_H
30 #ifdef HAVE_LINUX_FS_H
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
37 #ifdef HAVE_TM_TM_GMTOFF
43 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
44 #define BUP_HAVE_FILE_ATTRS 1
48 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
49 * pretend we don't have it.
51 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
56 // Of course, this assumes it's a bitfield value.
61 typedef unsigned char byte;
63 static int istty2 = 0;
67 // This function should technically be macro'd out if it's going to be used
68 // more than ocasionally. As of this writing, it'll actually never be called
69 // in real world bup scenarios (because our packs are < MAX_INT bytes).
70 static uint64_t htonll(uint64_t value)
72 static const int endian_test = 42;
74 if (*(char *)&endian_test == endian_test) // LSB-MSB
75 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
76 return value; // already in network byte order MSB-LSB
81 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
84 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
88 // At the moment any code that calls INTGER_TO_PY() will have to
89 // disable -Wtautological-compare for clang. See below.
91 #define INTEGER_TO_PY(x) \
92 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
95 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
98 const long tmp = PyInt_AsLong(py);
99 if (tmp == -1 && PyErr_Occurred())
101 if (PyErr_ExceptionMatches(PyExc_OverflowError))
102 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
108 PyErr_Format(PyExc_OverflowError,
109 "negative %s cannot be converted to unsigned long", name);
117 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
120 return bup_ulong_from_pyint(x, py, name);
122 if (!PyLong_Check(py))
124 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
128 const unsigned long tmp = PyLong_AsUnsignedLong(py);
129 if (PyErr_Occurred())
131 if (PyErr_ExceptionMatches(PyExc_OverflowError))
132 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
141 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
144 if (!bup_ulong_from_py(&tmp, py, name))
149 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
156 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
162 if (bup_ulong_from_pyint(&tmp, py, name))
170 if (!PyLong_Check(py))
172 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
176 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
177 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
179 if (PyErr_ExceptionMatches(PyExc_OverflowError))
180 PyErr_Format(PyExc_OverflowError,
181 "%s too big for unsigned long long", name);
189 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
190 #if __WIN32__ || __CYGWIN__
192 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
193 static void unpythonize_argv(void) { }
195 #else // not __WIN32__
197 // For some reason this isn't declared in Python.h
198 extern void Py_GetArgcArgv(int *argc, char ***argv);
200 static void unpythonize_argv(void)
205 Py_GetArgcArgv(&argc, &argv);
207 for (i = 0; i < argc-1; i++)
209 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
211 // The argv block doesn't work the way we expected; it's unsafe
217 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
219 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
223 p = strrchr(argv[1], '/');
229 memmove(argv[0], p, len);
230 memset(arge - diff, 0, diff);
231 for (i = 0; i < argc; i++)
232 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
237 #endif // not __WIN32__ or __CYGWIN__
240 static int write_all(int fd, const void *buf, const size_t count)
243 while (written < count)
245 const ssize_t rc = write(fd, buf + written, count - written);
254 static int uadd(unsigned long long *dest,
255 const unsigned long long x,
256 const unsigned long long y)
258 const unsigned long long result = x + y;
259 if (result < x || result < y)
266 static PyObject *append_sparse_region(const int fd, unsigned long long n)
271 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
273 const off_t off = lseek(fd, new_off, SEEK_CUR);
274 if (off == (off_t) -1)
275 return PyErr_SetFromErrno(PyExc_IOError);
282 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
284 unsigned long long prev_pending,
285 const unsigned long long count)
287 // Add count additional sparse zeros to prev_pending and store the
288 // result in new_pending, or if the total won't fit in
289 // new_pending, write some of the zeros to fd sparsely, and store
290 // the remaining sum in new_pending.
291 if (!uadd(new_pending, prev_pending, count))
293 PyObject *err = append_sparse_region(fd, prev_pending);
296 *new_pending = count;
302 static const byte * find_end_of_zero_run(const byte * const start,
303 const byte * const end)
305 // Return a pointer to first non-zero byte between start and end,
306 // or end if there isn't one.
307 assert(start <= end);
308 const unsigned char *cur = start;
309 while (cur < end && *cur == 0)
315 static const byte *find_non_sparse_end(const byte * const start,
316 const byte * const end,
317 const unsigned long long min_len)
319 // Return the first pointer to a min_len sparse block in [start,
320 // end) if there is one, otherwise a pointer to the start of any
321 // trailing run of zeros. If there are no trailing zeros, return
327 // Probe in min_len jumps, searching backward from the jump
328 // destination for a non-zero byte. If such a byte is found, move
329 // just past that byte and try again.
330 const byte *candidate = start;
331 ptrdiff_t known_trailing = 0;
332 while (end - candidate >= min_len)
334 const byte * const probe_region_end = candidate + min_len;
335 const byte *probe = probe_region_end - 1;
336 while (probe > candidate + known_trailing && *probe == 0)
338 if (probe == candidate + known_trailing && *probe == 0)
340 assert(candidate + min_len == probe_region_end);
344 // Skip past the probe and try again (remembering the leading zeros
345 // at the new location that we've already seen).
346 known_trailing = probe_region_end - probe - 1;
347 candidate = probe + 1;
349 // No min_len sparse run found, search backward from end for any
350 // trailing run of zeros.
351 const byte *probe = end - 1;
352 while (probe > candidate + known_trailing && *probe == 0)
356 if (probe == candidate + known_trailing && *probe == 0)
362 assert(*(result - 1) != 0);
365 assert(result >= start);
366 assert(result <= end);
367 assert(*result == 0);
373 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
376 unsigned char *buf = NULL;
378 PyObject *py_min_sparse_len, *py_prev_sparse_len;
379 if (!PyArg_ParseTuple(args, "it#OO",
380 &fd, &buf, &sbuf_len,
381 &py_min_sparse_len, &py_prev_sparse_len))
383 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
384 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
386 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
389 return PyErr_Format(PyExc_ValueError, "negative bufer length");
390 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
391 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
393 const byte * block = buf; // Start of pending block
394 const byte * const end = buf + buf_len;
395 unsigned long long zeros = prev_sparse_len;
398 assert(block <= end);
400 return PyLong_FromUnsignedLongLong(zeros);
404 // Look for the end of block, i.e. the next sparse run of
405 // at least min_sparse_len zeros, or the end of the
407 const byte * const probe = find_non_sparse_end(block + 1, end,
409 // Either at end of block, or end of non-sparse; write pending data
410 PyObject *err = append_sparse_region(fd, zeros);
413 int rc = write_all(fd, block, probe - block);
415 return PyErr_SetFromErrno(PyExc_IOError);
417 if (end - probe < min_sparse_len)
420 zeros = min_sparse_len;
421 block = probe + zeros;
425 // Should be in the first loop iteration, a sparse run of
426 // zeros, or nearly at the end of the block (within
428 const byte * const zeros_end = find_end_of_zero_run(block, end);
429 PyObject *err = record_sparse_zeros(&zeros, fd,
430 zeros, zeros_end - block);
433 assert(block <= zeros_end);
440 static PyObject *selftest(PyObject *self, PyObject *args)
442 if (!PyArg_ParseTuple(args, ""))
445 return Py_BuildValue("i", !bupsplit_selftest());
449 static PyObject *blobbits(PyObject *self, PyObject *args)
451 if (!PyArg_ParseTuple(args, ""))
453 return Py_BuildValue("i", BUP_BLOBBITS);
457 static PyObject *splitbuf(PyObject *self, PyObject *args)
459 unsigned char *buf = NULL;
461 int out = 0, bits = -1;
463 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
465 assert(len <= INT_MAX);
466 out = bupsplit_find_ofs(buf, len, &bits);
467 if (out) assert(bits >= BUP_BLOBBITS);
468 return Py_BuildValue("ii", out, bits);
472 static PyObject *bitmatch(PyObject *self, PyObject *args)
474 unsigned char *buf1 = NULL, *buf2 = NULL;
475 Py_ssize_t len1 = 0, len2 = 0;
479 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
483 for (byte = 0; byte < len1 && byte < len2; byte++)
485 int b1 = buf1[byte], b2 = buf2[byte];
488 for (bit = 0; bit < 8; bit++)
489 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
495 assert(byte <= (INT_MAX >> 3));
496 return Py_BuildValue("i", byte*8 + bit);
500 static PyObject *firstword(PyObject *self, PyObject *args)
502 unsigned char *buf = NULL;
506 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
512 v = ntohl(*(uint32_t *)buf);
513 return PyLong_FromUnsignedLong(v);
517 #define BLOOM2_HEADERLEN 16
519 static void to_bloom_address_bitmask4(const unsigned char *buf,
520 const int nbits, uint64_t *v, unsigned char *bitmask)
526 memcpy(&high, buf, 4);
527 mask = (1<<nbits) - 1;
528 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
529 bit = (raw >> (37-nbits)) & 0x7;
530 *v = (raw >> (40-nbits)) & mask;
534 static void to_bloom_address_bitmask5(const unsigned char *buf,
535 const int nbits, uint32_t *v, unsigned char *bitmask)
541 memcpy(&high, buf, 4);
542 mask = (1<<nbits) - 1;
544 bit = (raw >> (29-nbits)) & 0x7;
545 *v = (raw >> (32-nbits)) & mask;
549 #define BLOOM_SET_BIT(name, address, otype) \
550 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
552 unsigned char bitmask;\
554 address(buf, nbits, &v, &bitmask);\
555 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
557 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
558 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
561 #define BLOOM_GET_BIT(name, address, otype) \
562 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
564 unsigned char bitmask;\
566 address(buf, nbits, &v, &bitmask);\
567 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
569 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
570 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
573 static PyObject *bloom_add(PyObject *self, PyObject *args)
575 unsigned char *sha = NULL, *bloom = NULL;
577 Py_ssize_t len = 0, blen = 0;
578 int nbits = 0, k = 0;
580 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
583 if (blen < 16+(1<<nbits) || len % 20 != 0)
590 for (end = sha + len; sha < end; sha += 20/k)
591 bloom_set_bit5(bloom, sha, nbits);
597 for (end = sha + len; sha < end; sha += 20/k)
598 bloom_set_bit4(bloom, sha, nbits);
604 return Py_BuildValue("n", len/20);
607 static PyObject *bloom_contains(PyObject *self, PyObject *args)
609 unsigned char *sha = NULL, *bloom = NULL;
610 Py_ssize_t len = 0, blen = 0;
611 int nbits = 0, k = 0;
615 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
625 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
626 if (!bloom_get_bit5(bloom, sha, nbits))
627 return Py_BuildValue("Oi", Py_None, steps);
633 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
634 if (!bloom_get_bit4(bloom, sha, nbits))
635 return Py_BuildValue("Oi", Py_None, steps);
640 return Py_BuildValue("ii", 1, k);
644 static uint32_t _extract_bits(unsigned char *buf, int nbits)
648 mask = (1<<nbits) - 1;
649 v = ntohl(*(uint32_t *)buf);
650 v = (v >> (32-nbits)) & mask;
655 static PyObject *extract_bits(PyObject *self, PyObject *args)
657 unsigned char *buf = NULL;
661 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
667 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
672 unsigned char bytes[20];
686 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
689 for (i = 0; i < sizeof(struct sha); i++)
690 if (sha1->bytes[i] != sha2->bytes[i])
691 return sha1->bytes[i] - sha2->bytes[i];
696 static void _fix_idx_order(struct idx **idxs, int *last_i)
699 int low, mid, high, c = 0;
702 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
704 idxs[*last_i] = NULL;
717 mid = (low + high) / 2;
718 c = _cmp_sha(idx->cur, idxs[mid]->cur);
730 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
735 static uint32_t _get_idx_i(struct idx *idx)
737 if (idx->cur_name == NULL)
738 return idx->name_base;
739 return ntohl(*idx->cur_name) + idx->name_base;
742 #define MIDX4_HEADERLEN 12
744 static PyObject *merge_into(PyObject *self, PyObject *args)
746 PyObject *py_total, *ilist = NULL;
747 unsigned char *fmap = NULL;
748 struct sha *sha_ptr, *sha_start = NULL;
749 uint32_t *table_ptr, *name_ptr, *name_start;
750 struct idx **idxs = NULL;
754 uint32_t count, prefix;
758 if (!PyArg_ParseTuple(args, "w#iOO",
759 &fmap, &flen, &bits, &py_total, &ilist))
762 if (!bup_uint_from_py(&total, py_total, "total"))
765 num_i = PyList_Size(ilist);
766 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
768 for (i = 0; i < num_i; i++)
770 long len, sha_ofs, name_map_ofs;
771 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
772 PyObject *itup = PyList_GetItem(ilist, i);
773 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
774 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
776 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
777 idxs[i]->end = &idxs[i]->cur[len];
779 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
781 idxs[i]->cur_name = NULL;
783 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
784 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
785 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
794 if (count % 102424 == 0 && istty2)
795 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
796 count*100.0/total, count, total);
798 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
799 while (prefix < new_prefix)
800 table_ptr[prefix++] = htonl(count);
801 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
802 *name_ptr++ = htonl(_get_idx_i(idx));
804 if (idx->cur_name != NULL)
806 _fix_idx_order(idxs, &last_i);
809 while (prefix < (1<<bits))
810 table_ptr[prefix++] = htonl(count);
811 assert(count == total);
812 assert(prefix == (1<<bits));
813 assert(sha_ptr == sha_start+count);
814 assert(name_ptr == name_start+count);
817 return PyLong_FromUnsignedLong(count);
820 #define FAN_ENTRIES 256
822 static PyObject *write_idx(PyObject *self, PyObject *args)
824 char *filename = NULL;
825 PyObject *py_total, *idx = NULL;
827 unsigned char *fmap = NULL;
829 unsigned int total = 0;
831 int i, j, ofs64_count;
832 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
836 if (!PyArg_ParseTuple(args, "sw#OO",
837 &filename, &fmap, &flen, &idx, &py_total))
840 if (!bup_uint_from_py(&total, py_total, "total"))
843 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
844 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
847 const char idx_header[] = "\377tOc\0\0\0\002";
848 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
850 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
851 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
852 crc_ptr = (uint32_t *)&sha_ptr[total];
853 ofs_ptr = (uint32_t *)&crc_ptr[total];
854 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
858 for (i = 0; i < FAN_ENTRIES; ++i)
861 part = PyList_GET_ITEM(idx, i);
863 plen = PyList_GET_SIZE(part);
865 *fan_ptr++ = htonl(count);
866 for (j = 0; j < plen; ++j)
868 unsigned char *sha = NULL;
869 Py_ssize_t sha_len = 0;
870 PyObject *crc_py, *ofs_py;
872 unsigned PY_LONG_LONG ofs_ull;
874 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
875 &sha, &sha_len, &crc_py, &ofs_py))
877 if(!bup_uint_from_py(&crc, crc_py, "crc"))
879 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
881 assert(crc <= UINT32_MAX);
882 assert(ofs_ull <= UINT64_MAX);
884 if (sha_len != sizeof(struct sha))
886 memcpy(sha_ptr++, sha, sizeof(struct sha));
887 *crc_ptr++ = htonl(crc);
888 if (ofs > 0x7fffffff)
890 *ofs64_ptr++ = htonll(ofs);
891 ofs = 0x80000000 | ofs64_count++;
893 *ofs_ptr++ = htonl((uint32_t)ofs);
897 int rc = msync(fmap, flen, MS_ASYNC);
899 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
901 return PyLong_FromUnsignedLong(count);
905 // I would have made this a lower-level function that just fills in a buffer
906 // with random values, and then written those values from python. But that's
907 // about 20% slower in my tests, and since we typically generate random
908 // numbers for benchmarking other parts of bup, any slowness in generating
909 // random bytes will make our benchmarks inaccurate. Plus nobody wants
910 // pseudorandom bytes much except for this anyway.
911 static PyObject *write_random(PyObject *self, PyObject *args)
913 uint32_t buf[1024/4];
914 int fd = -1, seed = 0, verbose = 0;
916 long long len = 0, kbytes = 0, written = 0;
918 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
923 for (kbytes = 0; kbytes < len/1024; kbytes++)
926 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
928 ret = write(fd, buf, sizeof(buf));
932 if (ret < (int)sizeof(buf))
934 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
935 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
938 // handle non-multiples of 1024
942 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
944 ret = write(fd, buf, len % 1024);
951 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
952 return Py_BuildValue("L", written);
956 static PyObject *random_sha(PyObject *self, PyObject *args)
958 static int seeded = 0;
959 uint32_t shabuf[20/4];
964 assert(sizeof(shabuf) == 20);
969 if (!PyArg_ParseTuple(args, ""))
972 memset(shabuf, 0, sizeof(shabuf));
973 for (i=0; i < 20/4; i++)
974 shabuf[i] = random();
975 return Py_BuildValue("s#", shabuf, 20);
979 static int _open_noatime(const char *filename, int attrs)
981 int attrs_noatime, fd;
987 attrs |= O_LARGEFILE;
989 attrs_noatime = attrs;
991 attrs_noatime |= O_NOATIME;
993 fd = open(filename, attrs_noatime);
994 if (fd < 0 && errno == EPERM)
996 // older Linux kernels would return EPERM if you used O_NOATIME
997 // and weren't the file's owner. This pointless restriction was
998 // relaxed eventually, but we have to handle it anyway.
999 // (VERY old kernels didn't recognized O_NOATIME, but they would
1000 // just harmlessly ignore it, so this branch won't trigger)
1001 fd = open(filename, attrs);
1007 static PyObject *open_noatime(PyObject *self, PyObject *args)
1009 char *filename = NULL;
1011 if (!PyArg_ParseTuple(args, "s", &filename))
1013 fd = _open_noatime(filename, 0);
1015 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1016 return Py_BuildValue("i", fd);
1020 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1024 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
1026 #ifdef POSIX_FADV_DONTNEED
1027 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
1029 return Py_BuildValue("");
1033 // Currently the Linux kernel and FUSE disagree over the type for
1034 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1035 // but FUSE chose long (matching the declaration in linux/fs.h). So
1036 // if you use int, and then traverse a FUSE filesystem, you may
1037 // corrupt the stack. But if you use long, then you may get invalid
1038 // results on big-endian systems.
1040 // For now, we just use long, and then disable Linux attrs entirely
1041 // (with a warning) in helpers.py on systems that are affected.
1043 #ifdef BUP_HAVE_FILE_ATTRS
1044 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1051 if (!PyArg_ParseTuple(args, "s", &path))
1054 fd = _open_noatime(path, O_NONBLOCK);
1056 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1058 attr = 0; // Handle int/long mismatch (see above)
1059 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1063 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1066 assert(attr <= UINT_MAX); // Kernel type is actually int
1067 return PyLong_FromUnsignedLong(attr);
1069 #endif /* def BUP_HAVE_FILE_ATTRS */
1073 #ifdef BUP_HAVE_FILE_ATTRS
1074 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1077 unsigned long orig_attr;
1083 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1086 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1089 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1091 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1093 // Restrict attr to modifiable flags acdeijstuADST -- see
1094 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1095 // in pf.c flags_array[].
1096 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1097 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1098 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1099 | FS_TOPDIR_FL | FS_NOCOW_FL;
1101 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1102 orig_attr = 0; // Handle int/long mismatch (see above)
1103 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1104 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1108 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1110 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1112 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1116 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1120 return Py_BuildValue("O", Py_None);
1122 #endif /* def BUP_HAVE_FILE_ATTRS */
1125 #ifndef HAVE_UTIMENSAT
1127 #error "cannot find utimensat or utimes()"
1129 #ifndef HAVE_LUTIMES
1130 #error "cannot find utimensat or lutimes()"
1134 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1138 const long long lltmp = PyLong_AsLongLong(pylong); \
1139 if (lltmp == -1 && PyErr_Occurred()) \
1141 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1143 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1144 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1146 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1152 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1160 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1169 #ifdef HAVE_UTIMENSAT
1171 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1176 PyObject *access_py, *modification_py;
1177 struct timespec ts[2];
1179 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1182 &access_py, &(ts[0].tv_nsec),
1183 &modification_py, &(ts[1].tv_nsec),
1188 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1191 PyErr_SetString(PyExc_ValueError,
1192 "unable to convert access time seconds for utimensat");
1195 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1198 PyErr_SetString(PyExc_ValueError,
1199 "unable to convert modification time seconds for utimensat");
1202 rc = utimensat(fd, path, ts, flag);
1204 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1206 return Py_BuildValue("O", Py_None);
1209 #endif /* def HAVE_UTIMENSAT */
1212 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1214 static int bup_parse_xutimes_args(char **path,
1215 struct timeval tv[2],
1218 PyObject *access_py, *modification_py;
1219 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1221 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1223 &access_py, &access_us,
1224 &modification_py, &modification_us))
1228 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1231 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1234 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1236 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1239 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1242 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1245 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1247 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1253 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1257 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1260 struct timeval tv[2];
1261 if (!bup_parse_xutimes_args(&path, tv, args))
1263 int rc = utimes(path, tv);
1265 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1266 return Py_BuildValue("O", Py_None);
1268 #endif /* def HAVE_UTIMES */
1272 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1275 struct timeval tv[2];
1276 if (!bup_parse_xutimes_args(&path, tv, args))
1278 int rc = lutimes(path, tv);
1280 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1282 return Py_BuildValue("O", Py_None);
1284 #endif /* def HAVE_LUTIMES */
1287 #ifdef HAVE_STAT_ST_ATIM
1288 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1289 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1290 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1291 #elif defined HAVE_STAT_ST_ATIMENSEC
1292 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1293 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1294 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1296 # define BUP_STAT_ATIME_NS(st) 0
1297 # define BUP_STAT_MTIME_NS(st) 0
1298 # define BUP_STAT_CTIME_NS(st) 0
1302 #pragma clang diagnostic push
1303 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1305 static PyObject *stat_struct_to_py(const struct stat *st,
1306 const char *filename,
1309 // We can check the known (via POSIX) signed and unsigned types at
1310 // compile time, but not (easily) the unspecified types, so handle
1311 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1313 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1314 INTEGER_TO_PY(st->st_mode),
1315 (unsigned PY_LONG_LONG) st->st_ino,
1316 INTEGER_TO_PY(st->st_dev),
1317 INTEGER_TO_PY(st->st_nlink),
1318 INTEGER_TO_PY(st->st_uid),
1319 INTEGER_TO_PY(st->st_gid),
1320 INTEGER_TO_PY(st->st_rdev),
1321 (PY_LONG_LONG) st->st_size,
1322 INTEGER_TO_PY(st->st_atime),
1323 (long) BUP_STAT_ATIME_NS(st),
1324 INTEGER_TO_PY(st->st_mtime),
1325 (long) BUP_STAT_MTIME_NS(st),
1326 INTEGER_TO_PY(st->st_ctime),
1327 (long) BUP_STAT_CTIME_NS(st));
1330 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1332 static PyObject *bup_stat(PyObject *self, PyObject *args)
1337 if (!PyArg_ParseTuple(args, "s", &filename))
1341 rc = stat(filename, &st);
1343 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1344 return stat_struct_to_py(&st, filename, 0);
1348 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1353 if (!PyArg_ParseTuple(args, "s", &filename))
1357 rc = lstat(filename, &st);
1359 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1360 return stat_struct_to_py(&st, filename, 0);
1364 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1368 if (!PyArg_ParseTuple(args, "i", &fd))
1372 rc = fstat(fd, &st);
1374 return PyErr_SetFromErrno(PyExc_OSError);
1375 return stat_struct_to_py(&st, NULL, fd);
1379 #ifdef HAVE_TM_TM_GMTOFF
1380 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1384 if (!PyArg_ParseTuple(args, "L", &lltime))
1386 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1387 return PyErr_Format(PyExc_OverflowError, "time value too large");
1390 if(localtime_r(&ttime, &tm) == NULL)
1391 return PyErr_SetFromErrno(PyExc_OSError);
1393 // Match the Python struct_time values.
1394 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1395 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1396 tm.tm_hour, tm.tm_min, tm.tm_sec,
1397 tm.tm_wday, tm.tm_yday + 1,
1398 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1400 #endif /* def HAVE_TM_TM_GMTOFF */
1403 static PyMethodDef helper_methods[] = {
1404 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1405 "Write buf excepting zeros at the end. Return trailing zero count." },
1406 { "selftest", selftest, METH_VARARGS,
1407 "Check that the rolling checksum rolls correctly (for unit tests)." },
1408 { "blobbits", blobbits, METH_VARARGS,
1409 "Return the number of bits in the rolling checksum." },
1410 { "splitbuf", splitbuf, METH_VARARGS,
1411 "Split a list of strings based on a rolling checksum." },
1412 { "bitmatch", bitmatch, METH_VARARGS,
1413 "Count the number of matching prefix bits between two strings." },
1414 { "firstword", firstword, METH_VARARGS,
1415 "Return an int corresponding to the first 32 bits of buf." },
1416 { "bloom_contains", bloom_contains, METH_VARARGS,
1417 "Check if a bloom filter of 2^nbits bytes contains an object" },
1418 { "bloom_add", bloom_add, METH_VARARGS,
1419 "Add an object to a bloom filter of 2^nbits bytes" },
1420 { "extract_bits", extract_bits, METH_VARARGS,
1421 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1422 { "merge_into", merge_into, METH_VARARGS,
1423 "Merges a bunch of idx and midx files into a single midx." },
1424 { "write_idx", write_idx, METH_VARARGS,
1425 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1426 { "write_random", write_random, METH_VARARGS,
1427 "Write random bytes to the given file descriptor" },
1428 { "random_sha", random_sha, METH_VARARGS,
1429 "Return a random 20-byte string" },
1430 { "open_noatime", open_noatime, METH_VARARGS,
1431 "open() the given filename for read with O_NOATIME if possible" },
1432 { "fadvise_done", fadvise_done, METH_VARARGS,
1433 "Inform the kernel that we're finished with earlier parts of a file" },
1434 #ifdef BUP_HAVE_FILE_ATTRS
1435 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1436 "Return the Linux attributes for the given file." },
1438 #ifdef BUP_HAVE_FILE_ATTRS
1439 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1440 "Set the Linux attributes for the given file." },
1442 #ifdef HAVE_UTIMENSAT
1443 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1444 "Change path timestamps with nanosecond precision (POSIX)." },
1447 { "bup_utimes", bup_utimes, METH_VARARGS,
1448 "Change path timestamps with microsecond precision." },
1451 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1452 "Change path timestamps with microsecond precision;"
1453 " don't follow symlinks." },
1455 { "stat", bup_stat, METH_VARARGS,
1456 "Extended version of stat." },
1457 { "lstat", bup_lstat, METH_VARARGS,
1458 "Extended version of lstat." },
1459 { "fstat", bup_fstat, METH_VARARGS,
1460 "Extended version of fstat." },
1461 #ifdef HAVE_TM_TM_GMTOFF
1462 { "localtime", bup_localtime, METH_VARARGS,
1463 "Return struct_time elements plus the timezone offset and name." },
1465 { NULL, NULL, 0, NULL }, // sentinel
1469 PyMODINIT_FUNC init_helpers(void)
1471 // FIXME: migrate these tests to configure. Check against the
1472 // type we're going to use when passing to python. Other stat
1473 // types are tested at runtime.
1474 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1475 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1476 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1477 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1478 // Just be sure (relevant when passing timestamps back to Python above).
1479 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1480 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1482 // Originally required by append_sparse_region()
1485 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1487 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1493 PyObject *m = Py_InitModule("_helpers", helper_methods);
1497 #pragma clang diagnostic push
1498 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1499 #ifdef HAVE_UTIMENSAT
1502 value = INTEGER_TO_PY(AT_FDCWD);
1503 PyObject_SetAttrString(m, "AT_FDCWD", value);
1505 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1506 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1508 value = INTEGER_TO_PY(UTIME_NOW);
1509 PyObject_SetAttrString(m, "UTIME_NOW", value);
1515 const long arg_max = sysconf(_SC_ARG_MAX);
1518 fprintf(stderr, "Cannot find SC_ARG_MAX, please report a bug.\n");
1521 value = INTEGER_TO_PY(arg_max);
1522 PyObject_SetAttrString(m, "SC_ARG_MAX", value);
1525 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1527 e = getenv("BUP_FORCE_TTY");
1528 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);