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>
18 #ifdef HAVE_SYS_MMAN_H
21 #ifdef HAVE_SYS_TYPES_H
22 #include <sys/types.h>
24 #ifdef HAVE_SYS_STAT_H
31 #ifdef HAVE_LINUX_FS_H
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
38 #ifdef HAVE_TM_TM_GMTOFF
44 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
45 #define BUP_HAVE_FILE_ATTRS 1
49 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
50 * pretend we don't have it.
52 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
57 // Of course, this assumes it's a bitfield value.
61 static int istty2 = 0;
65 // This function should technically be macro'd out if it's going to be used
66 // more than ocasionally. As of this writing, it'll actually never be called
67 // in real world bup scenarios (because our packs are < MAX_INT bytes).
68 static uint64_t htonll(uint64_t value)
70 static const int endian_test = 42;
72 if (*(char *)&endian_test == endian_test) // LSB-MSB
73 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
74 return value; // already in network byte order MSB-LSB
79 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
82 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
86 // At the moment any code that calls INTGER_TO_PY() will have to
87 // disable -Wtautological-compare for clang. See below.
89 #define INTEGER_TO_PY(x) \
90 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
93 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
96 const long tmp = PyInt_AsLong(py);
97 if (tmp == -1 && PyErr_Occurred())
99 if (PyErr_ExceptionMatches(PyExc_OverflowError))
100 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
106 PyErr_Format(PyExc_OverflowError,
107 "negative %s cannot be converted to unsigned long", name);
115 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
118 return bup_ulong_from_pyint(x, py, name);
120 if (!PyLong_Check(py))
122 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
126 const unsigned long tmp = PyLong_AsUnsignedLong(py);
127 if (PyErr_Occurred())
129 if (PyErr_ExceptionMatches(PyExc_OverflowError))
130 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
139 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
142 if (!bup_ulong_from_py(&tmp, py, name))
147 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
154 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
160 if (bup_ulong_from_pyint(&tmp, py, name))
168 if (!PyLong_Check(py))
170 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
174 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
175 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
177 if (PyErr_ExceptionMatches(PyExc_OverflowError))
178 PyErr_Format(PyExc_OverflowError,
179 "%s too big for unsigned long long", name);
187 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
188 #if __WIN32__ || __CYGWIN__
190 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
191 static void unpythonize_argv(void) { }
193 #else // not __WIN32__
195 // For some reason this isn't declared in Python.h
196 extern void Py_GetArgcArgv(int *argc, char ***argv);
198 static void unpythonize_argv(void)
203 Py_GetArgcArgv(&argc, &argv);
205 for (i = 0; i < argc-1; i++)
207 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
209 // The argv block doesn't work the way we expected; it's unsafe
215 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
217 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
221 p = strrchr(argv[1], '/');
227 memmove(argv[0], p, len);
228 memset(arge - diff, 0, diff);
229 for (i = 0; i < argc; i++)
230 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
235 #endif // not __WIN32__ or __CYGWIN__
238 static unsigned long long count_leading_zeros(const unsigned char * const buf,
239 unsigned long long len)
241 const unsigned char *cur = buf;
242 while(len-- && *cur == 0)
248 static int write_all(int fd, const void *buf, const size_t count)
251 while (written < count)
253 const ssize_t rc = write(fd, buf + written, count - written);
262 static int uadd(unsigned long long *dest,
263 const unsigned long long x,
264 const unsigned long long y)
266 const unsigned long long result = x + y;
267 if (result < x || result < y)
273 static PyObject *append_sparse_region(const int fd, unsigned long long n)
278 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
280 const off_t off = lseek(fd, new_off, SEEK_CUR);
281 if (off == (off_t) -1)
282 return PyErr_SetFromErrno(PyExc_IOError);
289 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
292 unsigned char *buf = NULL;
294 PyObject *py_min_sparse_len, *py_prev_sparse_len;
295 if (!PyArg_ParseTuple(args, "it#OO",
296 &fd, &buf, &sbuf_len,
297 &py_min_sparse_len, &py_prev_sparse_len))
299 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
300 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
302 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
305 return PyErr_Format(PyExc_ValueError, "negative bufer length");
306 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
307 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
309 // The value of zeros_read indicates the number of zeros read from
310 // buf that haven't been accounted for yet (with respect to cur),
311 // while zeros indicates the total number of pending zeros, which
312 // could be larger in the first iteration if prev_sparse_len
315 unsigned long long unexamined = buf_len;
316 unsigned char *block_start = buf, *cur = buf;
317 unsigned long long zeros, zeros_read = count_leading_zeros(cur, unexamined);
318 assert(zeros_read <= unexamined);
319 unexamined -= zeros_read;
320 if (!uadd(&zeros, prev_sparse_len, zeros_read))
322 PyObject *err = append_sparse_region(fd, prev_sparse_len);
330 if (zeros < min_sparse_len)
334 rc = write_all(fd, block_start, cur - block_start);
336 return PyErr_SetFromErrno(PyExc_IOError);
337 PyObject *err = append_sparse_region(fd, zeros);
343 // Pending zeros have ether been made sparse, or are going to
344 // be rolled into the next non-sparse block since we know we
345 // now have at least one unexamined non-zero byte.
346 assert(unexamined && *cur != 0);
347 zeros = zeros_read = 0;
348 while (unexamined && *cur != 0)
354 zeros_read = count_leading_zeros(cur, unexamined);
355 assert(zeros_read <= unexamined);
356 unexamined -= zeros_read;
360 rc = write_all(fd, block_start, cur - block_start);
362 return PyErr_SetFromErrno(PyExc_IOError);
363 return PyLong_FromUnsignedLongLong(zeros);
367 static PyObject *selftest(PyObject *self, PyObject *args)
369 if (!PyArg_ParseTuple(args, ""))
372 return Py_BuildValue("i", !bupsplit_selftest());
376 static PyObject *blobbits(PyObject *self, PyObject *args)
378 if (!PyArg_ParseTuple(args, ""))
380 return Py_BuildValue("i", BUP_BLOBBITS);
384 static PyObject *splitbuf(PyObject *self, PyObject *args)
386 unsigned char *buf = NULL;
388 int out = 0, bits = -1;
390 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
392 assert(len <= INT_MAX);
393 out = bupsplit_find_ofs(buf, len, &bits);
394 if (out) assert(bits >= BUP_BLOBBITS);
395 return Py_BuildValue("ii", out, bits);
399 static PyObject *bitmatch(PyObject *self, PyObject *args)
401 unsigned char *buf1 = NULL, *buf2 = NULL;
402 Py_ssize_t len1 = 0, len2 = 0;
406 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
410 for (byte = 0; byte < len1 && byte < len2; byte++)
412 int b1 = buf1[byte], b2 = buf2[byte];
415 for (bit = 0; bit < 8; bit++)
416 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
422 assert(byte <= (INT_MAX >> 3));
423 return Py_BuildValue("i", byte*8 + bit);
427 static PyObject *firstword(PyObject *self, PyObject *args)
429 unsigned char *buf = NULL;
433 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
439 v = ntohl(*(uint32_t *)buf);
440 return PyLong_FromUnsignedLong(v);
444 #define BLOOM2_HEADERLEN 16
446 static void to_bloom_address_bitmask4(const unsigned char *buf,
447 const int nbits, uint64_t *v, unsigned char *bitmask)
453 memcpy(&high, buf, 4);
454 mask = (1<<nbits) - 1;
455 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
456 bit = (raw >> (37-nbits)) & 0x7;
457 *v = (raw >> (40-nbits)) & mask;
461 static void to_bloom_address_bitmask5(const unsigned char *buf,
462 const int nbits, uint32_t *v, unsigned char *bitmask)
468 memcpy(&high, buf, 4);
469 mask = (1<<nbits) - 1;
471 bit = (raw >> (29-nbits)) & 0x7;
472 *v = (raw >> (32-nbits)) & mask;
476 #define BLOOM_SET_BIT(name, address, otype) \
477 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
479 unsigned char bitmask;\
481 address(buf, nbits, &v, &bitmask);\
482 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
484 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
485 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
488 #define BLOOM_GET_BIT(name, address, otype) \
489 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
491 unsigned char bitmask;\
493 address(buf, nbits, &v, &bitmask);\
494 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
496 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
497 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
500 static PyObject *bloom_add(PyObject *self, PyObject *args)
502 unsigned char *sha = NULL, *bloom = NULL;
504 Py_ssize_t len = 0, blen = 0;
505 int nbits = 0, k = 0;
507 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
510 if (blen < 16+(1<<nbits) || len % 20 != 0)
517 for (end = sha + len; sha < end; sha += 20/k)
518 bloom_set_bit5(bloom, sha, nbits);
524 for (end = sha + len; sha < end; sha += 20/k)
525 bloom_set_bit4(bloom, sha, nbits);
531 return Py_BuildValue("n", len/20);
534 static PyObject *bloom_contains(PyObject *self, PyObject *args)
536 unsigned char *sha = NULL, *bloom = NULL;
537 Py_ssize_t len = 0, blen = 0;
538 int nbits = 0, k = 0;
542 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
552 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
553 if (!bloom_get_bit5(bloom, sha, nbits))
554 return Py_BuildValue("Oi", Py_None, steps);
560 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
561 if (!bloom_get_bit4(bloom, sha, nbits))
562 return Py_BuildValue("Oi", Py_None, steps);
567 return Py_BuildValue("ii", 1, k);
571 static uint32_t _extract_bits(unsigned char *buf, int nbits)
575 mask = (1<<nbits) - 1;
576 v = ntohl(*(uint32_t *)buf);
577 v = (v >> (32-nbits)) & mask;
582 static PyObject *extract_bits(PyObject *self, PyObject *args)
584 unsigned char *buf = NULL;
588 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
594 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
599 unsigned char bytes[20];
613 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
616 for (i = 0; i < sizeof(struct sha); i++)
617 if (sha1->bytes[i] != sha2->bytes[i])
618 return sha1->bytes[i] - sha2->bytes[i];
623 static void _fix_idx_order(struct idx **idxs, int *last_i)
626 int low, mid, high, c = 0;
629 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
631 idxs[*last_i] = NULL;
644 mid = (low + high) / 2;
645 c = _cmp_sha(idx->cur, idxs[mid]->cur);
657 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
662 static uint32_t _get_idx_i(struct idx *idx)
664 if (idx->cur_name == NULL)
665 return idx->name_base;
666 return ntohl(*idx->cur_name) + idx->name_base;
669 #define MIDX4_HEADERLEN 12
671 static PyObject *merge_into(PyObject *self, PyObject *args)
673 PyObject *py_total, *ilist = NULL;
674 unsigned char *fmap = NULL;
675 struct sha *sha_ptr, *sha_start = NULL;
676 uint32_t *table_ptr, *name_ptr, *name_start;
677 struct idx **idxs = NULL;
681 uint32_t count, prefix;
685 if (!PyArg_ParseTuple(args, "w#iOO",
686 &fmap, &flen, &bits, &py_total, &ilist))
689 if (!bup_uint_from_py(&total, py_total, "total"))
692 num_i = PyList_Size(ilist);
693 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
695 for (i = 0; i < num_i; i++)
697 long len, sha_ofs, name_map_ofs;
698 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
699 PyObject *itup = PyList_GetItem(ilist, i);
700 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
701 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
703 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
704 idxs[i]->end = &idxs[i]->cur[len];
706 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
708 idxs[i]->cur_name = NULL;
710 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
711 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
712 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
721 if (count % 102424 == 0 && istty2)
722 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
723 count*100.0/total, count, total);
725 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
726 while (prefix < new_prefix)
727 table_ptr[prefix++] = htonl(count);
728 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
729 *name_ptr++ = htonl(_get_idx_i(idx));
731 if (idx->cur_name != NULL)
733 _fix_idx_order(idxs, &last_i);
736 while (prefix < (1<<bits))
737 table_ptr[prefix++] = htonl(count);
738 assert(count == total);
739 assert(prefix == (1<<bits));
740 assert(sha_ptr == sha_start+count);
741 assert(name_ptr == name_start+count);
744 return PyLong_FromUnsignedLong(count);
747 #define FAN_ENTRIES 256
749 static PyObject *write_idx(PyObject *self, PyObject *args)
751 char *filename = NULL;
752 PyObject *py_total, *idx = NULL;
754 unsigned char *fmap = NULL;
756 unsigned int total = 0;
758 int i, j, ofs64_count;
759 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
763 if (!PyArg_ParseTuple(args, "sw#OO",
764 &filename, &fmap, &flen, &idx, &py_total))
767 if (!bup_uint_from_py(&total, py_total, "total"))
770 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
771 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
774 const char idx_header[] = "\377tOc\0\0\0\002";
775 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
777 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
778 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
779 crc_ptr = (uint32_t *)&sha_ptr[total];
780 ofs_ptr = (uint32_t *)&crc_ptr[total];
781 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
785 for (i = 0; i < FAN_ENTRIES; ++i)
788 part = PyList_GET_ITEM(idx, i);
790 plen = PyList_GET_SIZE(part);
792 *fan_ptr++ = htonl(count);
793 for (j = 0; j < plen; ++j)
795 unsigned char *sha = NULL;
796 Py_ssize_t sha_len = 0;
797 PyObject *crc_py, *ofs_py;
799 unsigned PY_LONG_LONG ofs_ull;
801 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
802 &sha, &sha_len, &crc_py, &ofs_py))
804 if(!bup_uint_from_py(&crc, crc_py, "crc"))
806 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
808 assert(crc <= UINT32_MAX);
809 assert(ofs_ull <= UINT64_MAX);
811 if (sha_len != sizeof(struct sha))
813 memcpy(sha_ptr++, sha, sizeof(struct sha));
814 *crc_ptr++ = htonl(crc);
815 if (ofs > 0x7fffffff)
817 *ofs64_ptr++ = htonll(ofs);
818 ofs = 0x80000000 | ofs64_count++;
820 *ofs_ptr++ = htonl((uint32_t)ofs);
824 int rc = msync(fmap, flen, MS_ASYNC);
826 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
828 return PyLong_FromUnsignedLong(count);
832 // I would have made this a lower-level function that just fills in a buffer
833 // with random values, and then written those values from python. But that's
834 // about 20% slower in my tests, and since we typically generate random
835 // numbers for benchmarking other parts of bup, any slowness in generating
836 // random bytes will make our benchmarks inaccurate. Plus nobody wants
837 // pseudorandom bytes much except for this anyway.
838 static PyObject *write_random(PyObject *self, PyObject *args)
840 uint32_t buf[1024/4];
841 int fd = -1, seed = 0, verbose = 0;
843 long long len = 0, kbytes = 0, written = 0;
845 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
850 for (kbytes = 0; kbytes < len/1024; kbytes++)
853 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
855 ret = write(fd, buf, sizeof(buf));
859 if (ret < (int)sizeof(buf))
861 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
862 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
865 // handle non-multiples of 1024
869 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
871 ret = write(fd, buf, len % 1024);
878 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
879 return Py_BuildValue("L", written);
883 static PyObject *random_sha(PyObject *self, PyObject *args)
885 static int seeded = 0;
886 uint32_t shabuf[20/4];
891 assert(sizeof(shabuf) == 20);
896 if (!PyArg_ParseTuple(args, ""))
899 memset(shabuf, 0, sizeof(shabuf));
900 for (i=0; i < 20/4; i++)
901 shabuf[i] = random();
902 return Py_BuildValue("s#", shabuf, 20);
906 static int _open_noatime(const char *filename, int attrs)
908 int attrs_noatime, fd;
914 attrs |= O_LARGEFILE;
916 attrs_noatime = attrs;
918 attrs_noatime |= O_NOATIME;
920 fd = open(filename, attrs_noatime);
921 if (fd < 0 && errno == EPERM)
923 // older Linux kernels would return EPERM if you used O_NOATIME
924 // and weren't the file's owner. This pointless restriction was
925 // relaxed eventually, but we have to handle it anyway.
926 // (VERY old kernels didn't recognized O_NOATIME, but they would
927 // just harmlessly ignore it, so this branch won't trigger)
928 fd = open(filename, attrs);
934 static PyObject *open_noatime(PyObject *self, PyObject *args)
936 char *filename = NULL;
938 if (!PyArg_ParseTuple(args, "s", &filename))
940 fd = _open_noatime(filename, 0);
942 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
943 return Py_BuildValue("i", fd);
947 static PyObject *fadvise_done(PyObject *self, PyObject *args)
950 long long llofs, lllen = 0;
951 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
954 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
955 return PyErr_Format(PyExc_OverflowError,
956 "fadvise offset overflows off_t");
957 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
958 return PyErr_Format(PyExc_OverflowError,
959 "fadvise length overflows off_t");
960 #ifdef POSIX_FADV_DONTNEED
961 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
963 return Py_BuildValue("");
967 // Currently the Linux kernel and FUSE disagree over the type for
968 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
969 // but FUSE chose long (matching the declaration in linux/fs.h). So
970 // if you use int, and then traverse a FUSE filesystem, you may
971 // corrupt the stack. But if you use long, then you may get invalid
972 // results on big-endian systems.
974 // For now, we just use long, and then disable Linux attrs entirely
975 // (with a warning) in helpers.py on systems that are affected.
977 #ifdef BUP_HAVE_FILE_ATTRS
978 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
985 if (!PyArg_ParseTuple(args, "s", &path))
988 fd = _open_noatime(path, O_NONBLOCK);
990 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
992 attr = 0; // Handle int/long mismatch (see above)
993 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
997 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1000 assert(attr <= UINT_MAX); // Kernel type is actually int
1001 return PyLong_FromUnsignedLong(attr);
1003 #endif /* def BUP_HAVE_FILE_ATTRS */
1007 #ifdef BUP_HAVE_FILE_ATTRS
1008 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1011 unsigned long orig_attr;
1017 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1020 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1023 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1025 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1027 // Restrict attr to modifiable flags acdeijstuADST -- see
1028 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1029 // in pf.c flags_array[].
1030 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1031 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1032 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1033 | FS_TOPDIR_FL | FS_NOCOW_FL;
1035 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1036 orig_attr = 0; // Handle int/long mismatch (see above)
1037 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1038 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1042 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1044 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1046 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1050 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1054 return Py_BuildValue("O", Py_None);
1056 #endif /* def BUP_HAVE_FILE_ATTRS */
1059 #ifndef HAVE_UTIMENSAT
1061 #error "cannot find utimensat or utimes()"
1063 #ifndef HAVE_LUTIMES
1064 #error "cannot find utimensat or lutimes()"
1068 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1072 const long long lltmp = PyLong_AsLongLong(pylong); \
1073 if (lltmp == -1 && PyErr_Occurred()) \
1075 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1077 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1078 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1080 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1086 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1094 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1103 #ifdef HAVE_UTIMENSAT
1105 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1110 PyObject *access_py, *modification_py;
1111 struct timespec ts[2];
1113 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1116 &access_py, &(ts[0].tv_nsec),
1117 &modification_py, &(ts[1].tv_nsec),
1122 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1125 PyErr_SetString(PyExc_ValueError,
1126 "unable to convert access time seconds for utimensat");
1129 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1132 PyErr_SetString(PyExc_ValueError,
1133 "unable to convert modification time seconds for utimensat");
1136 rc = utimensat(fd, path, ts, flag);
1138 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1140 return Py_BuildValue("O", Py_None);
1143 #endif /* def HAVE_UTIMENSAT */
1146 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1148 static int bup_parse_xutimes_args(char **path,
1149 struct timeval tv[2],
1152 PyObject *access_py, *modification_py;
1153 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1155 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1157 &access_py, &access_us,
1158 &modification_py, &modification_us))
1162 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1165 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1168 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1170 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1173 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1176 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1179 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1181 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1187 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1191 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1194 struct timeval tv[2];
1195 if (!bup_parse_xutimes_args(&path, tv, args))
1197 int rc = utimes(path, tv);
1199 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1200 return Py_BuildValue("O", Py_None);
1202 #endif /* def HAVE_UTIMES */
1206 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1209 struct timeval tv[2];
1210 if (!bup_parse_xutimes_args(&path, tv, args))
1212 int rc = lutimes(path, tv);
1214 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1216 return Py_BuildValue("O", Py_None);
1218 #endif /* def HAVE_LUTIMES */
1221 #ifdef HAVE_STAT_ST_ATIM
1222 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1223 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1224 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1225 #elif defined HAVE_STAT_ST_ATIMENSEC
1226 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1227 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1228 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1230 # define BUP_STAT_ATIME_NS(st) 0
1231 # define BUP_STAT_MTIME_NS(st) 0
1232 # define BUP_STAT_CTIME_NS(st) 0
1236 #pragma clang diagnostic push
1237 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1239 static PyObject *stat_struct_to_py(const struct stat *st,
1240 const char *filename,
1243 // We can check the known (via POSIX) signed and unsigned types at
1244 // compile time, but not (easily) the unspecified types, so handle
1245 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1247 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1248 INTEGER_TO_PY(st->st_mode),
1249 (unsigned PY_LONG_LONG) st->st_ino,
1250 INTEGER_TO_PY(st->st_dev),
1251 INTEGER_TO_PY(st->st_nlink),
1252 INTEGER_TO_PY(st->st_uid),
1253 INTEGER_TO_PY(st->st_gid),
1254 INTEGER_TO_PY(st->st_rdev),
1255 (PY_LONG_LONG) st->st_size,
1256 INTEGER_TO_PY(st->st_atime),
1257 (long) BUP_STAT_ATIME_NS(st),
1258 INTEGER_TO_PY(st->st_mtime),
1259 (long) BUP_STAT_MTIME_NS(st),
1260 INTEGER_TO_PY(st->st_ctime),
1261 (long) BUP_STAT_CTIME_NS(st));
1264 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1266 static PyObject *bup_stat(PyObject *self, PyObject *args)
1271 if (!PyArg_ParseTuple(args, "s", &filename))
1275 rc = stat(filename, &st);
1277 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1278 return stat_struct_to_py(&st, filename, 0);
1282 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1287 if (!PyArg_ParseTuple(args, "s", &filename))
1291 rc = lstat(filename, &st);
1293 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1294 return stat_struct_to_py(&st, filename, 0);
1298 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1302 if (!PyArg_ParseTuple(args, "i", &fd))
1306 rc = fstat(fd, &st);
1308 return PyErr_SetFromErrno(PyExc_OSError);
1309 return stat_struct_to_py(&st, NULL, fd);
1313 #ifdef HAVE_TM_TM_GMTOFF
1314 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1318 if (!PyArg_ParseTuple(args, "L", &lltime))
1320 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1321 return PyErr_Format(PyExc_OverflowError, "time value too large");
1325 if(localtime_r(&ttime, &tm) == NULL)
1326 return PyErr_SetFromErrno(PyExc_OSError);
1328 // Match the Python struct_time values.
1329 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1330 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1331 tm.tm_hour, tm.tm_min, tm.tm_sec,
1332 tm.tm_wday, tm.tm_yday + 1,
1333 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1335 #endif /* def HAVE_TM_TM_GMTOFF */
1338 #ifdef BUP_MINCORE_BUF_TYPE
1339 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1342 Py_ssize_t src_ssize;
1344 PyObject *py_src_n, *py_src_off, *py_dest_off;
1345 if (!PyArg_ParseTuple(args, "s#OOw*O",
1346 &src, &src_ssize, &py_src_n, &py_src_off,
1347 &dest, &py_dest_off))
1350 unsigned long long src_size, src_n, src_off, dest_size, dest_off;
1351 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1352 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1353 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1356 if (!INTEGRAL_ASSIGNMENT_FITS(&src_size, src_ssize))
1357 return PyErr_Format(PyExc_OverflowError, "invalid src size");
1358 unsigned long long src_region_end;
1360 if (!uadd(&src_region_end, src_off, src_n))
1361 return PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1362 if (src_region_end > src_size)
1363 return PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1365 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len))
1366 return PyErr_Format(PyExc_OverflowError, "invalid dest size");
1367 if (dest_off > dest_size)
1368 return PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1371 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n))
1372 return PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1373 int rc = mincore((void *)(src + src_off), src_n,
1374 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1376 return PyErr_SetFromErrno(PyExc_OSError);
1377 return Py_BuildValue("O", Py_None);
1379 #endif /* def BUP_MINCORE_BUF_TYPE */
1382 static PyMethodDef helper_methods[] = {
1383 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1384 "Write buf excepting zeros at the end. Return trailing zero count." },
1385 { "selftest", selftest, METH_VARARGS,
1386 "Check that the rolling checksum rolls correctly (for unit tests)." },
1387 { "blobbits", blobbits, METH_VARARGS,
1388 "Return the number of bits in the rolling checksum." },
1389 { "splitbuf", splitbuf, METH_VARARGS,
1390 "Split a list of strings based on a rolling checksum." },
1391 { "bitmatch", bitmatch, METH_VARARGS,
1392 "Count the number of matching prefix bits between two strings." },
1393 { "firstword", firstword, METH_VARARGS,
1394 "Return an int corresponding to the first 32 bits of buf." },
1395 { "bloom_contains", bloom_contains, METH_VARARGS,
1396 "Check if a bloom filter of 2^nbits bytes contains an object" },
1397 { "bloom_add", bloom_add, METH_VARARGS,
1398 "Add an object to a bloom filter of 2^nbits bytes" },
1399 { "extract_bits", extract_bits, METH_VARARGS,
1400 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1401 { "merge_into", merge_into, METH_VARARGS,
1402 "Merges a bunch of idx and midx files into a single midx." },
1403 { "write_idx", write_idx, METH_VARARGS,
1404 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1405 { "write_random", write_random, METH_VARARGS,
1406 "Write random bytes to the given file descriptor" },
1407 { "random_sha", random_sha, METH_VARARGS,
1408 "Return a random 20-byte string" },
1409 { "open_noatime", open_noatime, METH_VARARGS,
1410 "open() the given filename for read with O_NOATIME if possible" },
1411 { "fadvise_done", fadvise_done, METH_VARARGS,
1412 "Inform the kernel that we're finished with earlier parts of a file" },
1413 #ifdef BUP_HAVE_FILE_ATTRS
1414 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1415 "Return the Linux attributes for the given file." },
1417 #ifdef BUP_HAVE_FILE_ATTRS
1418 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1419 "Set the Linux attributes for the given file." },
1421 #ifdef HAVE_UTIMENSAT
1422 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1423 "Change path timestamps with nanosecond precision (POSIX)." },
1426 { "bup_utimes", bup_utimes, METH_VARARGS,
1427 "Change path timestamps with microsecond precision." },
1430 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1431 "Change path timestamps with microsecond precision;"
1432 " don't follow symlinks." },
1434 { "stat", bup_stat, METH_VARARGS,
1435 "Extended version of stat." },
1436 { "lstat", bup_lstat, METH_VARARGS,
1437 "Extended version of lstat." },
1438 { "fstat", bup_fstat, METH_VARARGS,
1439 "Extended version of fstat." },
1440 #ifdef HAVE_TM_TM_GMTOFF
1441 { "localtime", bup_localtime, METH_VARARGS,
1442 "Return struct_time elements plus the timezone offset and name." },
1444 #ifdef BUP_MINCORE_BUF_TYPE
1445 { "mincore", bup_mincore, METH_VARARGS,
1446 "For mincore(src, src_n, src_off, dest, dest_off)"
1447 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1449 { NULL, NULL, 0, NULL }, // sentinel
1453 PyMODINIT_FUNC init_helpers(void)
1455 // FIXME: migrate these tests to configure. Check against the
1456 // type we're going to use when passing to python. Other stat
1457 // types are tested at runtime.
1458 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1459 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1460 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1461 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1462 // Just be sure (relevant when passing timestamps back to Python above).
1463 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1464 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1466 if (sizeof(off_t) < sizeof(int))
1468 // Originally required by append_sparse_region().
1469 fprintf(stderr, "sizeof(off_t) < sizeof(int); please report.\n");
1474 PyObject *m = Py_InitModule("_helpers", helper_methods);
1478 #pragma clang diagnostic push
1479 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1482 value = INTEGER_TO_PY(INT_MAX);
1483 PyObject_SetAttrString(m, "INT_MAX", value);
1485 value = INTEGER_TO_PY(UINT_MAX);
1486 PyObject_SetAttrString(m, "UINT_MAX", value);
1489 #ifdef HAVE_UTIMENSAT
1492 value = INTEGER_TO_PY(AT_FDCWD);
1493 PyObject_SetAttrString(m, "AT_FDCWD", value);
1495 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1496 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1498 value = INTEGER_TO_PY(UTIME_NOW);
1499 PyObject_SetAttrString(m, "UTIME_NOW", value);
1503 #ifdef BUP_HAVE_MINCORE_INCORE
1506 value = INTEGER_TO_PY(MINCORE_INCORE);
1507 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1511 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1513 e = getenv("BUP_FORCE_TTY");
1514 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);