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_MMAN_H
22 #ifdef HAVE_SYS_TYPES_H
23 #include <sys/types.h>
25 #ifdef HAVE_SYS_STAT_H
32 #ifdef HAVE_LINUX_FS_H
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h>
39 #ifdef HAVE_TM_TM_GMTOFF
45 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
46 #define BUP_HAVE_FILE_ATTRS 1
50 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
51 * pretend we don't have it.
53 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
58 // Of course, this assumes it's a bitfield value.
63 typedef unsigned char byte;
65 static int istty2 = 0;
69 // This function should technically be macro'd out if it's going to be used
70 // more than ocasionally. As of this writing, it'll actually never be called
71 // in real world bup scenarios (because our packs are < MAX_INT bytes).
72 static uint64_t htonll(uint64_t value)
74 static const int endian_test = 42;
76 if (*(char *)&endian_test == endian_test) // LSB-MSB
77 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
78 return value; // already in network byte order MSB-LSB
83 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
86 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
90 // At the moment any code that calls INTGER_TO_PY() will have to
91 // disable -Wtautological-compare for clang. See below.
93 #define INTEGER_TO_PY(x) \
94 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
97 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
100 const long tmp = PyInt_AsLong(py);
101 if (tmp == -1 && PyErr_Occurred())
103 if (PyErr_ExceptionMatches(PyExc_OverflowError))
104 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
110 PyErr_Format(PyExc_OverflowError,
111 "negative %s cannot be converted to unsigned long", name);
119 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
122 return bup_ulong_from_pyint(x, py, name);
124 if (!PyLong_Check(py))
126 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
130 const unsigned long tmp = PyLong_AsUnsignedLong(py);
131 if (PyErr_Occurred())
133 if (PyErr_ExceptionMatches(PyExc_OverflowError))
134 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
143 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
146 if (!bup_ulong_from_py(&tmp, py, name))
151 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
158 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
164 if (bup_ulong_from_pyint(&tmp, py, name))
172 if (!PyLong_Check(py))
174 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
178 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
179 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
181 if (PyErr_ExceptionMatches(PyExc_OverflowError))
182 PyErr_Format(PyExc_OverflowError,
183 "%s too big for unsigned long long", name);
191 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
192 #if __WIN32__ || __CYGWIN__
194 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
195 static void unpythonize_argv(void) { }
197 #else // not __WIN32__
199 // For some reason this isn't declared in Python.h
200 extern void Py_GetArgcArgv(int *argc, char ***argv);
202 static void unpythonize_argv(void)
207 Py_GetArgcArgv(&argc, &argv);
209 for (i = 0; i < argc-1; i++)
211 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
213 // The argv block doesn't work the way we expected; it's unsafe
219 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
221 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
225 p = strrchr(argv[1], '/');
231 memmove(argv[0], p, len);
232 memset(arge - diff, 0, diff);
233 for (i = 0; i < argc; i++)
234 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
239 #endif // not __WIN32__ or __CYGWIN__
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 *append_sparse_region(const int fd, unsigned long long n)
273 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
275 const off_t off = lseek(fd, new_off, SEEK_CUR);
276 if (off == (off_t) -1)
277 return PyErr_SetFromErrno(PyExc_IOError);
284 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
286 unsigned long long prev_pending,
287 const unsigned long long count)
289 // Add count additional sparse zeros to prev_pending and store the
290 // result in new_pending, or if the total won't fit in
291 // new_pending, write some of the zeros to fd sparsely, and store
292 // the remaining sum in new_pending.
293 if (!uadd(new_pending, prev_pending, count))
295 PyObject *err = append_sparse_region(fd, prev_pending);
298 *new_pending = count;
304 static const byte * find_not_zero(const byte * const start,
305 const byte * const end)
307 // Return a pointer to first non-zero byte between start and end,
308 // or end if there isn't one.
309 assert(start <= end);
310 const unsigned char *cur = start;
311 while (cur < end && *cur == 0)
317 static const byte * const find_trailing_zeros(const byte * const start,
318 const byte * const end)
320 // Return a pointer to the start of any trailing run of zeros, or
321 // end if there isn't one.
322 assert(start <= end);
325 const byte * cur = end;
326 while (cur > start && *--cur == 0) {}
334 static const byte *find_non_sparse_end(const byte * const start,
335 const byte * const end,
336 const unsigned long long min_len)
338 // Return the first pointer to a min_len sparse block in [start,
339 // end) if there is one, otherwise a pointer to the start of any
340 // trailing run of zeros. If there are no trailing zeros, return
346 // Probe in min_len jumps, searching backward from the jump
347 // destination for a non-zero byte. If such a byte is found, move
348 // just past it and try again.
349 const byte *candidate = start;
350 // End of any run of zeros, starting at candidate, that we've already seen
351 const byte *end_of_known_zeros = candidate;
352 while (end - candidate >= min_len) // Handle all min_len candidate blocks
354 const byte * const probe_end = candidate + min_len;
355 const byte * const trailing_zeros =
356 find_trailing_zeros(end_of_known_zeros, probe_end);
357 if (trailing_zeros == probe_end)
358 end_of_known_zeros = candidate = probe_end;
359 else if (trailing_zeros == end_of_known_zeros)
361 assert(candidate >= start);
362 assert(candidate <= end);
363 assert(*candidate == 0);
368 candidate = trailing_zeros;
369 end_of_known_zeros = probe_end;
373 if (candidate == end)
376 // No min_len sparse run found, search backward from end
377 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
380 if (trailing_zeros == end_of_known_zeros)
382 assert(candidate >= start);
383 assert(candidate < end);
384 assert(*candidate == 0);
385 assert(end - candidate < min_len);
389 if (trailing_zeros == end)
391 assert(*(end - 1) != 0);
395 assert(end - trailing_zeros < min_len);
396 assert(trailing_zeros >= start);
397 assert(trailing_zeros < end);
398 assert(*trailing_zeros == 0);
399 return trailing_zeros;
403 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
406 unsigned char *buf = NULL;
408 PyObject *py_min_sparse_len, *py_prev_sparse_len;
409 if (!PyArg_ParseTuple(args, "it#OO",
410 &fd, &buf, &sbuf_len,
411 &py_min_sparse_len, &py_prev_sparse_len))
413 unsigned long long min_sparse_len, prev_sparse_len, buf_len;
414 if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
416 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
419 return PyErr_Format(PyExc_ValueError, "negative bufer length");
420 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
421 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
423 const byte * block = buf; // Start of pending block
424 const byte * const end = buf + buf_len;
425 unsigned long long zeros = prev_sparse_len;
428 assert(block <= end);
430 return PyLong_FromUnsignedLongLong(zeros);
434 // Look for the end of block, i.e. the next sparse run of
435 // at least min_sparse_len zeros, or the end of the
437 const byte * const probe = find_non_sparse_end(block + 1, end,
439 // Either at end of block, or end of non-sparse; write pending data
440 PyObject *err = append_sparse_region(fd, zeros);
443 int rc = write_all(fd, block, probe - block);
445 return PyErr_SetFromErrno(PyExc_IOError);
447 if (end - probe < min_sparse_len)
450 zeros = min_sparse_len;
451 block = probe + zeros;
455 // Should be in the first loop iteration, a sparse run of
456 // zeros, or nearly at the end of the block (within
458 const byte * const zeros_end = find_not_zero(block, end);
459 PyObject *err = record_sparse_zeros(&zeros, fd,
460 zeros, zeros_end - block);
463 assert(block <= zeros_end);
470 static PyObject *selftest(PyObject *self, PyObject *args)
472 if (!PyArg_ParseTuple(args, ""))
475 return Py_BuildValue("i", !bupsplit_selftest());
479 static PyObject *blobbits(PyObject *self, PyObject *args)
481 if (!PyArg_ParseTuple(args, ""))
483 return Py_BuildValue("i", BUP_BLOBBITS);
487 static PyObject *splitbuf(PyObject *self, PyObject *args)
489 unsigned char *buf = NULL;
491 int out = 0, bits = -1;
493 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
495 assert(len <= INT_MAX);
496 out = bupsplit_find_ofs(buf, len, &bits);
497 if (out) assert(bits >= BUP_BLOBBITS);
498 return Py_BuildValue("ii", out, bits);
502 static PyObject *bitmatch(PyObject *self, PyObject *args)
504 unsigned char *buf1 = NULL, *buf2 = NULL;
505 Py_ssize_t len1 = 0, len2 = 0;
509 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
513 for (byte = 0; byte < len1 && byte < len2; byte++)
515 int b1 = buf1[byte], b2 = buf2[byte];
518 for (bit = 0; bit < 8; bit++)
519 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
525 assert(byte <= (INT_MAX >> 3));
526 return Py_BuildValue("i", byte*8 + bit);
530 static PyObject *firstword(PyObject *self, PyObject *args)
532 unsigned char *buf = NULL;
536 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
542 v = ntohl(*(uint32_t *)buf);
543 return PyLong_FromUnsignedLong(v);
547 #define BLOOM2_HEADERLEN 16
549 static void to_bloom_address_bitmask4(const unsigned char *buf,
550 const int nbits, uint64_t *v, unsigned char *bitmask)
556 memcpy(&high, buf, 4);
557 mask = (1<<nbits) - 1;
558 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
559 bit = (raw >> (37-nbits)) & 0x7;
560 *v = (raw >> (40-nbits)) & mask;
564 static void to_bloom_address_bitmask5(const unsigned char *buf,
565 const int nbits, uint32_t *v, unsigned char *bitmask)
571 memcpy(&high, buf, 4);
572 mask = (1<<nbits) - 1;
574 bit = (raw >> (29-nbits)) & 0x7;
575 *v = (raw >> (32-nbits)) & mask;
579 #define BLOOM_SET_BIT(name, address, otype) \
580 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
582 unsigned char bitmask;\
584 address(buf, nbits, &v, &bitmask);\
585 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
587 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
588 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
591 #define BLOOM_GET_BIT(name, address, otype) \
592 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
594 unsigned char bitmask;\
596 address(buf, nbits, &v, &bitmask);\
597 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
599 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
600 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
603 static PyObject *bloom_add(PyObject *self, PyObject *args)
605 unsigned char *sha = NULL, *bloom = NULL;
607 Py_ssize_t len = 0, blen = 0;
608 int nbits = 0, k = 0;
610 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
613 if (blen < 16+(1<<nbits) || len % 20 != 0)
620 for (end = sha + len; sha < end; sha += 20/k)
621 bloom_set_bit5(bloom, sha, nbits);
627 for (end = sha + len; sha < end; sha += 20/k)
628 bloom_set_bit4(bloom, sha, nbits);
634 return Py_BuildValue("n", len/20);
637 static PyObject *bloom_contains(PyObject *self, PyObject *args)
639 unsigned char *sha = NULL, *bloom = NULL;
640 Py_ssize_t len = 0, blen = 0;
641 int nbits = 0, k = 0;
645 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
655 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
656 if (!bloom_get_bit5(bloom, sha, nbits))
657 return Py_BuildValue("Oi", Py_None, steps);
663 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
664 if (!bloom_get_bit4(bloom, sha, nbits))
665 return Py_BuildValue("Oi", Py_None, steps);
670 return Py_BuildValue("ii", 1, k);
674 static uint32_t _extract_bits(unsigned char *buf, int nbits)
678 mask = (1<<nbits) - 1;
679 v = ntohl(*(uint32_t *)buf);
680 v = (v >> (32-nbits)) & mask;
685 static PyObject *extract_bits(PyObject *self, PyObject *args)
687 unsigned char *buf = NULL;
691 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
697 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
702 unsigned char bytes[20];
716 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
719 for (i = 0; i < sizeof(struct sha); i++)
720 if (sha1->bytes[i] != sha2->bytes[i])
721 return sha1->bytes[i] - sha2->bytes[i];
726 static void _fix_idx_order(struct idx **idxs, int *last_i)
729 int low, mid, high, c = 0;
732 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
734 idxs[*last_i] = NULL;
747 mid = (low + high) / 2;
748 c = _cmp_sha(idx->cur, idxs[mid]->cur);
760 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
765 static uint32_t _get_idx_i(struct idx *idx)
767 if (idx->cur_name == NULL)
768 return idx->name_base;
769 return ntohl(*idx->cur_name) + idx->name_base;
772 #define MIDX4_HEADERLEN 12
774 static PyObject *merge_into(PyObject *self, PyObject *args)
776 PyObject *py_total, *ilist = NULL;
777 unsigned char *fmap = NULL;
778 struct sha *sha_ptr, *sha_start = NULL;
779 uint32_t *table_ptr, *name_ptr, *name_start;
780 struct idx **idxs = NULL;
784 uint32_t count, prefix;
788 if (!PyArg_ParseTuple(args, "w#iOO",
789 &fmap, &flen, &bits, &py_total, &ilist))
792 if (!bup_uint_from_py(&total, py_total, "total"))
795 num_i = PyList_Size(ilist);
796 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
798 for (i = 0; i < num_i; i++)
800 long len, sha_ofs, name_map_ofs;
801 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
802 PyObject *itup = PyList_GetItem(ilist, i);
803 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
804 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
806 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
807 idxs[i]->end = &idxs[i]->cur[len];
809 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
811 idxs[i]->cur_name = NULL;
813 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
814 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
815 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
824 if (count % 102424 == 0 && istty2)
825 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
826 count*100.0/total, count, total);
828 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
829 while (prefix < new_prefix)
830 table_ptr[prefix++] = htonl(count);
831 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
832 *name_ptr++ = htonl(_get_idx_i(idx));
834 if (idx->cur_name != NULL)
836 _fix_idx_order(idxs, &last_i);
839 while (prefix < (1<<bits))
840 table_ptr[prefix++] = htonl(count);
841 assert(count == total);
842 assert(prefix == (1<<bits));
843 assert(sha_ptr == sha_start+count);
844 assert(name_ptr == name_start+count);
847 return PyLong_FromUnsignedLong(count);
850 #define FAN_ENTRIES 256
852 static PyObject *write_idx(PyObject *self, PyObject *args)
854 char *filename = NULL;
855 PyObject *py_total, *idx = NULL;
857 unsigned char *fmap = NULL;
859 unsigned int total = 0;
861 int i, j, ofs64_count;
862 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
866 if (!PyArg_ParseTuple(args, "sw#OO",
867 &filename, &fmap, &flen, &idx, &py_total))
870 if (!bup_uint_from_py(&total, py_total, "total"))
873 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
874 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
877 const char idx_header[] = "\377tOc\0\0\0\002";
878 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
880 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
881 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
882 crc_ptr = (uint32_t *)&sha_ptr[total];
883 ofs_ptr = (uint32_t *)&crc_ptr[total];
884 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
888 for (i = 0; i < FAN_ENTRIES; ++i)
891 part = PyList_GET_ITEM(idx, i);
893 plen = PyList_GET_SIZE(part);
895 *fan_ptr++ = htonl(count);
896 for (j = 0; j < plen; ++j)
898 unsigned char *sha = NULL;
899 Py_ssize_t sha_len = 0;
900 PyObject *crc_py, *ofs_py;
902 unsigned PY_LONG_LONG ofs_ull;
904 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
905 &sha, &sha_len, &crc_py, &ofs_py))
907 if(!bup_uint_from_py(&crc, crc_py, "crc"))
909 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
911 assert(crc <= UINT32_MAX);
912 assert(ofs_ull <= UINT64_MAX);
914 if (sha_len != sizeof(struct sha))
916 memcpy(sha_ptr++, sha, sizeof(struct sha));
917 *crc_ptr++ = htonl(crc);
918 if (ofs > 0x7fffffff)
920 *ofs64_ptr++ = htonll(ofs);
921 ofs = 0x80000000 | ofs64_count++;
923 *ofs_ptr++ = htonl((uint32_t)ofs);
927 int rc = msync(fmap, flen, MS_ASYNC);
929 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
931 return PyLong_FromUnsignedLong(count);
935 // I would have made this a lower-level function that just fills in a buffer
936 // with random values, and then written those values from python. But that's
937 // about 20% slower in my tests, and since we typically generate random
938 // numbers for benchmarking other parts of bup, any slowness in generating
939 // random bytes will make our benchmarks inaccurate. Plus nobody wants
940 // pseudorandom bytes much except for this anyway.
941 static PyObject *write_random(PyObject *self, PyObject *args)
943 uint32_t buf[1024/4];
944 int fd = -1, seed = 0, verbose = 0;
946 long long len = 0, kbytes = 0, written = 0;
948 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
953 for (kbytes = 0; kbytes < len/1024; kbytes++)
956 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
958 ret = write(fd, buf, sizeof(buf));
962 if (ret < (int)sizeof(buf))
964 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
965 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
968 // handle non-multiples of 1024
972 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
974 ret = write(fd, buf, len % 1024);
981 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
982 return Py_BuildValue("L", written);
986 static PyObject *random_sha(PyObject *self, PyObject *args)
988 static int seeded = 0;
989 uint32_t shabuf[20/4];
994 assert(sizeof(shabuf) == 20);
999 if (!PyArg_ParseTuple(args, ""))
1002 memset(shabuf, 0, sizeof(shabuf));
1003 for (i=0; i < 20/4; i++)
1004 shabuf[i] = random();
1005 return Py_BuildValue("s#", shabuf, 20);
1009 static int _open_noatime(const char *filename, int attrs)
1011 int attrs_noatime, fd;
1014 attrs |= O_NOFOLLOW;
1017 attrs |= O_LARGEFILE;
1019 attrs_noatime = attrs;
1021 attrs_noatime |= O_NOATIME;
1023 fd = open(filename, attrs_noatime);
1024 if (fd < 0 && errno == EPERM)
1026 // older Linux kernels would return EPERM if you used O_NOATIME
1027 // and weren't the file's owner. This pointless restriction was
1028 // relaxed eventually, but we have to handle it anyway.
1029 // (VERY old kernels didn't recognized O_NOATIME, but they would
1030 // just harmlessly ignore it, so this branch won't trigger)
1031 fd = open(filename, attrs);
1037 static PyObject *open_noatime(PyObject *self, PyObject *args)
1039 char *filename = NULL;
1041 if (!PyArg_ParseTuple(args, "s", &filename))
1043 fd = _open_noatime(filename, 0);
1045 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1046 return Py_BuildValue("i", fd);
1050 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1053 long long llofs, lllen = 0;
1054 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1057 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1058 return PyErr_Format(PyExc_OverflowError,
1059 "fadvise offset overflows off_t");
1060 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1061 return PyErr_Format(PyExc_OverflowError,
1062 "fadvise length overflows off_t");
1063 #ifdef POSIX_FADV_DONTNEED
1064 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1066 return Py_BuildValue("");
1070 // Currently the Linux kernel and FUSE disagree over the type for
1071 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1072 // but FUSE chose long (matching the declaration in linux/fs.h). So
1073 // if you use int, and then traverse a FUSE filesystem, you may
1074 // corrupt the stack. But if you use long, then you may get invalid
1075 // results on big-endian systems.
1077 // For now, we just use long, and then disable Linux attrs entirely
1078 // (with a warning) in helpers.py on systems that are affected.
1080 #ifdef BUP_HAVE_FILE_ATTRS
1081 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1088 if (!PyArg_ParseTuple(args, "s", &path))
1091 fd = _open_noatime(path, O_NONBLOCK);
1093 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1095 attr = 0; // Handle int/long mismatch (see above)
1096 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1100 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1103 assert(attr <= UINT_MAX); // Kernel type is actually int
1104 return PyLong_FromUnsignedLong(attr);
1106 #endif /* def BUP_HAVE_FILE_ATTRS */
1110 #ifdef BUP_HAVE_FILE_ATTRS
1111 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1114 unsigned long orig_attr;
1120 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1123 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1126 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1128 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1130 // Restrict attr to modifiable flags acdeijstuADST -- see
1131 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1132 // in pf.c flags_array[].
1133 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1134 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1135 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1136 | FS_TOPDIR_FL | FS_NOCOW_FL;
1138 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1139 orig_attr = 0; // Handle int/long mismatch (see above)
1140 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1141 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1145 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1147 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1149 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1153 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1157 return Py_BuildValue("O", Py_None);
1159 #endif /* def BUP_HAVE_FILE_ATTRS */
1162 #ifndef HAVE_UTIMENSAT
1164 #error "cannot find utimensat or utimes()"
1166 #ifndef HAVE_LUTIMES
1167 #error "cannot find utimensat or lutimes()"
1171 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1175 const long long lltmp = PyLong_AsLongLong(pylong); \
1176 if (lltmp == -1 && PyErr_Occurred()) \
1178 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1180 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1181 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1183 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1189 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1197 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1206 #ifdef HAVE_UTIMENSAT
1208 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1213 PyObject *access_py, *modification_py;
1214 struct timespec ts[2];
1216 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1219 &access_py, &(ts[0].tv_nsec),
1220 &modification_py, &(ts[1].tv_nsec),
1225 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1228 PyErr_SetString(PyExc_ValueError,
1229 "unable to convert access time seconds for utimensat");
1232 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1235 PyErr_SetString(PyExc_ValueError,
1236 "unable to convert modification time seconds for utimensat");
1239 rc = utimensat(fd, path, ts, flag);
1241 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1243 return Py_BuildValue("O", Py_None);
1246 #endif /* def HAVE_UTIMENSAT */
1249 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1251 static int bup_parse_xutimes_args(char **path,
1252 struct timeval tv[2],
1255 PyObject *access_py, *modification_py;
1256 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1258 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1260 &access_py, &access_us,
1261 &modification_py, &modification_us))
1265 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1268 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1271 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1273 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1276 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1279 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1282 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1284 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1290 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1294 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1297 struct timeval tv[2];
1298 if (!bup_parse_xutimes_args(&path, tv, args))
1300 int rc = utimes(path, tv);
1302 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1303 return Py_BuildValue("O", Py_None);
1305 #endif /* def HAVE_UTIMES */
1309 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1312 struct timeval tv[2];
1313 if (!bup_parse_xutimes_args(&path, tv, args))
1315 int rc = lutimes(path, tv);
1317 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1319 return Py_BuildValue("O", Py_None);
1321 #endif /* def HAVE_LUTIMES */
1324 #ifdef HAVE_STAT_ST_ATIM
1325 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1326 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1327 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1328 #elif defined HAVE_STAT_ST_ATIMENSEC
1329 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1330 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1331 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1333 # define BUP_STAT_ATIME_NS(st) 0
1334 # define BUP_STAT_MTIME_NS(st) 0
1335 # define BUP_STAT_CTIME_NS(st) 0
1339 #pragma clang diagnostic push
1340 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1342 static PyObject *stat_struct_to_py(const struct stat *st,
1343 const char *filename,
1346 // We can check the known (via POSIX) signed and unsigned types at
1347 // compile time, but not (easily) the unspecified types, so handle
1348 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1350 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1351 INTEGER_TO_PY(st->st_mode),
1352 (unsigned PY_LONG_LONG) st->st_ino,
1353 INTEGER_TO_PY(st->st_dev),
1354 INTEGER_TO_PY(st->st_nlink),
1355 INTEGER_TO_PY(st->st_uid),
1356 INTEGER_TO_PY(st->st_gid),
1357 INTEGER_TO_PY(st->st_rdev),
1358 (PY_LONG_LONG) st->st_size,
1359 INTEGER_TO_PY(st->st_atime),
1360 (long) BUP_STAT_ATIME_NS(st),
1361 INTEGER_TO_PY(st->st_mtime),
1362 (long) BUP_STAT_MTIME_NS(st),
1363 INTEGER_TO_PY(st->st_ctime),
1364 (long) BUP_STAT_CTIME_NS(st));
1367 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1369 static PyObject *bup_stat(PyObject *self, PyObject *args)
1374 if (!PyArg_ParseTuple(args, "s", &filename))
1378 rc = stat(filename, &st);
1380 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1381 return stat_struct_to_py(&st, filename, 0);
1385 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1390 if (!PyArg_ParseTuple(args, "s", &filename))
1394 rc = lstat(filename, &st);
1396 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1397 return stat_struct_to_py(&st, filename, 0);
1401 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1405 if (!PyArg_ParseTuple(args, "i", &fd))
1409 rc = fstat(fd, &st);
1411 return PyErr_SetFromErrno(PyExc_OSError);
1412 return stat_struct_to_py(&st, NULL, fd);
1416 #ifdef HAVE_TM_TM_GMTOFF
1417 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1421 if (!PyArg_ParseTuple(args, "L", &lltime))
1423 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1424 return PyErr_Format(PyExc_OverflowError, "time value too large");
1428 if(localtime_r(&ttime, &tm) == NULL)
1429 return PyErr_SetFromErrno(PyExc_OSError);
1431 // Match the Python struct_time values.
1432 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1433 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1434 tm.tm_hour, tm.tm_min, tm.tm_sec,
1435 tm.tm_wday, tm.tm_yday + 1,
1436 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1438 #endif /* def HAVE_TM_TM_GMTOFF */
1441 #ifdef BUP_MINCORE_BUF_TYPE
1442 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1445 Py_ssize_t src_ssize;
1447 PyObject *py_src_n, *py_src_off, *py_dest_off;
1448 if (!PyArg_ParseTuple(args, "s#OOw*O",
1449 &src, &src_ssize, &py_src_n, &py_src_off,
1450 &dest, &py_dest_off))
1453 unsigned long long src_size, src_n, src_off, dest_size, dest_off;
1454 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1455 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1456 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1459 if (!INTEGRAL_ASSIGNMENT_FITS(&src_size, src_ssize))
1460 return PyErr_Format(PyExc_OverflowError, "invalid src size");
1461 unsigned long long src_region_end;
1463 if (!uadd(&src_region_end, src_off, src_n))
1464 return PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1465 if (src_region_end > src_size)
1466 return PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1468 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len))
1469 return PyErr_Format(PyExc_OverflowError, "invalid dest size");
1470 if (dest_off > dest_size)
1471 return PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1474 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n))
1475 return PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1476 int rc = mincore((void *)(src + src_off), src_n,
1477 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1479 return PyErr_SetFromErrno(PyExc_OSError);
1480 return Py_BuildValue("O", Py_None);
1482 #endif /* def BUP_MINCORE_BUF_TYPE */
1485 static PyMethodDef helper_methods[] = {
1486 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1487 "Write buf excepting zeros at the end. Return trailing zero count." },
1488 { "selftest", selftest, METH_VARARGS,
1489 "Check that the rolling checksum rolls correctly (for unit tests)." },
1490 { "blobbits", blobbits, METH_VARARGS,
1491 "Return the number of bits in the rolling checksum." },
1492 { "splitbuf", splitbuf, METH_VARARGS,
1493 "Split a list of strings based on a rolling checksum." },
1494 { "bitmatch", bitmatch, METH_VARARGS,
1495 "Count the number of matching prefix bits between two strings." },
1496 { "firstword", firstword, METH_VARARGS,
1497 "Return an int corresponding to the first 32 bits of buf." },
1498 { "bloom_contains", bloom_contains, METH_VARARGS,
1499 "Check if a bloom filter of 2^nbits bytes contains an object" },
1500 { "bloom_add", bloom_add, METH_VARARGS,
1501 "Add an object to a bloom filter of 2^nbits bytes" },
1502 { "extract_bits", extract_bits, METH_VARARGS,
1503 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1504 { "merge_into", merge_into, METH_VARARGS,
1505 "Merges a bunch of idx and midx files into a single midx." },
1506 { "write_idx", write_idx, METH_VARARGS,
1507 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1508 { "write_random", write_random, METH_VARARGS,
1509 "Write random bytes to the given file descriptor" },
1510 { "random_sha", random_sha, METH_VARARGS,
1511 "Return a random 20-byte string" },
1512 { "open_noatime", open_noatime, METH_VARARGS,
1513 "open() the given filename for read with O_NOATIME if possible" },
1514 { "fadvise_done", fadvise_done, METH_VARARGS,
1515 "Inform the kernel that we're finished with earlier parts of a file" },
1516 #ifdef BUP_HAVE_FILE_ATTRS
1517 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1518 "Return the Linux attributes for the given file." },
1520 #ifdef BUP_HAVE_FILE_ATTRS
1521 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1522 "Set the Linux attributes for the given file." },
1524 #ifdef HAVE_UTIMENSAT
1525 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1526 "Change path timestamps with nanosecond precision (POSIX)." },
1529 { "bup_utimes", bup_utimes, METH_VARARGS,
1530 "Change path timestamps with microsecond precision." },
1533 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1534 "Change path timestamps with microsecond precision;"
1535 " don't follow symlinks." },
1537 { "stat", bup_stat, METH_VARARGS,
1538 "Extended version of stat." },
1539 { "lstat", bup_lstat, METH_VARARGS,
1540 "Extended version of lstat." },
1541 { "fstat", bup_fstat, METH_VARARGS,
1542 "Extended version of fstat." },
1543 #ifdef HAVE_TM_TM_GMTOFF
1544 { "localtime", bup_localtime, METH_VARARGS,
1545 "Return struct_time elements plus the timezone offset and name." },
1547 #ifdef BUP_MINCORE_BUF_TYPE
1548 { "mincore", bup_mincore, METH_VARARGS,
1549 "For mincore(src, src_n, src_off, dest, dest_off)"
1550 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1552 { NULL, NULL, 0, NULL }, // sentinel
1556 PyMODINIT_FUNC init_helpers(void)
1558 // FIXME: migrate these tests to configure. Check against the
1559 // type we're going to use when passing to python. Other stat
1560 // types are tested at runtime.
1561 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1562 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1563 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1564 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1565 // Just be sure (relevant when passing timestamps back to Python above).
1566 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1567 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1569 // Originally required by append_sparse_region()
1572 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1574 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1580 PyObject *m = Py_InitModule("_helpers", helper_methods);
1584 #pragma clang diagnostic push
1585 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1588 value = INTEGER_TO_PY(INT_MAX);
1589 PyObject_SetAttrString(m, "INT_MAX", value);
1591 value = INTEGER_TO_PY(UINT_MAX);
1592 PyObject_SetAttrString(m, "UINT_MAX", value);
1595 #ifdef HAVE_UTIMENSAT
1598 value = INTEGER_TO_PY(AT_FDCWD);
1599 PyObject_SetAttrString(m, "AT_FDCWD", value);
1601 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1602 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1604 value = INTEGER_TO_PY(UTIME_NOW);
1605 PyObject_SetAttrString(m, "UTIME_NOW", value);
1609 #ifdef BUP_HAVE_MINCORE_INCORE
1612 value = INTEGER_TO_PY(MINCORE_INCORE);
1613 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1617 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1619 e = getenv("BUP_FORCE_TTY");
1620 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);