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 // Of course, this assumes it's a bitfield value.
47 static int istty2 = 0;
49 // At the moment any code that calls INTGER_TO_PY() will have to
50 // disable -Wtautological-compare for clang. See below.
52 #define INTEGER_TO_PY(x) \
53 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
56 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
59 const long tmp = PyInt_AsLong(py);
60 if (tmp == -1 && PyErr_Occurred())
62 if (PyErr_ExceptionMatches(PyExc_OverflowError))
63 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
69 PyErr_Format(PyExc_OverflowError,
70 "negative %s cannot be converted to unsigned long", name);
78 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
81 return bup_ulong_from_pyint(x, py, name);
83 if (!PyLong_Check(py))
85 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
89 const unsigned long tmp = PyLong_AsUnsignedLong(py);
92 if (PyErr_ExceptionMatches(PyExc_OverflowError))
93 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
102 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
105 if (!bup_ulong_from_py(&tmp, py, name))
110 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
117 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
123 if (bup_ulong_from_pyint(&tmp, py, name))
131 if (!PyLong_Check(py))
133 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
137 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
138 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
140 if (PyErr_ExceptionMatches(PyExc_OverflowError))
141 PyErr_Format(PyExc_OverflowError,
142 "%s too big for unsigned long long", name);
150 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
151 #if __WIN32__ || __CYGWIN__
153 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
154 static void unpythonize_argv(void) { }
156 #else // not __WIN32__
158 // For some reason this isn't declared in Python.h
159 extern void Py_GetArgcArgv(int *argc, char ***argv);
161 static void unpythonize_argv(void)
166 Py_GetArgcArgv(&argc, &argv);
168 for (i = 0; i < argc-1; i++)
170 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
172 // The argv block doesn't work the way we expected; it's unsafe
178 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
180 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
184 p = strrchr(argv[1], '/');
190 memmove(argv[0], p, len);
191 memset(arge - diff, 0, diff);
192 for (i = 0; i < argc; i++)
193 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
198 #endif // not __WIN32__ or __CYGWIN__
201 static PyObject *selftest(PyObject *self, PyObject *args)
203 if (!PyArg_ParseTuple(args, ""))
206 return Py_BuildValue("i", !bupsplit_selftest());
210 static PyObject *blobbits(PyObject *self, PyObject *args)
212 if (!PyArg_ParseTuple(args, ""))
214 return Py_BuildValue("i", BUP_BLOBBITS);
218 static PyObject *splitbuf(PyObject *self, PyObject *args)
220 unsigned char *buf = NULL;
222 int out = 0, bits = -1;
224 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
226 assert(len <= INT_MAX);
227 out = bupsplit_find_ofs(buf, len, &bits);
228 if (out) assert(bits >= BUP_BLOBBITS);
229 return Py_BuildValue("ii", out, bits);
233 static PyObject *bitmatch(PyObject *self, PyObject *args)
235 unsigned char *buf1 = NULL, *buf2 = NULL;
236 Py_ssize_t len1 = 0, len2 = 0;
240 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
244 for (byte = 0; byte < len1 && byte < len2; byte++)
246 int b1 = buf1[byte], b2 = buf2[byte];
249 for (bit = 0; bit < 8; bit++)
250 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
256 assert(byte <= (INT_MAX >> 3));
257 return Py_BuildValue("i", byte*8 + bit);
261 static PyObject *firstword(PyObject *self, PyObject *args)
263 unsigned char *buf = NULL;
267 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
273 v = ntohl(*(uint32_t *)buf);
274 return PyLong_FromUnsignedLong(v);
278 #define BLOOM2_HEADERLEN 16
280 static void to_bloom_address_bitmask4(const unsigned char *buf,
281 const int nbits, uint64_t *v, unsigned char *bitmask)
287 memcpy(&high, buf, 4);
288 mask = (1<<nbits) - 1;
289 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
290 bit = (raw >> (37-nbits)) & 0x7;
291 *v = (raw >> (40-nbits)) & mask;
295 static void to_bloom_address_bitmask5(const unsigned char *buf,
296 const int nbits, uint32_t *v, unsigned char *bitmask)
302 memcpy(&high, buf, 4);
303 mask = (1<<nbits) - 1;
305 bit = (raw >> (29-nbits)) & 0x7;
306 *v = (raw >> (32-nbits)) & mask;
310 #define BLOOM_SET_BIT(name, address, otype) \
311 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
313 unsigned char bitmask;\
315 address(buf, nbits, &v, &bitmask);\
316 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
318 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
319 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
322 #define BLOOM_GET_BIT(name, address, otype) \
323 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
325 unsigned char bitmask;\
327 address(buf, nbits, &v, &bitmask);\
328 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
330 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
331 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
334 static PyObject *bloom_add(PyObject *self, PyObject *args)
336 unsigned char *sha = NULL, *bloom = NULL;
338 Py_ssize_t len = 0, blen = 0;
339 int nbits = 0, k = 0;
341 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
344 if (blen < 16+(1<<nbits) || len % 20 != 0)
351 for (end = sha + len; sha < end; sha += 20/k)
352 bloom_set_bit5(bloom, sha, nbits);
358 for (end = sha + len; sha < end; sha += 20/k)
359 bloom_set_bit4(bloom, sha, nbits);
365 return Py_BuildValue("n", len/20);
368 static PyObject *bloom_contains(PyObject *self, PyObject *args)
370 unsigned char *sha = NULL, *bloom = NULL;
371 Py_ssize_t len = 0, blen = 0;
372 int nbits = 0, k = 0;
376 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
386 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
387 if (!bloom_get_bit5(bloom, sha, nbits))
388 return Py_BuildValue("Oi", Py_None, steps);
394 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
395 if (!bloom_get_bit4(bloom, sha, nbits))
396 return Py_BuildValue("Oi", Py_None, steps);
401 return Py_BuildValue("ii", 1, k);
405 static uint32_t _extract_bits(unsigned char *buf, int nbits)
409 mask = (1<<nbits) - 1;
410 v = ntohl(*(uint32_t *)buf);
411 v = (v >> (32-nbits)) & mask;
416 static PyObject *extract_bits(PyObject *self, PyObject *args)
418 unsigned char *buf = NULL;
422 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
428 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
433 unsigned char bytes[20];
447 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
450 for (i = 0; i < sizeof(struct sha); i++)
451 if (sha1->bytes[i] != sha2->bytes[i])
452 return sha1->bytes[i] - sha2->bytes[i];
457 static void _fix_idx_order(struct idx **idxs, int *last_i)
460 int low, mid, high, c = 0;
463 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
465 idxs[*last_i] = NULL;
478 mid = (low + high) / 2;
479 c = _cmp_sha(idx->cur, idxs[mid]->cur);
491 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
496 static uint32_t _get_idx_i(struct idx *idx)
498 if (idx->cur_name == NULL)
499 return idx->name_base;
500 return ntohl(*idx->cur_name) + idx->name_base;
503 #define MIDX4_HEADERLEN 12
505 static PyObject *merge_into(PyObject *self, PyObject *args)
507 PyObject *py_total, *ilist = NULL;
508 unsigned char *fmap = NULL;
509 struct sha *sha_ptr, *sha_start = NULL;
510 uint32_t *table_ptr, *name_ptr, *name_start;
511 struct idx **idxs = NULL;
515 uint32_t count, prefix;
519 if (!PyArg_ParseTuple(args, "w#iOO",
520 &fmap, &flen, &bits, &py_total, &ilist))
523 if (!bup_uint_from_py(&total, py_total, "total"))
526 num_i = PyList_Size(ilist);
527 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
529 for (i = 0; i < num_i; i++)
531 long len, sha_ofs, name_map_ofs;
532 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
533 PyObject *itup = PyList_GetItem(ilist, i);
534 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
535 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
537 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
538 idxs[i]->end = &idxs[i]->cur[len];
540 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
542 idxs[i]->cur_name = NULL;
544 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
545 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
546 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
555 if (count % 102424 == 0 && istty2)
556 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
557 count*100.0/total, count, total);
559 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
560 while (prefix < new_prefix)
561 table_ptr[prefix++] = htonl(count);
562 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
563 *name_ptr++ = htonl(_get_idx_i(idx));
565 if (idx->cur_name != NULL)
567 _fix_idx_order(idxs, &last_i);
570 while (prefix < (1<<bits))
571 table_ptr[prefix++] = htonl(count);
572 assert(count == total);
573 assert(prefix == (1<<bits));
574 assert(sha_ptr == sha_start+count);
575 assert(name_ptr == name_start+count);
578 return PyLong_FromUnsignedLong(count);
581 // This function should technically be macro'd out if it's going to be used
582 // more than ocasionally. As of this writing, it'll actually never be called
583 // in real world bup scenarios (because our packs are < MAX_INT bytes).
584 static uint64_t htonll(uint64_t value)
586 static const int endian_test = 42;
588 if (*(char *)&endian_test == endian_test) // LSB-MSB
589 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
590 return value; // already in network byte order MSB-LSB
593 #define FAN_ENTRIES 256
595 static PyObject *write_idx(PyObject *self, PyObject *args)
597 char *filename = NULL;
598 PyObject *py_total, *idx = NULL;
600 unsigned char *fmap = NULL;
602 unsigned int total = 0;
604 int i, j, ofs64_count;
605 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
609 if (!PyArg_ParseTuple(args, "sw#OO",
610 &filename, &fmap, &flen, &idx, &py_total))
613 if (!bup_uint_from_py(&total, py_total, "total"))
616 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
617 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
620 const char idx_header[] = "\377tOc\0\0\0\002";
621 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
623 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
624 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
625 crc_ptr = (uint32_t *)&sha_ptr[total];
626 ofs_ptr = (uint32_t *)&crc_ptr[total];
627 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
631 for (i = 0; i < FAN_ENTRIES; ++i)
634 part = PyList_GET_ITEM(idx, i);
636 plen = PyList_GET_SIZE(part);
638 *fan_ptr++ = htonl(count);
639 for (j = 0; j < plen; ++j)
641 unsigned char *sha = NULL;
642 Py_ssize_t sha_len = 0;
643 PyObject *crc_py, *ofs_py;
645 unsigned PY_LONG_LONG ofs_ull;
647 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
648 &sha, &sha_len, &crc_py, &ofs_py))
650 if(!bup_uint_from_py(&crc, crc_py, "crc"))
652 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
654 assert(crc <= UINT32_MAX);
655 assert(ofs_ull <= UINT64_MAX);
657 if (sha_len != sizeof(struct sha))
659 memcpy(sha_ptr++, sha, sizeof(struct sha));
660 *crc_ptr++ = htonl(crc);
661 if (ofs > 0x7fffffff)
663 *ofs64_ptr++ = htonll(ofs);
664 ofs = 0x80000000 | ofs64_count++;
666 *ofs_ptr++ = htonl((uint32_t)ofs);
670 int rc = msync(fmap, flen, MS_ASYNC);
672 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
674 return PyLong_FromUnsignedLong(count);
678 // I would have made this a lower-level function that just fills in a buffer
679 // with random values, and then written those values from python. But that's
680 // about 20% slower in my tests, and since we typically generate random
681 // numbers for benchmarking other parts of bup, any slowness in generating
682 // random bytes will make our benchmarks inaccurate. Plus nobody wants
683 // pseudorandom bytes much except for this anyway.
684 static PyObject *write_random(PyObject *self, PyObject *args)
686 uint32_t buf[1024/4];
687 int fd = -1, seed = 0, verbose = 0;
689 long long len = 0, kbytes = 0, written = 0;
691 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
696 for (kbytes = 0; kbytes < len/1024; kbytes++)
699 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
701 ret = write(fd, buf, sizeof(buf));
705 if (ret < (int)sizeof(buf))
707 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
708 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
711 // handle non-multiples of 1024
715 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
717 ret = write(fd, buf, len % 1024);
724 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
725 return Py_BuildValue("L", written);
729 static PyObject *random_sha(PyObject *self, PyObject *args)
731 static int seeded = 0;
732 uint32_t shabuf[20/4];
737 assert(sizeof(shabuf) == 20);
742 if (!PyArg_ParseTuple(args, ""))
745 memset(shabuf, 0, sizeof(shabuf));
746 for (i=0; i < 20/4; i++)
747 shabuf[i] = random();
748 return Py_BuildValue("s#", shabuf, 20);
752 static int _open_noatime(const char *filename, int attrs)
754 int attrs_noatime, fd;
760 attrs |= O_LARGEFILE;
762 attrs_noatime = attrs;
764 attrs_noatime |= O_NOATIME;
766 fd = open(filename, attrs_noatime);
767 if (fd < 0 && errno == EPERM)
769 // older Linux kernels would return EPERM if you used O_NOATIME
770 // and weren't the file's owner. This pointless restriction was
771 // relaxed eventually, but we have to handle it anyway.
772 // (VERY old kernels didn't recognized O_NOATIME, but they would
773 // just harmlessly ignore it, so this branch won't trigger)
774 fd = open(filename, attrs);
780 static PyObject *open_noatime(PyObject *self, PyObject *args)
782 char *filename = NULL;
784 if (!PyArg_ParseTuple(args, "s", &filename))
786 fd = _open_noatime(filename, 0);
788 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
789 return Py_BuildValue("i", fd);
793 static PyObject *fadvise_done(PyObject *self, PyObject *args)
797 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
799 #ifdef POSIX_FADV_DONTNEED
800 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
802 return Py_BuildValue("");
806 #ifdef BUP_HAVE_FILE_ATTRS
807 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
814 if (!PyArg_ParseTuple(args, "s", &path))
817 fd = _open_noatime(path, O_NONBLOCK);
819 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
822 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
826 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
830 return Py_BuildValue("I", attr);
832 #endif /* def BUP_HAVE_FILE_ATTRS */
836 #ifdef BUP_HAVE_FILE_ATTRS
837 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
840 unsigned int orig_attr, attr;
845 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
848 if (!bup_uint_from_py(&attr, py_attr, "attr"))
851 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
853 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
855 // Restrict attr to modifiable flags acdeijstuADST -- see
856 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
857 // in pf.c flags_array[].
858 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
859 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
860 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
861 | FS_TOPDIR_FL | FS_NOCOW_FL;
863 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
864 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
868 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
870 attr |= (orig_attr & FS_EXTENT_FL);
872 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
876 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
880 return Py_BuildValue("O", Py_None);
882 #endif /* def BUP_HAVE_FILE_ATTRS */
885 #ifndef HAVE_UTIMENSAT
887 #error "cannot find utimensat or utimes()"
890 #error "cannot find utimensat or lutimes()"
895 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
898 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
902 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
906 const long long lltmp = PyLong_AsLongLong(pylong); \
907 if (lltmp == -1 && PyErr_Occurred()) \
909 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
911 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
912 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
914 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
920 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
928 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
937 #ifdef HAVE_UTIMENSAT
939 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
944 PyObject *access_py, *modification_py;
945 struct timespec ts[2];
947 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
950 &access_py, &(ts[0].tv_nsec),
951 &modification_py, &(ts[1].tv_nsec),
956 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
959 PyErr_SetString(PyExc_ValueError,
960 "unable to convert access time seconds for utimensat");
963 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
966 PyErr_SetString(PyExc_ValueError,
967 "unable to convert modification time seconds for utimensat");
970 rc = utimensat(fd, path, ts, flag);
972 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
974 return Py_BuildValue("O", Py_None);
977 #endif /* def HAVE_UTIMENSAT */
980 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
982 static int bup_parse_xutimes_args(char **path,
983 struct timeval tv[2],
986 PyObject *access_py, *modification_py;
987 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
989 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
991 &access_py, &access_us,
992 &modification_py, &modification_us))
996 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
999 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1002 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1004 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1007 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1010 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1013 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1015 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1021 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1025 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1028 struct timeval tv[2];
1029 if (!bup_parse_xutimes_args(&path, tv, args))
1031 int rc = utimes(path, tv);
1033 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1034 return Py_BuildValue("O", Py_None);
1036 #endif /* def HAVE_UTIMES */
1040 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1043 struct timeval tv[2];
1044 if (!bup_parse_xutimes_args(&path, tv, args))
1046 int rc = lutimes(path, tv);
1048 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1050 return Py_BuildValue("O", Py_None);
1052 #endif /* def HAVE_LUTIMES */
1055 #ifdef HAVE_STAT_ST_ATIM
1056 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1057 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1058 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1059 #elif defined HAVE_STAT_ST_ATIMENSEC
1060 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1061 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1062 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1064 # define BUP_STAT_ATIME_NS(st) 0
1065 # define BUP_STAT_MTIME_NS(st) 0
1066 # define BUP_STAT_CTIME_NS(st) 0
1070 #pragma clang diagnostic push
1071 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1073 static PyObject *stat_struct_to_py(const struct stat *st,
1074 const char *filename,
1077 // We can check the known (via POSIX) signed and unsigned types at
1078 // compile time, but not (easily) the unspecified types, so handle
1079 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1081 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1082 INTEGER_TO_PY(st->st_mode),
1083 (unsigned PY_LONG_LONG) st->st_ino,
1084 INTEGER_TO_PY(st->st_dev),
1085 INTEGER_TO_PY(st->st_nlink),
1086 INTEGER_TO_PY(st->st_uid),
1087 INTEGER_TO_PY(st->st_gid),
1088 INTEGER_TO_PY(st->st_rdev),
1089 (PY_LONG_LONG) st->st_size,
1090 INTEGER_TO_PY(st->st_atime),
1091 (long) BUP_STAT_ATIME_NS(st),
1092 INTEGER_TO_PY(st->st_mtime),
1093 (long) BUP_STAT_MTIME_NS(st),
1094 INTEGER_TO_PY(st->st_ctime),
1095 (long) BUP_STAT_CTIME_NS(st));
1098 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1100 static PyObject *bup_stat(PyObject *self, PyObject *args)
1105 if (!PyArg_ParseTuple(args, "s", &filename))
1109 rc = stat(filename, &st);
1111 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1112 return stat_struct_to_py(&st, filename, 0);
1116 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1121 if (!PyArg_ParseTuple(args, "s", &filename))
1125 rc = lstat(filename, &st);
1127 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1128 return stat_struct_to_py(&st, filename, 0);
1132 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1136 if (!PyArg_ParseTuple(args, "i", &fd))
1140 rc = fstat(fd, &st);
1142 return PyErr_SetFromErrno(PyExc_OSError);
1143 return stat_struct_to_py(&st, NULL, fd);
1147 static PyMethodDef helper_methods[] = {
1148 { "selftest", selftest, METH_VARARGS,
1149 "Check that the rolling checksum rolls correctly (for unit tests)." },
1150 { "blobbits", blobbits, METH_VARARGS,
1151 "Return the number of bits in the rolling checksum." },
1152 { "splitbuf", splitbuf, METH_VARARGS,
1153 "Split a list of strings based on a rolling checksum." },
1154 { "bitmatch", bitmatch, METH_VARARGS,
1155 "Count the number of matching prefix bits between two strings." },
1156 { "firstword", firstword, METH_VARARGS,
1157 "Return an int corresponding to the first 32 bits of buf." },
1158 { "bloom_contains", bloom_contains, METH_VARARGS,
1159 "Check if a bloom filter of 2^nbits bytes contains an object" },
1160 { "bloom_add", bloom_add, METH_VARARGS,
1161 "Add an object to a bloom filter of 2^nbits bytes" },
1162 { "extract_bits", extract_bits, METH_VARARGS,
1163 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1164 { "merge_into", merge_into, METH_VARARGS,
1165 "Merges a bunch of idx and midx files into a single midx." },
1166 { "write_idx", write_idx, METH_VARARGS,
1167 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1168 { "write_random", write_random, METH_VARARGS,
1169 "Write random bytes to the given file descriptor" },
1170 { "random_sha", random_sha, METH_VARARGS,
1171 "Return a random 20-byte string" },
1172 { "open_noatime", open_noatime, METH_VARARGS,
1173 "open() the given filename for read with O_NOATIME if possible" },
1174 { "fadvise_done", fadvise_done, METH_VARARGS,
1175 "Inform the kernel that we're finished with earlier parts of a file" },
1176 #ifdef BUP_HAVE_FILE_ATTRS
1177 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1178 "Return the Linux attributes for the given file." },
1180 #ifdef BUP_HAVE_FILE_ATTRS
1181 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1182 "Set the Linux attributes for the given file." },
1184 #ifdef HAVE_UTIMENSAT
1185 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1186 "Change path timestamps with nanosecond precision (POSIX)." },
1189 { "bup_utimes", bup_utimes, METH_VARARGS,
1190 "Change path timestamps with microsecond precision." },
1193 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1194 "Change path timestamps with microsecond precision;"
1195 " don't follow symlinks." },
1197 { "stat", bup_stat, METH_VARARGS,
1198 "Extended version of stat." },
1199 { "lstat", bup_lstat, METH_VARARGS,
1200 "Extended version of lstat." },
1201 { "fstat", bup_fstat, METH_VARARGS,
1202 "Extended version of fstat." },
1203 { NULL, NULL, 0, NULL }, // sentinel
1207 PyMODINIT_FUNC init_helpers(void)
1209 // FIXME: migrate these tests to configure. Check against the
1210 // type we're going to use when passing to python. Other stat
1211 // types are tested at runtime.
1212 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1213 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1214 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1215 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1216 // Just be sure (relevant when passing timestamps back to Python above).
1217 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1218 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1221 PyObject *m = Py_InitModule("_helpers", helper_methods);
1225 #pragma clang diagnostic push
1226 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1227 #ifdef HAVE_UTIMENSAT
1230 value = INTEGER_TO_PY(AT_FDCWD);
1231 PyObject_SetAttrString(m, "AT_FDCWD", value);
1233 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1234 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1236 value = INTEGER_TO_PY(UTIME_NOW);
1237 PyObject_SetAttrString(m, "UTIME_NOW", value);
1243 const long arg_max = sysconf(_SC_ARG_MAX);
1246 fprintf(stderr, "Cannot find SC_ARG_MAX, please report a bug.\n");
1249 value = INTEGER_TO_PY(arg_max);
1250 PyObject_SetAttrString(m, "SC_ARG_MAX", value);
1253 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1255 e = getenv("BUP_FORCE_TTY");
1256 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);