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)
267 static PyObject *append_sparse_region(const int fd, unsigned long long n)
272 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
274 const off_t off = lseek(fd, new_off, SEEK_CUR);
275 if (off == (off_t) -1)
276 return PyErr_SetFromErrno(PyExc_IOError);
283 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
286 unsigned char *buf = NULL;
288 PyObject *py_min_sparse_len, *py_prev_sparse_len;
289 if (!PyArg_ParseTuple(args, "it#OO",
290 &fd, &buf, &sbuf_len,
291 &py_min_sparse_len, &py_prev_sparse_len))
293 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
294 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
296 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
299 return PyErr_Format(PyExc_ValueError, "negative bufer length");
300 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
301 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
303 // The value of zeros_read indicates the number of zeros read from
304 // buf that haven't been accounted for yet (with respect to cur),
305 // while zeros indicates the total number of pending zeros, which
306 // could be larger in the first iteration if prev_sparse_len
309 unsigned long long unexamined = buf_len;
310 unsigned char *block_start = buf, *cur = buf;
311 unsigned long long zeros, zeros_read = count_leading_zeros(cur, unexamined);
312 assert(zeros_read <= unexamined);
313 unexamined -= zeros_read;
314 if (!uadd(&zeros, prev_sparse_len, zeros_read))
316 PyObject *err = append_sparse_region(fd, prev_sparse_len);
324 if (zeros < min_sparse_len)
328 rc = write_all(fd, block_start, cur - block_start);
330 return PyErr_SetFromErrno(PyExc_IOError);
331 PyObject *err = append_sparse_region(fd, zeros);
337 // Pending zeros have ether been made sparse, or are going to
338 // be rolled into the next non-sparse block since we know we
339 // now have at least one unexamined non-zero byte.
340 assert(unexamined && *cur != 0);
341 zeros = zeros_read = 0;
342 while (unexamined && *cur != 0)
348 zeros_read = count_leading_zeros(cur, unexamined);
349 assert(zeros_read <= unexamined);
350 unexamined -= zeros_read;
354 rc = write_all(fd, block_start, cur - block_start);
356 return PyErr_SetFromErrno(PyExc_IOError);
357 return PyLong_FromUnsignedLongLong(zeros);
361 static PyObject *selftest(PyObject *self, PyObject *args)
363 if (!PyArg_ParseTuple(args, ""))
366 return Py_BuildValue("i", !bupsplit_selftest());
370 static PyObject *blobbits(PyObject *self, PyObject *args)
372 if (!PyArg_ParseTuple(args, ""))
374 return Py_BuildValue("i", BUP_BLOBBITS);
378 static PyObject *splitbuf(PyObject *self, PyObject *args)
380 unsigned char *buf = NULL;
382 int out = 0, bits = -1;
384 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
386 assert(len <= INT_MAX);
387 out = bupsplit_find_ofs(buf, len, &bits);
388 if (out) assert(bits >= BUP_BLOBBITS);
389 return Py_BuildValue("ii", out, bits);
393 static PyObject *bitmatch(PyObject *self, PyObject *args)
395 unsigned char *buf1 = NULL, *buf2 = NULL;
396 Py_ssize_t len1 = 0, len2 = 0;
400 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
404 for (byte = 0; byte < len1 && byte < len2; byte++)
406 int b1 = buf1[byte], b2 = buf2[byte];
409 for (bit = 0; bit < 8; bit++)
410 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
416 assert(byte <= (INT_MAX >> 3));
417 return Py_BuildValue("i", byte*8 + bit);
421 static PyObject *firstword(PyObject *self, PyObject *args)
423 unsigned char *buf = NULL;
427 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
433 v = ntohl(*(uint32_t *)buf);
434 return PyLong_FromUnsignedLong(v);
438 #define BLOOM2_HEADERLEN 16
440 static void to_bloom_address_bitmask4(const unsigned char *buf,
441 const int nbits, uint64_t *v, unsigned char *bitmask)
447 memcpy(&high, buf, 4);
448 mask = (1<<nbits) - 1;
449 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
450 bit = (raw >> (37-nbits)) & 0x7;
451 *v = (raw >> (40-nbits)) & mask;
455 static void to_bloom_address_bitmask5(const unsigned char *buf,
456 const int nbits, uint32_t *v, unsigned char *bitmask)
462 memcpy(&high, buf, 4);
463 mask = (1<<nbits) - 1;
465 bit = (raw >> (29-nbits)) & 0x7;
466 *v = (raw >> (32-nbits)) & mask;
470 #define BLOOM_SET_BIT(name, address, otype) \
471 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
473 unsigned char bitmask;\
475 address(buf, nbits, &v, &bitmask);\
476 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
478 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
479 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
482 #define BLOOM_GET_BIT(name, address, otype) \
483 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
485 unsigned char bitmask;\
487 address(buf, nbits, &v, &bitmask);\
488 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
490 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
491 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
494 static PyObject *bloom_add(PyObject *self, PyObject *args)
496 unsigned char *sha = NULL, *bloom = NULL;
498 Py_ssize_t len = 0, blen = 0;
499 int nbits = 0, k = 0;
501 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
504 if (blen < 16+(1<<nbits) || len % 20 != 0)
511 for (end = sha + len; sha < end; sha += 20/k)
512 bloom_set_bit5(bloom, sha, nbits);
518 for (end = sha + len; sha < end; sha += 20/k)
519 bloom_set_bit4(bloom, sha, nbits);
525 return Py_BuildValue("n", len/20);
528 static PyObject *bloom_contains(PyObject *self, PyObject *args)
530 unsigned char *sha = NULL, *bloom = NULL;
531 Py_ssize_t len = 0, blen = 0;
532 int nbits = 0, k = 0;
536 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
546 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
547 if (!bloom_get_bit5(bloom, sha, nbits))
548 return Py_BuildValue("Oi", Py_None, steps);
554 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
555 if (!bloom_get_bit4(bloom, sha, nbits))
556 return Py_BuildValue("Oi", Py_None, steps);
561 return Py_BuildValue("ii", 1, k);
565 static uint32_t _extract_bits(unsigned char *buf, int nbits)
569 mask = (1<<nbits) - 1;
570 v = ntohl(*(uint32_t *)buf);
571 v = (v >> (32-nbits)) & mask;
576 static PyObject *extract_bits(PyObject *self, PyObject *args)
578 unsigned char *buf = NULL;
582 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
588 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
593 unsigned char bytes[20];
607 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
610 for (i = 0; i < sizeof(struct sha); i++)
611 if (sha1->bytes[i] != sha2->bytes[i])
612 return sha1->bytes[i] - sha2->bytes[i];
617 static void _fix_idx_order(struct idx **idxs, int *last_i)
620 int low, mid, high, c = 0;
623 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
625 idxs[*last_i] = NULL;
638 mid = (low + high) / 2;
639 c = _cmp_sha(idx->cur, idxs[mid]->cur);
651 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
656 static uint32_t _get_idx_i(struct idx *idx)
658 if (idx->cur_name == NULL)
659 return idx->name_base;
660 return ntohl(*idx->cur_name) + idx->name_base;
663 #define MIDX4_HEADERLEN 12
665 static PyObject *merge_into(PyObject *self, PyObject *args)
667 PyObject *py_total, *ilist = NULL;
668 unsigned char *fmap = NULL;
669 struct sha *sha_ptr, *sha_start = NULL;
670 uint32_t *table_ptr, *name_ptr, *name_start;
671 struct idx **idxs = NULL;
675 uint32_t count, prefix;
679 if (!PyArg_ParseTuple(args, "w#iOO",
680 &fmap, &flen, &bits, &py_total, &ilist))
683 if (!bup_uint_from_py(&total, py_total, "total"))
686 num_i = PyList_Size(ilist);
687 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
689 for (i = 0; i < num_i; i++)
691 long len, sha_ofs, name_map_ofs;
692 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
693 PyObject *itup = PyList_GetItem(ilist, i);
694 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
695 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
697 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
698 idxs[i]->end = &idxs[i]->cur[len];
700 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
702 idxs[i]->cur_name = NULL;
704 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
705 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
706 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
715 if (count % 102424 == 0 && istty2)
716 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
717 count*100.0/total, count, total);
719 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
720 while (prefix < new_prefix)
721 table_ptr[prefix++] = htonl(count);
722 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
723 *name_ptr++ = htonl(_get_idx_i(idx));
725 if (idx->cur_name != NULL)
727 _fix_idx_order(idxs, &last_i);
730 while (prefix < (1<<bits))
731 table_ptr[prefix++] = htonl(count);
732 assert(count == total);
733 assert(prefix == (1<<bits));
734 assert(sha_ptr == sha_start+count);
735 assert(name_ptr == name_start+count);
738 return PyLong_FromUnsignedLong(count);
741 #define FAN_ENTRIES 256
743 static PyObject *write_idx(PyObject *self, PyObject *args)
745 char *filename = NULL;
746 PyObject *py_total, *idx = NULL;
748 unsigned char *fmap = NULL;
750 unsigned int total = 0;
752 int i, j, ofs64_count;
753 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
757 if (!PyArg_ParseTuple(args, "sw#OO",
758 &filename, &fmap, &flen, &idx, &py_total))
761 if (!bup_uint_from_py(&total, py_total, "total"))
764 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
765 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
768 const char idx_header[] = "\377tOc\0\0\0\002";
769 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
771 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
772 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
773 crc_ptr = (uint32_t *)&sha_ptr[total];
774 ofs_ptr = (uint32_t *)&crc_ptr[total];
775 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
779 for (i = 0; i < FAN_ENTRIES; ++i)
782 part = PyList_GET_ITEM(idx, i);
784 plen = PyList_GET_SIZE(part);
786 *fan_ptr++ = htonl(count);
787 for (j = 0; j < plen; ++j)
789 unsigned char *sha = NULL;
790 Py_ssize_t sha_len = 0;
791 PyObject *crc_py, *ofs_py;
793 unsigned PY_LONG_LONG ofs_ull;
795 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
796 &sha, &sha_len, &crc_py, &ofs_py))
798 if(!bup_uint_from_py(&crc, crc_py, "crc"))
800 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
802 assert(crc <= UINT32_MAX);
803 assert(ofs_ull <= UINT64_MAX);
805 if (sha_len != sizeof(struct sha))
807 memcpy(sha_ptr++, sha, sizeof(struct sha));
808 *crc_ptr++ = htonl(crc);
809 if (ofs > 0x7fffffff)
811 *ofs64_ptr++ = htonll(ofs);
812 ofs = 0x80000000 | ofs64_count++;
814 *ofs_ptr++ = htonl((uint32_t)ofs);
818 int rc = msync(fmap, flen, MS_ASYNC);
820 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
822 return PyLong_FromUnsignedLong(count);
826 // I would have made this a lower-level function that just fills in a buffer
827 // with random values, and then written those values from python. But that's
828 // about 20% slower in my tests, and since we typically generate random
829 // numbers for benchmarking other parts of bup, any slowness in generating
830 // random bytes will make our benchmarks inaccurate. Plus nobody wants
831 // pseudorandom bytes much except for this anyway.
832 static PyObject *write_random(PyObject *self, PyObject *args)
834 uint32_t buf[1024/4];
835 int fd = -1, seed = 0, verbose = 0;
837 long long len = 0, kbytes = 0, written = 0;
839 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
844 for (kbytes = 0; kbytes < len/1024; kbytes++)
847 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
849 ret = write(fd, buf, sizeof(buf));
853 if (ret < (int)sizeof(buf))
855 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
856 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
859 // handle non-multiples of 1024
863 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
865 ret = write(fd, buf, len % 1024);
872 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
873 return Py_BuildValue("L", written);
877 static PyObject *random_sha(PyObject *self, PyObject *args)
879 static int seeded = 0;
880 uint32_t shabuf[20/4];
885 assert(sizeof(shabuf) == 20);
890 if (!PyArg_ParseTuple(args, ""))
893 memset(shabuf, 0, sizeof(shabuf));
894 for (i=0; i < 20/4; i++)
895 shabuf[i] = random();
896 return Py_BuildValue("s#", shabuf, 20);
900 static int _open_noatime(const char *filename, int attrs)
902 int attrs_noatime, fd;
908 attrs |= O_LARGEFILE;
910 attrs_noatime = attrs;
912 attrs_noatime |= O_NOATIME;
914 fd = open(filename, attrs_noatime);
915 if (fd < 0 && errno == EPERM)
917 // older Linux kernels would return EPERM if you used O_NOATIME
918 // and weren't the file's owner. This pointless restriction was
919 // relaxed eventually, but we have to handle it anyway.
920 // (VERY old kernels didn't recognized O_NOATIME, but they would
921 // just harmlessly ignore it, so this branch won't trigger)
922 fd = open(filename, attrs);
928 static PyObject *open_noatime(PyObject *self, PyObject *args)
930 char *filename = NULL;
932 if (!PyArg_ParseTuple(args, "s", &filename))
934 fd = _open_noatime(filename, 0);
936 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
937 return Py_BuildValue("i", fd);
941 static PyObject *fadvise_done(PyObject *self, PyObject *args)
945 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
947 #ifdef POSIX_FADV_DONTNEED
948 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
950 return Py_BuildValue("");
954 // Currently the Linux kernel and FUSE disagree over the type for
955 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
956 // but FUSE chose long (matching the declaration in linux/fs.h). So
957 // if you use int, and then traverse a FUSE filesystem, you may
958 // corrupt the stack. But if you use long, then you may get invalid
959 // results on big-endian systems.
961 // For now, we just use long, and then disable Linux attrs entirely
962 // (with a warning) in helpers.py on systems that are affected.
964 #ifdef BUP_HAVE_FILE_ATTRS
965 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
972 if (!PyArg_ParseTuple(args, "s", &path))
975 fd = _open_noatime(path, O_NONBLOCK);
977 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
979 attr = 0; // Handle int/long mismatch (see above)
980 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
984 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
987 assert(attr <= UINT_MAX); // Kernel type is actually int
988 return PyLong_FromUnsignedLong(attr);
990 #endif /* def BUP_HAVE_FILE_ATTRS */
994 #ifdef BUP_HAVE_FILE_ATTRS
995 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
998 unsigned long orig_attr;
1004 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1007 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1010 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1012 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1014 // Restrict attr to modifiable flags acdeijstuADST -- see
1015 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1016 // in pf.c flags_array[].
1017 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1018 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1019 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1020 | FS_TOPDIR_FL | FS_NOCOW_FL;
1022 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1023 orig_attr = 0; // Handle int/long mismatch (see above)
1024 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1025 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1029 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1031 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1033 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1037 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1041 return Py_BuildValue("O", Py_None);
1043 #endif /* def BUP_HAVE_FILE_ATTRS */
1046 #ifndef HAVE_UTIMENSAT
1048 #error "cannot find utimensat or utimes()"
1050 #ifndef HAVE_LUTIMES
1051 #error "cannot find utimensat or lutimes()"
1055 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1059 const long long lltmp = PyLong_AsLongLong(pylong); \
1060 if (lltmp == -1 && PyErr_Occurred()) \
1062 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1064 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1065 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1067 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1073 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1081 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1090 #ifdef HAVE_UTIMENSAT
1092 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1097 PyObject *access_py, *modification_py;
1098 struct timespec ts[2];
1100 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1103 &access_py, &(ts[0].tv_nsec),
1104 &modification_py, &(ts[1].tv_nsec),
1109 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1112 PyErr_SetString(PyExc_ValueError,
1113 "unable to convert access time seconds for utimensat");
1116 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1119 PyErr_SetString(PyExc_ValueError,
1120 "unable to convert modification time seconds for utimensat");
1123 rc = utimensat(fd, path, ts, flag);
1125 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1127 return Py_BuildValue("O", Py_None);
1130 #endif /* def HAVE_UTIMENSAT */
1133 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1135 static int bup_parse_xutimes_args(char **path,
1136 struct timeval tv[2],
1139 PyObject *access_py, *modification_py;
1140 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1142 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1144 &access_py, &access_us,
1145 &modification_py, &modification_us))
1149 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1152 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1155 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1157 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1160 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1163 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1166 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1168 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1174 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1178 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1181 struct timeval tv[2];
1182 if (!bup_parse_xutimes_args(&path, tv, args))
1184 int rc = utimes(path, tv);
1186 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1187 return Py_BuildValue("O", Py_None);
1189 #endif /* def HAVE_UTIMES */
1193 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1196 struct timeval tv[2];
1197 if (!bup_parse_xutimes_args(&path, tv, args))
1199 int rc = lutimes(path, tv);
1201 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1203 return Py_BuildValue("O", Py_None);
1205 #endif /* def HAVE_LUTIMES */
1208 #ifdef HAVE_STAT_ST_ATIM
1209 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1210 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1211 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1212 #elif defined HAVE_STAT_ST_ATIMENSEC
1213 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1214 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1215 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1217 # define BUP_STAT_ATIME_NS(st) 0
1218 # define BUP_STAT_MTIME_NS(st) 0
1219 # define BUP_STAT_CTIME_NS(st) 0
1223 #pragma clang diagnostic push
1224 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1226 static PyObject *stat_struct_to_py(const struct stat *st,
1227 const char *filename,
1230 // We can check the known (via POSIX) signed and unsigned types at
1231 // compile time, but not (easily) the unspecified types, so handle
1232 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1234 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1235 INTEGER_TO_PY(st->st_mode),
1236 (unsigned PY_LONG_LONG) st->st_ino,
1237 INTEGER_TO_PY(st->st_dev),
1238 INTEGER_TO_PY(st->st_nlink),
1239 INTEGER_TO_PY(st->st_uid),
1240 INTEGER_TO_PY(st->st_gid),
1241 INTEGER_TO_PY(st->st_rdev),
1242 (PY_LONG_LONG) st->st_size,
1243 INTEGER_TO_PY(st->st_atime),
1244 (long) BUP_STAT_ATIME_NS(st),
1245 INTEGER_TO_PY(st->st_mtime),
1246 (long) BUP_STAT_MTIME_NS(st),
1247 INTEGER_TO_PY(st->st_ctime),
1248 (long) BUP_STAT_CTIME_NS(st));
1251 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1253 static PyObject *bup_stat(PyObject *self, PyObject *args)
1258 if (!PyArg_ParseTuple(args, "s", &filename))
1262 rc = stat(filename, &st);
1264 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1265 return stat_struct_to_py(&st, filename, 0);
1269 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1274 if (!PyArg_ParseTuple(args, "s", &filename))
1278 rc = lstat(filename, &st);
1280 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1281 return stat_struct_to_py(&st, filename, 0);
1285 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1289 if (!PyArg_ParseTuple(args, "i", &fd))
1293 rc = fstat(fd, &st);
1295 return PyErr_SetFromErrno(PyExc_OSError);
1296 return stat_struct_to_py(&st, NULL, fd);
1300 static PyMethodDef helper_methods[] = {
1301 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1302 "Write buf excepting zeros at the end. Return trailing zero count." },
1303 { "selftest", selftest, METH_VARARGS,
1304 "Check that the rolling checksum rolls correctly (for unit tests)." },
1305 { "blobbits", blobbits, METH_VARARGS,
1306 "Return the number of bits in the rolling checksum." },
1307 { "splitbuf", splitbuf, METH_VARARGS,
1308 "Split a list of strings based on a rolling checksum." },
1309 { "bitmatch", bitmatch, METH_VARARGS,
1310 "Count the number of matching prefix bits between two strings." },
1311 { "firstword", firstword, METH_VARARGS,
1312 "Return an int corresponding to the first 32 bits of buf." },
1313 { "bloom_contains", bloom_contains, METH_VARARGS,
1314 "Check if a bloom filter of 2^nbits bytes contains an object" },
1315 { "bloom_add", bloom_add, METH_VARARGS,
1316 "Add an object to a bloom filter of 2^nbits bytes" },
1317 { "extract_bits", extract_bits, METH_VARARGS,
1318 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1319 { "merge_into", merge_into, METH_VARARGS,
1320 "Merges a bunch of idx and midx files into a single midx." },
1321 { "write_idx", write_idx, METH_VARARGS,
1322 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1323 { "write_random", write_random, METH_VARARGS,
1324 "Write random bytes to the given file descriptor" },
1325 { "random_sha", random_sha, METH_VARARGS,
1326 "Return a random 20-byte string" },
1327 { "open_noatime", open_noatime, METH_VARARGS,
1328 "open() the given filename for read with O_NOATIME if possible" },
1329 { "fadvise_done", fadvise_done, METH_VARARGS,
1330 "Inform the kernel that we're finished with earlier parts of a file" },
1331 #ifdef BUP_HAVE_FILE_ATTRS
1332 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1333 "Return the Linux attributes for the given file." },
1335 #ifdef BUP_HAVE_FILE_ATTRS
1336 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1337 "Set the Linux attributes for the given file." },
1339 #ifdef HAVE_UTIMENSAT
1340 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1341 "Change path timestamps with nanosecond precision (POSIX)." },
1344 { "bup_utimes", bup_utimes, METH_VARARGS,
1345 "Change path timestamps with microsecond precision." },
1348 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1349 "Change path timestamps with microsecond precision;"
1350 " don't follow symlinks." },
1352 { "stat", bup_stat, METH_VARARGS,
1353 "Extended version of stat." },
1354 { "lstat", bup_lstat, METH_VARARGS,
1355 "Extended version of lstat." },
1356 { "fstat", bup_fstat, METH_VARARGS,
1357 "Extended version of fstat." },
1358 { NULL, NULL, 0, NULL }, // sentinel
1362 PyMODINIT_FUNC init_helpers(void)
1364 // FIXME: migrate these tests to configure. Check against the
1365 // type we're going to use when passing to python. Other stat
1366 // types are tested at runtime.
1367 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1368 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1369 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1370 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1371 // Just be sure (relevant when passing timestamps back to Python above).
1372 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1373 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1375 if (sizeof(off_t) < sizeof(int))
1377 // Originally required by append_sparse_region().
1378 fprintf(stderr, "sizeof(off_t) < sizeof(int); please report.\n");
1383 PyObject *m = Py_InitModule("_helpers", helper_methods);
1387 #pragma clang diagnostic push
1388 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1389 #ifdef HAVE_UTIMENSAT
1392 value = INTEGER_TO_PY(AT_FDCWD);
1393 PyObject_SetAttrString(m, "AT_FDCWD", value);
1395 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1396 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1398 value = INTEGER_TO_PY(UTIME_NOW);
1399 PyObject_SetAttrString(m, "UTIME_NOW", value);
1405 const long arg_max = sysconf(_SC_ARG_MAX);
1408 fprintf(stderr, "Cannot find SC_ARG_MAX, please report a bug.\n");
1411 value = INTEGER_TO_PY(arg_max);
1412 PyObject_SetAttrString(m, "SC_ARG_MAX", value);
1415 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1417 e = getenv("BUP_FORCE_TTY");
1418 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);