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 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
50 #if __WIN32__ || __CYGWIN__
52 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
53 static void unpythonize_argv(void) { }
55 #else // not __WIN32__
57 // For some reason this isn't declared in Python.h
58 extern void Py_GetArgcArgv(int *argc, char ***argv);
60 static void unpythonize_argv(void)
65 Py_GetArgcArgv(&argc, &argv);
67 for (i = 0; i < argc-1; i++)
69 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
71 // The argv block doesn't work the way we expected; it's unsafe
77 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
79 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
83 p = strrchr(argv[1], '/');
89 memmove(argv[0], p, len);
90 memset(arge - diff, 0, diff);
91 for (i = 0; i < argc; i++)
92 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
97 #endif // not __WIN32__ or __CYGWIN__
100 static PyObject *selftest(PyObject *self, PyObject *args)
102 if (!PyArg_ParseTuple(args, ""))
105 return Py_BuildValue("i", !bupsplit_selftest());
109 static PyObject *blobbits(PyObject *self, PyObject *args)
111 if (!PyArg_ParseTuple(args, ""))
113 return Py_BuildValue("i", BUP_BLOBBITS);
117 static PyObject *splitbuf(PyObject *self, PyObject *args)
119 unsigned char *buf = NULL;
121 int out = 0, bits = -1;
123 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
125 assert(len <= INT_MAX);
126 out = bupsplit_find_ofs(buf, len, &bits);
127 if (out) assert(bits >= BUP_BLOBBITS);
128 return Py_BuildValue("ii", out, bits);
132 static PyObject *bitmatch(PyObject *self, PyObject *args)
134 unsigned char *buf1 = NULL, *buf2 = NULL;
135 Py_ssize_t len1 = 0, len2 = 0;
139 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
143 for (byte = 0; byte < len1 && byte < len2; byte++)
145 int b1 = buf1[byte], b2 = buf2[byte];
148 for (bit = 0; bit < 8; bit++)
149 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
155 assert(byte <= (INT_MAX >> 3));
156 return Py_BuildValue("i", byte*8 + bit);
160 static PyObject *firstword(PyObject *self, PyObject *args)
162 unsigned char *buf = NULL;
166 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
172 v = ntohl(*(uint32_t *)buf);
173 return PyLong_FromUnsignedLong(v);
177 #define BLOOM2_HEADERLEN 16
179 static void to_bloom_address_bitmask4(const unsigned char *buf,
180 const int nbits, uint64_t *v, unsigned char *bitmask)
186 memcpy(&high, buf, 4);
187 mask = (1<<nbits) - 1;
188 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
189 bit = (raw >> (37-nbits)) & 0x7;
190 *v = (raw >> (40-nbits)) & mask;
194 static void to_bloom_address_bitmask5(const unsigned char *buf,
195 const int nbits, uint32_t *v, unsigned char *bitmask)
201 memcpy(&high, buf, 4);
202 mask = (1<<nbits) - 1;
204 bit = (raw >> (29-nbits)) & 0x7;
205 *v = (raw >> (32-nbits)) & mask;
209 #define BLOOM_SET_BIT(name, address, otype) \
210 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
212 unsigned char bitmask;\
214 address(buf, nbits, &v, &bitmask);\
215 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
217 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
218 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
221 #define BLOOM_GET_BIT(name, address, otype) \
222 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
224 unsigned char bitmask;\
226 address(buf, nbits, &v, &bitmask);\
227 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
229 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
230 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
233 static PyObject *bloom_add(PyObject *self, PyObject *args)
235 unsigned char *sha = NULL, *bloom = NULL;
237 Py_ssize_t len = 0, blen = 0;
238 int nbits = 0, k = 0;
240 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
243 if (blen < 16+(1<<nbits) || len % 20 != 0)
250 for (end = sha + len; sha < end; sha += 20/k)
251 bloom_set_bit5(bloom, sha, nbits);
257 for (end = sha + len; sha < end; sha += 20/k)
258 bloom_set_bit4(bloom, sha, nbits);
264 return Py_BuildValue("n", len/20);
267 static PyObject *bloom_contains(PyObject *self, PyObject *args)
269 unsigned char *sha = NULL, *bloom = NULL;
270 Py_ssize_t len = 0, blen = 0;
271 int nbits = 0, k = 0;
275 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
285 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
286 if (!bloom_get_bit5(bloom, sha, nbits))
287 return Py_BuildValue("Oi", Py_None, steps);
293 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
294 if (!bloom_get_bit4(bloom, sha, nbits))
295 return Py_BuildValue("Oi", Py_None, steps);
300 return Py_BuildValue("ii", 1, k);
304 static uint32_t _extract_bits(unsigned char *buf, int nbits)
308 mask = (1<<nbits) - 1;
309 v = ntohl(*(uint32_t *)buf);
310 v = (v >> (32-nbits)) & mask;
315 static PyObject *extract_bits(PyObject *self, PyObject *args)
317 unsigned char *buf = NULL;
321 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
327 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
332 unsigned char bytes[20];
346 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
349 for (i = 0; i < sizeof(struct sha); i++)
350 if (sha1->bytes[i] != sha2->bytes[i])
351 return sha1->bytes[i] - sha2->bytes[i];
356 static void _fix_idx_order(struct idx **idxs, int *last_i)
359 int low, mid, high, c = 0;
362 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
364 idxs[*last_i] = NULL;
377 mid = (low + high) / 2;
378 c = _cmp_sha(idx->cur, idxs[mid]->cur);
390 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
395 static uint32_t _get_idx_i(struct idx *idx)
397 if (idx->cur_name == NULL)
398 return idx->name_base;
399 return ntohl(*idx->cur_name) + idx->name_base;
402 #define MIDX4_HEADERLEN 12
404 static PyObject *merge_into(PyObject *self, PyObject *args)
406 PyObject *ilist = NULL;
407 unsigned char *fmap = NULL;
408 struct sha *sha_ptr, *sha_start = NULL;
409 uint32_t *table_ptr, *name_ptr, *name_start;
410 struct idx **idxs = NULL;
414 uint32_t count, prefix;
418 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
421 num_i = PyList_Size(ilist);
422 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
424 for (i = 0; i < num_i; i++)
426 long len, sha_ofs, name_map_ofs;
427 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
428 PyObject *itup = PyList_GetItem(ilist, i);
429 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
430 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
432 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
433 idxs[i]->end = &idxs[i]->cur[len];
435 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
437 idxs[i]->cur_name = NULL;
439 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
440 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
441 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
450 if (count % 102424 == 0 && istty2)
451 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
452 count*100.0/total, count, total);
454 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
455 while (prefix < new_prefix)
456 table_ptr[prefix++] = htonl(count);
457 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
458 *name_ptr++ = htonl(_get_idx_i(idx));
460 if (idx->cur_name != NULL)
462 _fix_idx_order(idxs, &last_i);
465 while (prefix < (1<<bits))
466 table_ptr[prefix++] = htonl(count);
467 assert(count == total);
468 assert(prefix == (1<<bits));
469 assert(sha_ptr == sha_start+count);
470 assert(name_ptr == name_start+count);
473 return PyLong_FromUnsignedLong(count);
476 // This function should technically be macro'd out if it's going to be used
477 // more than ocasionally. As of this writing, it'll actually never be called
478 // in real world bup scenarios (because our packs are < MAX_INT bytes).
479 static uint64_t htonll(uint64_t value)
481 static const int endian_test = 42;
483 if (*(char *)&endian_test == endian_test) // LSB-MSB
484 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
485 return value; // already in network byte order MSB-LSB
488 #define FAN_ENTRIES 256
490 static PyObject *write_idx(PyObject *self, PyObject *args)
492 char *filename = NULL;
493 PyObject *idx = NULL;
495 unsigned char *fmap = NULL;
497 unsigned int total = 0;
499 int i, j, ofs64_count;
500 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
504 if (!PyArg_ParseTuple(args, "sw#OI", &filename, &fmap, &flen, &idx, &total))
507 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
508 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
511 const char idx_header[] = "\377tOc\0\0\0\002";
512 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
514 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
515 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
516 crc_ptr = (uint32_t *)&sha_ptr[total];
517 ofs_ptr = (uint32_t *)&crc_ptr[total];
518 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
522 for (i = 0; i < FAN_ENTRIES; ++i)
525 part = PyList_GET_ITEM(idx, i);
527 plen = PyList_GET_SIZE(part);
529 *fan_ptr++ = htonl(count);
530 for (j = 0; j < plen; ++j)
532 unsigned char *sha = NULL;
533 Py_ssize_t sha_len = 0;
534 unsigned int crc = 0;
535 unsigned PY_LONG_LONG ofs_py = 0;
537 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
538 &sha, &sha_len, &crc, &ofs_py))
540 assert(crc <= UINT32_MAX);
541 assert(ofs_py <= UINT64_MAX);
543 if (sha_len != sizeof(struct sha))
545 memcpy(sha_ptr++, sha, sizeof(struct sha));
546 *crc_ptr++ = htonl(crc);
547 if (ofs > 0x7fffffff)
549 *ofs64_ptr++ = htonll(ofs);
550 ofs = 0x80000000 | ofs64_count++;
552 *ofs_ptr++ = htonl((uint32_t)ofs);
556 int rc = msync(fmap, flen, MS_ASYNC);
558 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
560 return PyLong_FromUnsignedLong(count);
564 // I would have made this a lower-level function that just fills in a buffer
565 // with random values, and then written those values from python. But that's
566 // about 20% slower in my tests, and since we typically generate random
567 // numbers for benchmarking other parts of bup, any slowness in generating
568 // random bytes will make our benchmarks inaccurate. Plus nobody wants
569 // pseudorandom bytes much except for this anyway.
570 static PyObject *write_random(PyObject *self, PyObject *args)
572 uint32_t buf[1024/4];
573 int fd = -1, seed = 0, verbose = 0;
575 long long len = 0, kbytes = 0, written = 0;
577 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
582 for (kbytes = 0; kbytes < len/1024; kbytes++)
585 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
587 ret = write(fd, buf, sizeof(buf));
591 if (ret < (int)sizeof(buf))
593 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
594 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
597 // handle non-multiples of 1024
601 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
603 ret = write(fd, buf, len % 1024);
610 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
611 return Py_BuildValue("L", written);
615 static PyObject *random_sha(PyObject *self, PyObject *args)
617 static int seeded = 0;
618 uint32_t shabuf[20/4];
623 assert(sizeof(shabuf) == 20);
628 if (!PyArg_ParseTuple(args, ""))
631 memset(shabuf, 0, sizeof(shabuf));
632 for (i=0; i < 20/4; i++)
633 shabuf[i] = random();
634 return Py_BuildValue("s#", shabuf, 20);
638 static int _open_noatime(const char *filename, int attrs)
640 int attrs_noatime, fd;
646 attrs |= O_LARGEFILE;
648 attrs_noatime = attrs;
650 attrs_noatime |= O_NOATIME;
652 fd = open(filename, attrs_noatime);
653 if (fd < 0 && errno == EPERM)
655 // older Linux kernels would return EPERM if you used O_NOATIME
656 // and weren't the file's owner. This pointless restriction was
657 // relaxed eventually, but we have to handle it anyway.
658 // (VERY old kernels didn't recognized O_NOATIME, but they would
659 // just harmlessly ignore it, so this branch won't trigger)
660 fd = open(filename, attrs);
666 static PyObject *open_noatime(PyObject *self, PyObject *args)
668 char *filename = NULL;
670 if (!PyArg_ParseTuple(args, "s", &filename))
672 fd = _open_noatime(filename, 0);
674 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
675 return Py_BuildValue("i", fd);
679 static PyObject *fadvise_done(PyObject *self, PyObject *args)
683 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
685 #ifdef POSIX_FADV_DONTNEED
686 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
688 return Py_BuildValue("");
692 #ifdef BUP_HAVE_FILE_ATTRS
693 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
700 if (!PyArg_ParseTuple(args, "s", &path))
703 fd = _open_noatime(path, O_NONBLOCK);
705 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
708 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
712 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
716 return Py_BuildValue("I", attr);
718 #endif /* def BUP_HAVE_FILE_ATTRS */
721 #ifdef BUP_HAVE_FILE_ATTRS
722 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
725 unsigned int orig_attr, attr;
729 if (!PyArg_ParseTuple(args, "sI", &path, &attr))
732 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
734 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
736 // Restrict attr to modifiable flags acdeijstuADST -- see
737 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
738 // in pf.c flags_array[].
739 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
740 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
741 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
742 | FS_TOPDIR_FL | FS_NOCOW_FL;
744 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
745 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
749 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
751 attr |= (orig_attr & FS_EXTENT_FL);
753 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
757 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
761 return Py_BuildValue("O", Py_None);
763 #endif /* def BUP_HAVE_FILE_ATTRS */
766 #ifndef HAVE_UTIMENSAT
768 #error "cannot find utimensat or utimes()"
771 #error "cannot find utimensat or lutimes()"
776 #if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES) || defined(HAVE_LUTIMES)
778 static int bup_parse_xutime_args(char **path,
782 long *modification_ns,
783 PyObject *self, PyObject *args)
785 if (!PyArg_ParseTuple(args, "s((ll)(ll))",
788 modification, modification_ns))
793 PyErr_SetString(PyExc_ValueError, "access time is NaN");
796 else if (isinf(*access))
798 PyErr_SetString(PyExc_ValueError, "access time is infinite");
801 else if (isnan(*modification))
803 PyErr_SetString(PyExc_ValueError, "modification time is NaN");
806 else if (isinf(*modification))
808 PyErr_SetString(PyExc_ValueError, "modification time is infinite");
812 if (isnan(*access_ns))
814 PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
817 else if (isinf(*access_ns))
819 PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
822 else if (isnan(*modification_ns))
824 PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
827 else if (isinf(*modification_ns))
829 PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
836 #endif /* defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES)
837 || defined(HAVE_LUTIMES) */
840 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
843 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
847 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
851 const long long ltmp = PyLong_AsLongLong(pylong); \
852 if (ltmp == -1 && PyErr_Occurred()) \
854 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
856 const unsigned long ultmp = PyLong_AsUnsignedLongLong(pylong); \
857 if (ultmp == (unsigned long long) -1 && PyErr_Occurred()) \
859 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
865 if (INTEGRAL_ASSIGNMENT_FITS((dest), ultmp)) \
873 if (INTEGRAL_ASSIGNMENT_FITS((dest), ltmp)) \
882 #ifdef HAVE_UTIMENSAT
884 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
889 PyObject *access_py, *modification_py;
890 struct timespec ts[2];
892 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
895 &access_py, &(ts[0].tv_nsec),
896 &modification_py, &(ts[1].tv_nsec),
901 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
904 PyErr_SetString(PyExc_ValueError,
905 "unable to convert access time seconds for utimensat");
908 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
911 PyErr_SetString(PyExc_ValueError,
912 "unable to convert modification time seconds for utimensat");
915 rc = utimensat(fd, path, ts, flag);
917 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
919 return Py_BuildValue("O", Py_None);
922 #endif /* def HAVE_UTIMENSAT */
926 #define BUP_HAVE_BUP_UTIME_NS 1
927 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
931 long access, access_ns, modification, modification_ns;
932 struct timeval tv[2];
934 if (!bup_parse_xutime_args(&path, &access, &access_ns,
935 &modification, &modification_ns,
939 tv[0].tv_sec = access;
940 tv[0].tv_usec = access_ns / 1000;
941 tv[1].tv_sec = modification;
942 tv[1].tv_usec = modification_ns / 1000;
943 rc = utimes(path, tv);
945 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
947 return Py_BuildValue("O", Py_None);
949 #endif /* def HAVE_UTIMES */
953 #define BUP_HAVE_BUP_LUTIME_NS 1
954 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
958 long access, access_ns, modification, modification_ns;
959 struct timeval tv[2];
961 if (!bup_parse_xutime_args(&path, &access, &access_ns,
962 &modification, &modification_ns,
966 tv[0].tv_sec = access;
967 tv[0].tv_usec = access_ns / 1000;
968 tv[1].tv_sec = modification;
969 tv[1].tv_usec = modification_ns / 1000;
970 rc = lutimes(path, tv);
972 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
974 return Py_BuildValue("O", Py_None);
976 #endif /* def HAVE_LUTIMES */
979 #ifdef HAVE_STAT_ST_ATIM
980 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
981 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
982 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
983 #elif defined HAVE_STAT_ST_ATIMENSEC
984 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
985 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
986 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
988 # define BUP_STAT_ATIME_NS(st) 0
989 # define BUP_STAT_MTIME_NS(st) 0
990 # define BUP_STAT_CTIME_NS(st) 0
994 static void set_invalid_timespec_msg(const char *field,
997 const char *filename,
1000 if (filename != NULL)
1001 PyErr_Format(PyExc_ValueError,
1002 "invalid %s timespec (%lld %ld) for file \"%s\"",
1003 field, sec, nsec, filename);
1005 PyErr_Format(PyExc_ValueError,
1006 "invalid %s timespec (%lld %ld) for file descriptor %d",
1007 field, sec, nsec, fd);
1011 static int normalize_timespec_values(const char *name,
1014 const char *filename,
1017 if (*nsec < -999999999 || *nsec > 999999999)
1019 set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
1024 if (*sec == LONG_MIN)
1026 set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
1029 *nsec += 1000000000;
1036 #define INTEGER_TO_PY(x) \
1037 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
1040 static PyObject *stat_struct_to_py(const struct stat *st,
1041 const char *filename,
1044 long long atime = st->st_atime;
1045 long long mtime = st->st_mtime;
1046 long long ctime = st->st_ctime;
1047 long atime_ns = BUP_STAT_ATIME_NS(st);
1048 long mtime_ns = BUP_STAT_MTIME_NS(st);
1049 long ctime_ns = BUP_STAT_CTIME_NS(st);
1051 if (!normalize_timespec_values("atime", &atime, &atime_ns, filename, fd))
1053 if (!normalize_timespec_values("mtime", &mtime, &mtime_ns, filename, fd))
1055 if (!normalize_timespec_values("ctime", &ctime, &ctime_ns, filename, fd))
1058 // We can check the known (via POSIX) signed and unsigned types at
1059 // compile time, but not (easily) the unspecified types, so handle
1060 // those via INTEGER_TO_PY().
1061 return Py_BuildValue("OKOOOOOL(Ll)(Ll)(Ll)",
1062 INTEGER_TO_PY(st->st_mode),
1063 (unsigned PY_LONG_LONG) st->st_ino,
1064 INTEGER_TO_PY(st->st_dev),
1065 INTEGER_TO_PY(st->st_nlink),
1066 INTEGER_TO_PY(st->st_uid),
1067 INTEGER_TO_PY(st->st_gid),
1068 INTEGER_TO_PY(st->st_rdev),
1069 (PY_LONG_LONG) st->st_size,
1070 (PY_LONG_LONG) atime,
1072 (PY_LONG_LONG) mtime,
1074 (PY_LONG_LONG) ctime,
1079 static PyObject *bup_stat(PyObject *self, PyObject *args)
1084 if (!PyArg_ParseTuple(args, "s", &filename))
1088 rc = stat(filename, &st);
1090 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1091 return stat_struct_to_py(&st, filename, 0);
1095 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1100 if (!PyArg_ParseTuple(args, "s", &filename))
1104 rc = lstat(filename, &st);
1106 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1107 return stat_struct_to_py(&st, filename, 0);
1111 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1115 if (!PyArg_ParseTuple(args, "i", &fd))
1119 rc = fstat(fd, &st);
1121 return PyErr_SetFromErrno(PyExc_OSError);
1122 return stat_struct_to_py(&st, NULL, fd);
1126 static PyMethodDef helper_methods[] = {
1127 { "selftest", selftest, METH_VARARGS,
1128 "Check that the rolling checksum rolls correctly (for unit tests)." },
1129 { "blobbits", blobbits, METH_VARARGS,
1130 "Return the number of bits in the rolling checksum." },
1131 { "splitbuf", splitbuf, METH_VARARGS,
1132 "Split a list of strings based on a rolling checksum." },
1133 { "bitmatch", bitmatch, METH_VARARGS,
1134 "Count the number of matching prefix bits between two strings." },
1135 { "firstword", firstword, METH_VARARGS,
1136 "Return an int corresponding to the first 32 bits of buf." },
1137 { "bloom_contains", bloom_contains, METH_VARARGS,
1138 "Check if a bloom filter of 2^nbits bytes contains an object" },
1139 { "bloom_add", bloom_add, METH_VARARGS,
1140 "Add an object to a bloom filter of 2^nbits bytes" },
1141 { "extract_bits", extract_bits, METH_VARARGS,
1142 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1143 { "merge_into", merge_into, METH_VARARGS,
1144 "Merges a bunch of idx and midx files into a single midx." },
1145 { "write_idx", write_idx, METH_VARARGS,
1146 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1147 { "write_random", write_random, METH_VARARGS,
1148 "Write random bytes to the given file descriptor" },
1149 { "random_sha", random_sha, METH_VARARGS,
1150 "Return a random 20-byte string" },
1151 { "open_noatime", open_noatime, METH_VARARGS,
1152 "open() the given filename for read with O_NOATIME if possible" },
1153 { "fadvise_done", fadvise_done, METH_VARARGS,
1154 "Inform the kernel that we're finished with earlier parts of a file" },
1155 #ifdef BUP_HAVE_FILE_ATTRS
1156 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1157 "Return the Linux attributes for the given file." },
1159 #ifdef BUP_HAVE_FILE_ATTRS
1160 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1161 "Set the Linux attributes for the given file." },
1163 #ifdef HAVE_UTIMENSAT
1164 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1165 "Change path timestamps with nanosecond precision (POSIX)." },
1167 #ifdef BUP_HAVE_BUP_UTIME_NS
1168 { "bup_utime_ns", bup_utime_ns, METH_VARARGS,
1169 "Change path timestamps with up to nanosecond precision." },
1171 #ifdef BUP_HAVE_BUP_LUTIME_NS
1172 { "bup_lutime_ns", bup_lutime_ns, METH_VARARGS,
1173 "Change path timestamps with up to nanosecond precision;"
1174 " don't follow symlinks." },
1176 { "stat", bup_stat, METH_VARARGS,
1177 "Extended version of stat." },
1178 { "lstat", bup_lstat, METH_VARARGS,
1179 "Extended version of lstat." },
1180 { "fstat", bup_fstat, METH_VARARGS,
1181 "Extended version of fstat." },
1182 { NULL, NULL, 0, NULL }, // sentinel
1186 PyMODINIT_FUNC init_helpers(void)
1188 // FIXME: migrate these tests to configure. Check against the
1189 // type we're going to use when passing to python. Other stat
1190 // types are tested at runtime.
1191 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1192 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1193 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1194 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1195 // Just be sure (relevant when passing timestamps back to Python above).
1196 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1199 PyObject *m = Py_InitModule("_helpers", helper_methods);
1203 #ifdef HAVE_UTIMENSAT
1206 value = INTEGER_TO_PY(AT_FDCWD);
1207 PyObject_SetAttrString(m, "AT_FDCWD", value);
1209 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1210 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1212 value = INTEGER_TO_PY(UTIME_NOW);
1213 PyObject_SetAttrString(m, "UTIME_NOW", value);
1218 e = getenv("BUP_FORCE_TTY");
1219 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);