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>
19 #ifdef HAVE_SYS_TYPES_H
20 #include <sys/types.h>
22 #ifdef HAVE_SYS_STAT_H
29 #ifdef HAVE_LINUX_FS_H
32 #ifdef HAVE_SYS_IOCTL_H
33 #include <sys/ioctl.h>
38 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
39 #define BUP_HAVE_FILE_ATTRS 1
43 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
44 * pretend we don't have it.
46 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
51 // Of course, this assumes it's a bitfield value.
55 static int istty2 = 0;
59 // This function should technically be macro'd out if it's going to be used
60 // more than ocasionally. As of this writing, it'll actually never be called
61 // in real world bup scenarios (because our packs are < MAX_INT bytes).
62 static uint64_t htonll(uint64_t value)
64 static const int endian_test = 42;
66 if (*(char *)&endian_test == endian_test) // LSB-MSB
67 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
68 return value; // already in network byte order MSB-LSB
73 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
76 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
80 // At the moment any code that calls INTGER_TO_PY() will have to
81 // disable -Wtautological-compare for clang. See below.
83 #define INTEGER_TO_PY(x) \
84 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
87 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
90 const long tmp = PyInt_AsLong(py);
91 if (tmp == -1 && PyErr_Occurred())
93 if (PyErr_ExceptionMatches(PyExc_OverflowError))
94 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
100 PyErr_Format(PyExc_OverflowError,
101 "negative %s cannot be converted to unsigned long", name);
109 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
112 return bup_ulong_from_pyint(x, py, name);
114 if (!PyLong_Check(py))
116 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
120 const unsigned long tmp = PyLong_AsUnsignedLong(py);
121 if (PyErr_Occurred())
123 if (PyErr_ExceptionMatches(PyExc_OverflowError))
124 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
133 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
136 if (!bup_ulong_from_py(&tmp, py, name))
141 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
148 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
154 if (bup_ulong_from_pyint(&tmp, py, name))
162 if (!PyLong_Check(py))
164 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
168 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
169 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
171 if (PyErr_ExceptionMatches(PyExc_OverflowError))
172 PyErr_Format(PyExc_OverflowError,
173 "%s too big for unsigned long long", name);
181 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
182 #if __WIN32__ || __CYGWIN__
184 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
185 static void unpythonize_argv(void) { }
187 #else // not __WIN32__
189 // For some reason this isn't declared in Python.h
190 extern void Py_GetArgcArgv(int *argc, char ***argv);
192 static void unpythonize_argv(void)
197 Py_GetArgcArgv(&argc, &argv);
199 for (i = 0; i < argc-1; i++)
201 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
203 // The argv block doesn't work the way we expected; it's unsafe
209 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
211 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
215 p = strrchr(argv[1], '/');
221 memmove(argv[0], p, len);
222 memset(arge - diff, 0, diff);
223 for (i = 0; i < argc; i++)
224 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
229 #endif // not __WIN32__ or __CYGWIN__
232 static unsigned long long count_leading_zeros(const unsigned char * const buf,
233 unsigned long long len)
235 const unsigned char *cur = buf;
236 while(len-- && *cur == 0)
242 static int write_all(int fd, const void *buf, const size_t count)
245 while (written < count)
247 const ssize_t rc = write(fd, buf + written, count - written);
256 static int uadd(unsigned long long *dest,
257 const unsigned long long x,
258 const unsigned long long y)
260 const unsigned long long result = x + y;
261 if (result < x || result < y)
268 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
271 unsigned char *buf = NULL;
273 PyObject *py_min_sparse_len, *py_prev_sparse_len;
274 if (!PyArg_ParseTuple(args, "it#OO",
275 &fd, &buf, &sbuf_len,
276 &py_min_sparse_len, &py_prev_sparse_len))
278 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
279 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
281 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
284 return PyErr_Format(PyExc_ValueError, "negative bufer length");
285 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
286 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
288 // For now, there are some cases where we just give up if the
289 // values are too large, but we could try to break up the relevant
290 // operations into chunks.
292 // Deal with preceding zeros. Just make them sparse, along with
293 // any leading zeros in buf, even if the region's not >= min,
294 // since the alternative is a potentially extra small write.
297 const unsigned long long zeros = count_leading_zeros(buf, buf_len);
298 unsigned long long new_sparse_len = 0;
299 if (!uadd(&new_sparse_len, prev_sparse_len, zeros))
300 return PyErr_Format (PyExc_OverflowError, "sparse region too large");
301 if (zeros == buf_len)
302 return PyLong_FromUnsignedLongLong(new_sparse_len);
305 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, new_sparse_len))
306 return PyErr_Format(PyExc_OverflowError,
307 "sparse region too large for seek");
308 const off_t off = lseek(fd, new_off, SEEK_CUR);
310 return PyErr_SetFromErrno(PyExc_IOError);
316 unsigned long long unexamined = buf_len;
317 unsigned char *block_start = buf, *cur = buf;
320 const unsigned long long zeros = count_leading_zeros(cur, unexamined);
321 assert(zeros <= unexamined);
323 if (unexamined == 0) // Runs off the end.
325 rc = write_all(fd, block_start, cur - block_start);
327 return PyErr_SetFromErrno(PyExc_IOError);
328 return PyLong_FromUnsignedLongLong(zeros);
331 if (zeros >= min_sparse_len)
334 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, zeros))
335 return PyErr_Format(PyExc_ValueError,
336 "zero count overflows off_t");
337 off_t off = lseek(fd, new_off, SEEK_CUR);
339 return PyErr_SetFromErrno(PyExc_IOError);
342 while (unexamined && *cur != 0)
347 rc = write_all(fd, block_start, cur - block_start);
349 return PyErr_SetFromErrno(PyExc_IOError);
350 return PyInt_FromLong(0);
354 static PyObject *selftest(PyObject *self, PyObject *args)
356 if (!PyArg_ParseTuple(args, ""))
359 return Py_BuildValue("i", !bupsplit_selftest());
363 static PyObject *blobbits(PyObject *self, PyObject *args)
365 if (!PyArg_ParseTuple(args, ""))
367 return Py_BuildValue("i", BUP_BLOBBITS);
371 static PyObject *splitbuf(PyObject *self, PyObject *args)
373 unsigned char *buf = NULL;
375 int out = 0, bits = -1;
377 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
379 assert(len <= INT_MAX);
380 out = bupsplit_find_ofs(buf, len, &bits);
381 if (out) assert(bits >= BUP_BLOBBITS);
382 return Py_BuildValue("ii", out, bits);
386 static PyObject *bitmatch(PyObject *self, PyObject *args)
388 unsigned char *buf1 = NULL, *buf2 = NULL;
389 Py_ssize_t len1 = 0, len2 = 0;
393 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
397 for (byte = 0; byte < len1 && byte < len2; byte++)
399 int b1 = buf1[byte], b2 = buf2[byte];
402 for (bit = 0; bit < 8; bit++)
403 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
409 assert(byte <= (INT_MAX >> 3));
410 return Py_BuildValue("i", byte*8 + bit);
414 static PyObject *firstword(PyObject *self, PyObject *args)
416 unsigned char *buf = NULL;
420 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
426 v = ntohl(*(uint32_t *)buf);
427 return PyLong_FromUnsignedLong(v);
431 #define BLOOM2_HEADERLEN 16
433 static void to_bloom_address_bitmask4(const unsigned char *buf,
434 const int nbits, uint64_t *v, unsigned char *bitmask)
440 memcpy(&high, buf, 4);
441 mask = (1<<nbits) - 1;
442 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
443 bit = (raw >> (37-nbits)) & 0x7;
444 *v = (raw >> (40-nbits)) & mask;
448 static void to_bloom_address_bitmask5(const unsigned char *buf,
449 const int nbits, uint32_t *v, unsigned char *bitmask)
455 memcpy(&high, buf, 4);
456 mask = (1<<nbits) - 1;
458 bit = (raw >> (29-nbits)) & 0x7;
459 *v = (raw >> (32-nbits)) & mask;
463 #define BLOOM_SET_BIT(name, address, otype) \
464 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
466 unsigned char bitmask;\
468 address(buf, nbits, &v, &bitmask);\
469 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
471 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
472 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
475 #define BLOOM_GET_BIT(name, address, otype) \
476 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
478 unsigned char bitmask;\
480 address(buf, nbits, &v, &bitmask);\
481 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
483 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
484 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
487 static PyObject *bloom_add(PyObject *self, PyObject *args)
489 unsigned char *sha = NULL, *bloom = NULL;
491 Py_ssize_t len = 0, blen = 0;
492 int nbits = 0, k = 0;
494 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
497 if (blen < 16+(1<<nbits) || len % 20 != 0)
504 for (end = sha + len; sha < end; sha += 20/k)
505 bloom_set_bit5(bloom, sha, nbits);
511 for (end = sha + len; sha < end; sha += 20/k)
512 bloom_set_bit4(bloom, sha, nbits);
518 return Py_BuildValue("n", len/20);
521 static PyObject *bloom_contains(PyObject *self, PyObject *args)
523 unsigned char *sha = NULL, *bloom = NULL;
524 Py_ssize_t len = 0, blen = 0;
525 int nbits = 0, k = 0;
529 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
539 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
540 if (!bloom_get_bit5(bloom, sha, nbits))
541 return Py_BuildValue("Oi", Py_None, steps);
547 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
548 if (!bloom_get_bit4(bloom, sha, nbits))
549 return Py_BuildValue("Oi", Py_None, steps);
554 return Py_BuildValue("ii", 1, k);
558 static uint32_t _extract_bits(unsigned char *buf, int nbits)
562 mask = (1<<nbits) - 1;
563 v = ntohl(*(uint32_t *)buf);
564 v = (v >> (32-nbits)) & mask;
569 static PyObject *extract_bits(PyObject *self, PyObject *args)
571 unsigned char *buf = NULL;
575 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
581 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
586 unsigned char bytes[20];
600 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
603 for (i = 0; i < sizeof(struct sha); i++)
604 if (sha1->bytes[i] != sha2->bytes[i])
605 return sha1->bytes[i] - sha2->bytes[i];
610 static void _fix_idx_order(struct idx **idxs, int *last_i)
613 int low, mid, high, c = 0;
616 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
618 idxs[*last_i] = NULL;
631 mid = (low + high) / 2;
632 c = _cmp_sha(idx->cur, idxs[mid]->cur);
644 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
649 static uint32_t _get_idx_i(struct idx *idx)
651 if (idx->cur_name == NULL)
652 return idx->name_base;
653 return ntohl(*idx->cur_name) + idx->name_base;
656 #define MIDX4_HEADERLEN 12
658 static PyObject *merge_into(PyObject *self, PyObject *args)
660 PyObject *py_total, *ilist = NULL;
661 unsigned char *fmap = NULL;
662 struct sha *sha_ptr, *sha_start = NULL;
663 uint32_t *table_ptr, *name_ptr, *name_start;
664 struct idx **idxs = NULL;
668 uint32_t count, prefix;
672 if (!PyArg_ParseTuple(args, "w#iOO",
673 &fmap, &flen, &bits, &py_total, &ilist))
676 if (!bup_uint_from_py(&total, py_total, "total"))
679 num_i = PyList_Size(ilist);
680 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
682 for (i = 0; i < num_i; i++)
684 long len, sha_ofs, name_map_ofs;
685 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
686 PyObject *itup = PyList_GetItem(ilist, i);
687 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
688 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
690 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
691 idxs[i]->end = &idxs[i]->cur[len];
693 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
695 idxs[i]->cur_name = NULL;
697 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
698 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
699 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
708 if (count % 102424 == 0 && istty2)
709 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
710 count*100.0/total, count, total);
712 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
713 while (prefix < new_prefix)
714 table_ptr[prefix++] = htonl(count);
715 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
716 *name_ptr++ = htonl(_get_idx_i(idx));
718 if (idx->cur_name != NULL)
720 _fix_idx_order(idxs, &last_i);
723 while (prefix < (1<<bits))
724 table_ptr[prefix++] = htonl(count);
725 assert(count == total);
726 assert(prefix == (1<<bits));
727 assert(sha_ptr == sha_start+count);
728 assert(name_ptr == name_start+count);
731 return PyLong_FromUnsignedLong(count);
734 #define FAN_ENTRIES 256
736 static PyObject *write_idx(PyObject *self, PyObject *args)
738 char *filename = NULL;
739 PyObject *py_total, *idx = NULL;
741 unsigned char *fmap = NULL;
743 unsigned int total = 0;
745 int i, j, ofs64_count;
746 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
750 if (!PyArg_ParseTuple(args, "sw#OO",
751 &filename, &fmap, &flen, &idx, &py_total))
754 if (!bup_uint_from_py(&total, py_total, "total"))
757 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
758 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
761 const char idx_header[] = "\377tOc\0\0\0\002";
762 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
764 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
765 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
766 crc_ptr = (uint32_t *)&sha_ptr[total];
767 ofs_ptr = (uint32_t *)&crc_ptr[total];
768 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
772 for (i = 0; i < FAN_ENTRIES; ++i)
775 part = PyList_GET_ITEM(idx, i);
777 plen = PyList_GET_SIZE(part);
779 *fan_ptr++ = htonl(count);
780 for (j = 0; j < plen; ++j)
782 unsigned char *sha = NULL;
783 Py_ssize_t sha_len = 0;
784 PyObject *crc_py, *ofs_py;
786 unsigned PY_LONG_LONG ofs_ull;
788 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
789 &sha, &sha_len, &crc_py, &ofs_py))
791 if(!bup_uint_from_py(&crc, crc_py, "crc"))
793 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
795 assert(crc <= UINT32_MAX);
796 assert(ofs_ull <= UINT64_MAX);
798 if (sha_len != sizeof(struct sha))
800 memcpy(sha_ptr++, sha, sizeof(struct sha));
801 *crc_ptr++ = htonl(crc);
802 if (ofs > 0x7fffffff)
804 *ofs64_ptr++ = htonll(ofs);
805 ofs = 0x80000000 | ofs64_count++;
807 *ofs_ptr++ = htonl((uint32_t)ofs);
811 int rc = msync(fmap, flen, MS_ASYNC);
813 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
815 return PyLong_FromUnsignedLong(count);
819 // I would have made this a lower-level function that just fills in a buffer
820 // with random values, and then written those values from python. But that's
821 // about 20% slower in my tests, and since we typically generate random
822 // numbers for benchmarking other parts of bup, any slowness in generating
823 // random bytes will make our benchmarks inaccurate. Plus nobody wants
824 // pseudorandom bytes much except for this anyway.
825 static PyObject *write_random(PyObject *self, PyObject *args)
827 uint32_t buf[1024/4];
828 int fd = -1, seed = 0, verbose = 0;
830 long long len = 0, kbytes = 0, written = 0;
832 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
837 for (kbytes = 0; kbytes < len/1024; kbytes++)
840 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
842 ret = write(fd, buf, sizeof(buf));
846 if (ret < (int)sizeof(buf))
848 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
849 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
852 // handle non-multiples of 1024
856 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
858 ret = write(fd, buf, len % 1024);
865 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
866 return Py_BuildValue("L", written);
870 static PyObject *random_sha(PyObject *self, PyObject *args)
872 static int seeded = 0;
873 uint32_t shabuf[20/4];
878 assert(sizeof(shabuf) == 20);
883 if (!PyArg_ParseTuple(args, ""))
886 memset(shabuf, 0, sizeof(shabuf));
887 for (i=0; i < 20/4; i++)
888 shabuf[i] = random();
889 return Py_BuildValue("s#", shabuf, 20);
893 static int _open_noatime(const char *filename, int attrs)
895 int attrs_noatime, fd;
901 attrs |= O_LARGEFILE;
903 attrs_noatime = attrs;
905 attrs_noatime |= O_NOATIME;
907 fd = open(filename, attrs_noatime);
908 if (fd < 0 && errno == EPERM)
910 // older Linux kernels would return EPERM if you used O_NOATIME
911 // and weren't the file's owner. This pointless restriction was
912 // relaxed eventually, but we have to handle it anyway.
913 // (VERY old kernels didn't recognized O_NOATIME, but they would
914 // just harmlessly ignore it, so this branch won't trigger)
915 fd = open(filename, attrs);
921 static PyObject *open_noatime(PyObject *self, PyObject *args)
923 char *filename = NULL;
925 if (!PyArg_ParseTuple(args, "s", &filename))
927 fd = _open_noatime(filename, 0);
929 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
930 return Py_BuildValue("i", fd);
934 static PyObject *fadvise_done(PyObject *self, PyObject *args)
938 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
940 #ifdef POSIX_FADV_DONTNEED
941 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
943 return Py_BuildValue("");
947 // Currently the Linux kernel and FUSE disagree over the type for
948 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
949 // but FUSE chose long (matching the declaration in linux/fs.h). So
950 // if you use int, and then traverse a FUSE filesystem, you may
951 // corrupt the stack. But if you use long, then you may get invalid
952 // results on big-endian systems.
954 // For now, we just use long, and then disable Linux attrs entirely
955 // (with a warning) in helpers.py on systems that are affected.
957 #ifdef BUP_HAVE_FILE_ATTRS
958 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
965 if (!PyArg_ParseTuple(args, "s", &path))
968 fd = _open_noatime(path, O_NONBLOCK);
970 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
972 attr = 0; // Handle int/long mismatch (see above)
973 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
977 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
980 assert(attr <= UINT_MAX); // Kernel type is actually int
981 return PyLong_FromUnsignedLong(attr);
983 #endif /* def BUP_HAVE_FILE_ATTRS */
987 #ifdef BUP_HAVE_FILE_ATTRS
988 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
991 unsigned long orig_attr;
997 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1000 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1003 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1005 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1007 // Restrict attr to modifiable flags acdeijstuADST -- see
1008 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1009 // in pf.c flags_array[].
1010 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1011 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1012 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1013 | FS_TOPDIR_FL | FS_NOCOW_FL;
1015 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1016 orig_attr = 0; // Handle int/long mismatch (see above)
1017 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1018 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1022 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1024 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1026 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1030 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1034 return Py_BuildValue("O", Py_None);
1036 #endif /* def BUP_HAVE_FILE_ATTRS */
1039 #ifndef HAVE_UTIMENSAT
1041 #error "cannot find utimensat or utimes()"
1043 #ifndef HAVE_LUTIMES
1044 #error "cannot find utimensat or lutimes()"
1048 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1052 const long long lltmp = PyLong_AsLongLong(pylong); \
1053 if (lltmp == -1 && PyErr_Occurred()) \
1055 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1057 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1058 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1060 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1066 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1074 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1083 #ifdef HAVE_UTIMENSAT
1085 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1090 PyObject *access_py, *modification_py;
1091 struct timespec ts[2];
1093 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1096 &access_py, &(ts[0].tv_nsec),
1097 &modification_py, &(ts[1].tv_nsec),
1102 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1105 PyErr_SetString(PyExc_ValueError,
1106 "unable to convert access time seconds for utimensat");
1109 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1112 PyErr_SetString(PyExc_ValueError,
1113 "unable to convert modification time seconds for utimensat");
1116 rc = utimensat(fd, path, ts, flag);
1118 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1120 return Py_BuildValue("O", Py_None);
1123 #endif /* def HAVE_UTIMENSAT */
1126 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1128 static int bup_parse_xutimes_args(char **path,
1129 struct timeval tv[2],
1132 PyObject *access_py, *modification_py;
1133 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1135 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1137 &access_py, &access_us,
1138 &modification_py, &modification_us))
1142 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1145 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1148 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1150 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1153 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1156 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1159 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1161 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1167 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1171 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1174 struct timeval tv[2];
1175 if (!bup_parse_xutimes_args(&path, tv, args))
1177 int rc = utimes(path, tv);
1179 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1180 return Py_BuildValue("O", Py_None);
1182 #endif /* def HAVE_UTIMES */
1186 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1189 struct timeval tv[2];
1190 if (!bup_parse_xutimes_args(&path, tv, args))
1192 int rc = lutimes(path, tv);
1194 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1196 return Py_BuildValue("O", Py_None);
1198 #endif /* def HAVE_LUTIMES */
1201 #ifdef HAVE_STAT_ST_ATIM
1202 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1203 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1204 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1205 #elif defined HAVE_STAT_ST_ATIMENSEC
1206 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1207 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1208 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1210 # define BUP_STAT_ATIME_NS(st) 0
1211 # define BUP_STAT_MTIME_NS(st) 0
1212 # define BUP_STAT_CTIME_NS(st) 0
1216 #pragma clang diagnostic push
1217 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1219 static PyObject *stat_struct_to_py(const struct stat *st,
1220 const char *filename,
1223 // We can check the known (via POSIX) signed and unsigned types at
1224 // compile time, but not (easily) the unspecified types, so handle
1225 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1227 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1228 INTEGER_TO_PY(st->st_mode),
1229 (unsigned PY_LONG_LONG) st->st_ino,
1230 INTEGER_TO_PY(st->st_dev),
1231 INTEGER_TO_PY(st->st_nlink),
1232 INTEGER_TO_PY(st->st_uid),
1233 INTEGER_TO_PY(st->st_gid),
1234 INTEGER_TO_PY(st->st_rdev),
1235 (PY_LONG_LONG) st->st_size,
1236 INTEGER_TO_PY(st->st_atime),
1237 (long) BUP_STAT_ATIME_NS(st),
1238 INTEGER_TO_PY(st->st_mtime),
1239 (long) BUP_STAT_MTIME_NS(st),
1240 INTEGER_TO_PY(st->st_ctime),
1241 (long) BUP_STAT_CTIME_NS(st));
1244 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1246 static PyObject *bup_stat(PyObject *self, PyObject *args)
1251 if (!PyArg_ParseTuple(args, "s", &filename))
1255 rc = stat(filename, &st);
1257 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1258 return stat_struct_to_py(&st, filename, 0);
1262 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1267 if (!PyArg_ParseTuple(args, "s", &filename))
1271 rc = lstat(filename, &st);
1273 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1274 return stat_struct_to_py(&st, filename, 0);
1278 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1282 if (!PyArg_ParseTuple(args, "i", &fd))
1286 rc = fstat(fd, &st);
1288 return PyErr_SetFromErrno(PyExc_OSError);
1289 return stat_struct_to_py(&st, NULL, fd);
1293 static PyMethodDef helper_methods[] = {
1294 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1295 "Write buf excepting zeros at the end. Return trailing zero count." },
1296 { "selftest", selftest, METH_VARARGS,
1297 "Check that the rolling checksum rolls correctly (for unit tests)." },
1298 { "blobbits", blobbits, METH_VARARGS,
1299 "Return the number of bits in the rolling checksum." },
1300 { "splitbuf", splitbuf, METH_VARARGS,
1301 "Split a list of strings based on a rolling checksum." },
1302 { "bitmatch", bitmatch, METH_VARARGS,
1303 "Count the number of matching prefix bits between two strings." },
1304 { "firstword", firstword, METH_VARARGS,
1305 "Return an int corresponding to the first 32 bits of buf." },
1306 { "bloom_contains", bloom_contains, METH_VARARGS,
1307 "Check if a bloom filter of 2^nbits bytes contains an object" },
1308 { "bloom_add", bloom_add, METH_VARARGS,
1309 "Add an object to a bloom filter of 2^nbits bytes" },
1310 { "extract_bits", extract_bits, METH_VARARGS,
1311 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1312 { "merge_into", merge_into, METH_VARARGS,
1313 "Merges a bunch of idx and midx files into a single midx." },
1314 { "write_idx", write_idx, METH_VARARGS,
1315 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1316 { "write_random", write_random, METH_VARARGS,
1317 "Write random bytes to the given file descriptor" },
1318 { "random_sha", random_sha, METH_VARARGS,
1319 "Return a random 20-byte string" },
1320 { "open_noatime", open_noatime, METH_VARARGS,
1321 "open() the given filename for read with O_NOATIME if possible" },
1322 { "fadvise_done", fadvise_done, METH_VARARGS,
1323 "Inform the kernel that we're finished with earlier parts of a file" },
1324 #ifdef BUP_HAVE_FILE_ATTRS
1325 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1326 "Return the Linux attributes for the given file." },
1328 #ifdef BUP_HAVE_FILE_ATTRS
1329 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1330 "Set the Linux attributes for the given file." },
1332 #ifdef HAVE_UTIMENSAT
1333 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1334 "Change path timestamps with nanosecond precision (POSIX)." },
1337 { "bup_utimes", bup_utimes, METH_VARARGS,
1338 "Change path timestamps with microsecond precision." },
1341 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1342 "Change path timestamps with microsecond precision;"
1343 " don't follow symlinks." },
1345 { "stat", bup_stat, METH_VARARGS,
1346 "Extended version of stat." },
1347 { "lstat", bup_lstat, METH_VARARGS,
1348 "Extended version of lstat." },
1349 { "fstat", bup_fstat, METH_VARARGS,
1350 "Extended version of fstat." },
1351 { NULL, NULL, 0, NULL }, // sentinel
1355 PyMODINIT_FUNC init_helpers(void)
1357 // FIXME: migrate these tests to configure. Check against the
1358 // type we're going to use when passing to python. Other stat
1359 // types are tested at runtime.
1360 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1361 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1362 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1363 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1364 // Just be sure (relevant when passing timestamps back to Python above).
1365 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1366 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1369 PyObject *m = Py_InitModule("_helpers", helper_methods);
1373 #pragma clang diagnostic push
1374 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1375 #ifdef HAVE_UTIMENSAT
1378 value = INTEGER_TO_PY(AT_FDCWD);
1379 PyObject_SetAttrString(m, "AT_FDCWD", value);
1381 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1382 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1384 value = INTEGER_TO_PY(UTIME_NOW);
1385 PyObject_SetAttrString(m, "UTIME_NOW", value);
1391 const long arg_max = sysconf(_SC_ARG_MAX);
1394 fprintf(stderr, "Cannot find SC_ARG_MAX, please report a bug.\n");
1397 value = INTEGER_TO_PY(arg_max);
1398 PyObject_SetAttrString(m, "SC_ARG_MAX", value);
1401 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1403 e = getenv("BUP_FORCE_TTY");
1404 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);