1 #define _LARGEFILE64_SOURCE 1
2 #define PY_SSIZE_T_CLEAN 1
4 #include "../../config/config.h"
10 #include <arpa/inet.h>
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_STAT_H
26 #ifdef HAVE_LINUX_FS_H
29 #ifdef HAVE_SYS_IOCTL_H
30 #include <sys/ioctl.h>
33 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
34 #define BUP_HAVE_FILE_ATTRS 1
38 // Of course, this assumes it's a bitfield value.
42 static int istty2 = 0;
44 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
45 #if __WIN32__ || __CYGWIN__
47 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
48 static void unpythonize_argv(void) { }
50 #else // not __WIN32__
52 // For some reason this isn't declared in Python.h
53 extern void Py_GetArgcArgv(int *argc, char ***argv);
55 static void unpythonize_argv(void)
60 Py_GetArgcArgv(&argc, &argv);
62 for (i = 0; i < argc-1; i++)
64 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
66 // The argv block doesn't work the way we expected; it's unsafe
72 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
74 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
78 p = strrchr(argv[1], '/');
84 memmove(argv[0], p, len);
85 memset(arge - diff, 0, diff);
86 for (i = 0; i < argc; i++)
87 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
92 #endif // not __WIN32__ or __CYGWIN__
95 static PyObject *selftest(PyObject *self, PyObject *args)
97 if (!PyArg_ParseTuple(args, ""))
100 return Py_BuildValue("i", !bupsplit_selftest());
104 static PyObject *blobbits(PyObject *self, PyObject *args)
106 if (!PyArg_ParseTuple(args, ""))
108 return Py_BuildValue("i", BUP_BLOBBITS);
112 static PyObject *splitbuf(PyObject *self, PyObject *args)
114 unsigned char *buf = NULL;
116 int out = 0, bits = -1;
118 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
120 assert(len <= INT_MAX);
121 out = bupsplit_find_ofs(buf, len, &bits);
122 if (out) assert(bits >= BUP_BLOBBITS);
123 return Py_BuildValue("ii", out, bits);
127 static PyObject *bitmatch(PyObject *self, PyObject *args)
129 unsigned char *buf1 = NULL, *buf2 = NULL;
130 Py_ssize_t len1 = 0, len2 = 0;
134 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
138 for (byte = 0; byte < len1 && byte < len2; byte++)
140 int b1 = buf1[byte], b2 = buf2[byte];
143 for (bit = 0; bit < 8; bit++)
144 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
150 assert(byte <= (INT_MAX >> 3));
151 return Py_BuildValue("i", byte*8 + bit);
155 static PyObject *firstword(PyObject *self, PyObject *args)
157 unsigned char *buf = NULL;
161 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
167 v = ntohl(*(uint32_t *)buf);
168 return PyLong_FromUnsignedLong(v);
172 #define BLOOM2_HEADERLEN 16
174 static void to_bloom_address_bitmask4(const unsigned char *buf,
175 const int nbits, uint64_t *v, unsigned char *bitmask)
181 memcpy(&high, buf, 4);
182 mask = (1<<nbits) - 1;
183 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
184 bit = (raw >> (37-nbits)) & 0x7;
185 *v = (raw >> (40-nbits)) & mask;
189 static void to_bloom_address_bitmask5(const unsigned char *buf,
190 const int nbits, uint32_t *v, unsigned char *bitmask)
196 memcpy(&high, buf, 4);
197 mask = (1<<nbits) - 1;
199 bit = (raw >> (29-nbits)) & 0x7;
200 *v = (raw >> (32-nbits)) & mask;
204 #define BLOOM_SET_BIT(name, address, otype) \
205 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
207 unsigned char bitmask;\
209 address(buf, nbits, &v, &bitmask);\
210 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
212 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
213 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
216 #define BLOOM_GET_BIT(name, address, otype) \
217 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
219 unsigned char bitmask;\
221 address(buf, nbits, &v, &bitmask);\
222 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
224 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
225 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
228 static PyObject *bloom_add(PyObject *self, PyObject *args)
230 unsigned char *sha = NULL, *bloom = NULL;
232 Py_ssize_t len = 0, blen = 0;
233 int nbits = 0, k = 0;
235 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
238 if (blen < 16+(1<<nbits) || len % 20 != 0)
245 for (end = sha + len; sha < end; sha += 20/k)
246 bloom_set_bit5(bloom, sha, nbits);
252 for (end = sha + len; sha < end; sha += 20/k)
253 bloom_set_bit4(bloom, sha, nbits);
259 return Py_BuildValue("n", len/20);
262 static PyObject *bloom_contains(PyObject *self, PyObject *args)
264 unsigned char *sha = NULL, *bloom = NULL;
265 Py_ssize_t len = 0, blen = 0;
266 int nbits = 0, k = 0;
270 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
280 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
281 if (!bloom_get_bit5(bloom, sha, nbits))
282 return Py_BuildValue("Oi", Py_None, steps);
288 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
289 if (!bloom_get_bit4(bloom, sha, nbits))
290 return Py_BuildValue("Oi", Py_None, steps);
295 return Py_BuildValue("ii", 1, k);
299 static uint32_t _extract_bits(unsigned char *buf, int nbits)
303 mask = (1<<nbits) - 1;
304 v = ntohl(*(uint32_t *)buf);
305 v = (v >> (32-nbits)) & mask;
310 static PyObject *extract_bits(PyObject *self, PyObject *args)
312 unsigned char *buf = NULL;
316 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
322 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
327 unsigned char bytes[20];
341 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
344 for (i = 0; i < sizeof(struct sha); i++)
345 if (sha1->bytes[i] != sha2->bytes[i])
346 return sha1->bytes[i] - sha2->bytes[i];
351 static void _fix_idx_order(struct idx **idxs, int *last_i)
354 int low, mid, high, c = 0;
357 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
359 idxs[*last_i] = NULL;
372 mid = (low + high) / 2;
373 c = _cmp_sha(idx->cur, idxs[mid]->cur);
385 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
390 static uint32_t _get_idx_i(struct idx *idx)
392 if (idx->cur_name == NULL)
393 return idx->name_base;
394 return ntohl(*idx->cur_name) + idx->name_base;
397 #define MIDX4_HEADERLEN 12
399 static PyObject *merge_into(PyObject *self, PyObject *args)
401 PyObject *ilist = NULL;
402 unsigned char *fmap = NULL;
403 struct sha *sha_ptr, *sha_start = NULL;
404 uint32_t *table_ptr, *name_ptr, *name_start;
405 struct idx **idxs = NULL;
409 uint32_t count, prefix;
413 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
416 num_i = PyList_Size(ilist);
417 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
419 for (i = 0; i < num_i; i++)
421 long len, sha_ofs, name_map_ofs;
422 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
423 PyObject *itup = PyList_GetItem(ilist, i);
424 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
425 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
427 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
428 idxs[i]->end = &idxs[i]->cur[len];
430 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
432 idxs[i]->cur_name = NULL;
434 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
435 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
436 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
445 if (count % 102424 == 0 && istty2)
446 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
447 count*100.0/total, count, total);
449 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
450 while (prefix < new_prefix)
451 table_ptr[prefix++] = htonl(count);
452 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
453 *name_ptr++ = htonl(_get_idx_i(idx));
455 if (idx->cur_name != NULL)
457 _fix_idx_order(idxs, &last_i);
460 while (prefix < (1<<bits))
461 table_ptr[prefix++] = htonl(count);
462 assert(count == total);
463 assert(prefix == (1<<bits));
464 assert(sha_ptr == sha_start+count);
465 assert(name_ptr == name_start+count);
468 return PyLong_FromUnsignedLong(count);
471 // This function should technically be macro'd out if it's going to be used
472 // more than ocasionally. As of this writing, it'll actually never be called
473 // in real world bup scenarios (because our packs are < MAX_INT bytes).
474 static uint64_t htonll(uint64_t value)
476 static const int endian_test = 42;
478 if (*(char *)&endian_test == endian_test) // LSB-MSB
479 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
480 return value; // already in network byte order MSB-LSB
483 #define FAN_ENTRIES 256
485 static PyObject *write_idx(PyObject *self, PyObject *args)
487 const char *filename = NULL;
488 PyObject *idx = NULL;
490 unsigned char *fmap = NULL;
492 unsigned int total = 0;
494 int i, j, ofs64_count;
495 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
499 if (!PyArg_ParseTuple(args, "sw#OI", &filename, &fmap, &flen, &idx, &total))
502 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
503 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
506 const char idx_header[] = "\377tOc\0\0\0\002";
507 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
509 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
510 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
511 crc_ptr = (uint32_t *)&sha_ptr[total];
512 ofs_ptr = (uint32_t *)&crc_ptr[total];
513 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
517 for (i = 0; i < FAN_ENTRIES; ++i)
520 part = PyList_GET_ITEM(idx, i);
522 plen = PyList_GET_SIZE(part);
524 *fan_ptr++ = htonl(count);
525 for (j = 0; j < plen; ++j)
527 unsigned char *sha = NULL;
528 Py_ssize_t sha_len = 0;
529 unsigned int crc = 0;
530 unsigned PY_LONG_LONG ofs_py = 0;
532 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
533 &sha, &sha_len, &crc, &ofs_py))
535 assert(crc <= UINT32_MAX);
536 assert(ofs_py <= UINT64_MAX);
538 if (sha_len != sizeof(struct sha))
540 memcpy(sha_ptr++, sha, sizeof(struct sha));
541 *crc_ptr++ = htonl(crc);
542 if (ofs > 0x7fffffff)
544 *ofs64_ptr++ = htonll(ofs);
545 ofs = 0x80000000 | ofs64_count++;
547 *ofs_ptr++ = htonl((uint32_t)ofs);
551 int rc = msync(fmap, flen, MS_ASYNC);
553 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
555 return PyLong_FromUnsignedLong(count);
559 // I would have made this a lower-level function that just fills in a buffer
560 // with random values, and then written those values from python. But that's
561 // about 20% slower in my tests, and since we typically generate random
562 // numbers for benchmarking other parts of bup, any slowness in generating
563 // random bytes will make our benchmarks inaccurate. Plus nobody wants
564 // pseudorandom bytes much except for this anyway.
565 static PyObject *write_random(PyObject *self, PyObject *args)
567 uint32_t buf[1024/4];
568 int fd = -1, seed = 0, verbose = 0;
570 long long len = 0, kbytes = 0, written = 0;
572 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
577 for (kbytes = 0; kbytes < len/1024; kbytes++)
580 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
582 ret = write(fd, buf, sizeof(buf));
586 if (ret < (int)sizeof(buf))
588 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
589 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
592 // handle non-multiples of 1024
596 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
598 ret = write(fd, buf, len % 1024);
605 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
606 return Py_BuildValue("L", written);
610 static PyObject *random_sha(PyObject *self, PyObject *args)
612 static int seeded = 0;
613 uint32_t shabuf[20/4];
618 assert(sizeof(shabuf) == 20);
623 if (!PyArg_ParseTuple(args, ""))
626 memset(shabuf, 0, sizeof(shabuf));
627 for (i=0; i < 20/4; i++)
628 shabuf[i] = random();
629 return Py_BuildValue("s#", shabuf, 20);
633 static int _open_noatime(const char *filename, int attrs)
635 int attrs_noatime, fd;
641 attrs |= O_LARGEFILE;
643 attrs_noatime = attrs;
645 attrs_noatime |= O_NOATIME;
647 fd = open(filename, attrs_noatime);
648 if (fd < 0 && errno == EPERM)
650 // older Linux kernels would return EPERM if you used O_NOATIME
651 // and weren't the file's owner. This pointless restriction was
652 // relaxed eventually, but we have to handle it anyway.
653 // (VERY old kernels didn't recognized O_NOATIME, but they would
654 // just harmlessly ignore it, so this branch won't trigger)
655 fd = open(filename, attrs);
661 static PyObject *open_noatime(PyObject *self, PyObject *args)
663 char *filename = NULL;
665 if (!PyArg_ParseTuple(args, "s", &filename))
667 fd = _open_noatime(filename, 0);
669 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
670 return Py_BuildValue("i", fd);
674 static PyObject *fadvise_done(PyObject *self, PyObject *args)
678 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
680 #ifdef POSIX_FADV_DONTNEED
681 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
683 return Py_BuildValue("");
687 #ifdef BUP_HAVE_FILE_ATTRS
688 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
695 if (!PyArg_ParseTuple(args, "s", &path))
698 fd = _open_noatime(path, O_NONBLOCK);
700 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
703 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
707 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
711 return Py_BuildValue("k", attr);
713 #endif /* def BUP_HAVE_FILE_ATTRS */
716 #ifdef BUP_HAVE_FILE_ATTRS
717 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
720 unsigned long orig_attr, attr;
724 if (!PyArg_ParseTuple(args, "sk", &path, &attr))
727 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
729 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
731 // Restrict attr to modifiable flags acdeijstuADST -- see
732 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
733 // in pf.c flags_array[].
734 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
735 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
736 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
737 | FS_TOPDIR_FL | FS_NOCOW_FL;
739 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
740 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
744 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
746 attr |= (orig_attr & FS_EXTENT_FL);
748 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
752 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
756 return Py_BuildValue("O", Py_None);
758 #endif /* def BUP_HAVE_FILE_ATTRS */
761 #if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES) || defined(HAVE_LUTIMES)
763 static int bup_parse_xutime_args(char **path,
767 long *modification_ns,
768 PyObject *self, PyObject *args)
770 if (!PyArg_ParseTuple(args, "s((ll)(ll))",
773 modification, modification_ns))
778 PyErr_SetString(PyExc_ValueError, "access time is NaN");
781 else if (isinf(*access))
783 PyErr_SetString(PyExc_ValueError, "access time is infinite");
786 else if (isnan(*modification))
788 PyErr_SetString(PyExc_ValueError, "modification time is NaN");
791 else if (isinf(*modification))
793 PyErr_SetString(PyExc_ValueError, "modification time is infinite");
797 if (isnan(*access_ns))
799 PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
802 else if (isinf(*access_ns))
804 PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
807 else if (isnan(*modification_ns))
809 PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
812 else if (isinf(*modification_ns))
814 PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
821 #endif /* defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES)
822 || defined(HAVE_LUTIMES) */
825 #ifdef HAVE_UTIMENSAT
827 static PyObject *bup_xutime_ns(PyObject *self, PyObject *args,
832 long access, access_ns, modification, modification_ns;
833 struct timespec ts[2];
835 if (!bup_parse_xutime_args(&path, &access, &access_ns,
836 &modification, &modification_ns,
840 ts[0].tv_sec = access;
841 ts[0].tv_nsec = access_ns;
842 ts[1].tv_sec = modification;
843 ts[1].tv_nsec = modification_ns;
844 rc = utimensat(AT_FDCWD, path, ts,
845 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
847 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
849 return Py_BuildValue("O", Py_None);
853 #define BUP_HAVE_BUP_UTIME_NS 1
854 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
856 return bup_xutime_ns(self, args, 1);
860 #define BUP_HAVE_BUP_LUTIME_NS 1
861 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
863 return bup_xutime_ns(self, args, 0);
867 #else /* not defined(HAVE_UTIMENSAT) */
871 #define BUP_HAVE_BUP_UTIME_NS 1
872 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
876 long access, access_ns, modification, modification_ns;
877 struct timeval tv[2];
879 if (!bup_parse_xutime_args(&path, &access, &access_ns,
880 &modification, &modification_ns,
884 tv[0].tv_sec = access;
885 tv[0].tv_usec = access_ns / 1000;
886 tv[1].tv_sec = modification;
887 tv[1].tv_usec = modification_ns / 1000;
888 rc = utimes(path, tv);
890 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
892 return Py_BuildValue("O", Py_None);
894 #endif /* def HAVE_UTIMES */
898 #define BUP_HAVE_BUP_LUTIME_NS 1
899 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
903 long access, access_ns, modification, modification_ns;
904 struct timeval tv[2];
906 if (!bup_parse_xutime_args(&path, &access, &access_ns,
907 &modification, &modification_ns,
911 tv[0].tv_sec = access;
912 tv[0].tv_usec = access_ns / 1000;
913 tv[1].tv_sec = modification;
914 tv[1].tv_usec = modification_ns / 1000;
915 rc = lutimes(path, tv);
917 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
919 return Py_BuildValue("O", Py_None);
921 #endif /* def HAVE_LUTIMES */
924 #endif /* not defined(HAVE_UTIMENSAT) */
927 #ifdef HAVE_STAT_ST_ATIM
928 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
929 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
930 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
931 #elif defined HAVE_STAT_ST_ATIMENSEC
932 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
933 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
934 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
936 # define BUP_STAT_ATIME_NS(st) 0
937 # define BUP_STAT_MTIME_NS(st) 0
938 # define BUP_STAT_CTIME_NS(st) 0
942 static void set_invalid_timespec_msg(const char *field,
945 const char *filename,
948 if (filename != NULL)
949 PyErr_Format(PyExc_ValueError,
950 "invalid %s timespec (%lld %ld) for file \"%s\"",
951 field, sec, nsec, filename);
953 PyErr_Format(PyExc_ValueError,
954 "invalid %s timespec (%lld %ld) for file descriptor %d",
955 field, sec, nsec, fd);
959 static int normalize_timespec_values(const char *name,
962 const char *filename,
965 if (*nsec < -999999999 || *nsec > 999999999)
967 set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
972 if (*sec == LONG_MIN)
974 set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
984 static PyObject *stat_struct_to_py(const struct stat *st,
985 const char *filename,
988 long long atime = st->st_atime;
989 long long mtime = st->st_mtime;
990 long long ctime = st->st_ctime;
991 long atime_ns = BUP_STAT_ATIME_NS(st);
992 long mtime_ns = BUP_STAT_MTIME_NS(st);
993 long ctime_ns = BUP_STAT_CTIME_NS(st);
995 if (!normalize_timespec_values("atime", &atime, &atime_ns, filename, fd))
997 if (!normalize_timespec_values("mtime", &mtime, &mtime_ns, filename, fd))
999 if (!normalize_timespec_values("ctime", &ctime, &ctime_ns, filename, fd))
1002 return Py_BuildValue("kkkkkkkk(Ll)(Ll)(Ll)",
1003 (unsigned long) st->st_mode,
1004 (unsigned long) st->st_ino,
1005 (unsigned long) st->st_dev,
1006 (unsigned long) st->st_nlink,
1007 (unsigned long) st->st_uid,
1008 (unsigned long) st->st_gid,
1009 (unsigned long) st->st_rdev,
1010 (unsigned long) st->st_size,
1020 static PyObject *bup_stat(PyObject *self, PyObject *args)
1025 if (!PyArg_ParseTuple(args, "s", &filename))
1029 rc = stat(filename, &st);
1031 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1032 return stat_struct_to_py(&st, filename, 0);
1036 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1041 if (!PyArg_ParseTuple(args, "s", &filename))
1045 rc = lstat(filename, &st);
1047 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1048 return stat_struct_to_py(&st, filename, 0);
1052 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1056 if (!PyArg_ParseTuple(args, "i", &fd))
1060 rc = fstat(fd, &st);
1062 return PyErr_SetFromErrno(PyExc_OSError);
1063 return stat_struct_to_py(&st, NULL, fd);
1067 static PyMethodDef helper_methods[] = {
1068 { "selftest", selftest, METH_VARARGS,
1069 "Check that the rolling checksum rolls correctly (for unit tests)." },
1070 { "blobbits", blobbits, METH_VARARGS,
1071 "Return the number of bits in the rolling checksum." },
1072 { "splitbuf", splitbuf, METH_VARARGS,
1073 "Split a list of strings based on a rolling checksum." },
1074 { "bitmatch", bitmatch, METH_VARARGS,
1075 "Count the number of matching prefix bits between two strings." },
1076 { "firstword", firstword, METH_VARARGS,
1077 "Return an int corresponding to the first 32 bits of buf." },
1078 { "bloom_contains", bloom_contains, METH_VARARGS,
1079 "Check if a bloom filter of 2^nbits bytes contains an object" },
1080 { "bloom_add", bloom_add, METH_VARARGS,
1081 "Add an object to a bloom filter of 2^nbits bytes" },
1082 { "extract_bits", extract_bits, METH_VARARGS,
1083 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1084 { "merge_into", merge_into, METH_VARARGS,
1085 "Merges a bunch of idx and midx files into a single midx." },
1086 { "write_idx", write_idx, METH_VARARGS,
1087 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1088 { "write_random", write_random, METH_VARARGS,
1089 "Write random bytes to the given file descriptor" },
1090 { "random_sha", random_sha, METH_VARARGS,
1091 "Return a random 20-byte string" },
1092 { "open_noatime", open_noatime, METH_VARARGS,
1093 "open() the given filename for read with O_NOATIME if possible" },
1094 { "fadvise_done", fadvise_done, METH_VARARGS,
1095 "Inform the kernel that we're finished with earlier parts of a file" },
1096 #ifdef BUP_HAVE_FILE_ATTRS
1097 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1098 "Return the Linux attributes for the given file." },
1100 #ifdef BUP_HAVE_FILE_ATTRS
1101 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1102 "Set the Linux attributes for the given file." },
1104 #ifdef BUP_HAVE_BUP_UTIME_NS
1105 { "bup_utime_ns", bup_utime_ns, METH_VARARGS,
1106 "Change path timestamps with up to nanosecond precision." },
1108 #ifdef BUP_HAVE_BUP_LUTIME_NS
1109 { "bup_lutime_ns", bup_lutime_ns, METH_VARARGS,
1110 "Change path timestamps with up to nanosecond precision;"
1111 " don't follow symlinks." },
1113 { "stat", bup_stat, METH_VARARGS,
1114 "Extended version of stat." },
1115 { "lstat", bup_lstat, METH_VARARGS,
1116 "Extended version of lstat." },
1117 { "fstat", bup_fstat, METH_VARARGS,
1118 "Extended version of fstat." },
1119 { NULL, NULL, 0, NULL }, // sentinel
1123 PyMODINIT_FUNC init_helpers(void)
1126 PyObject *m = Py_InitModule("_helpers", helper_methods);
1129 e = getenv("BUP_FORCE_TTY");
1130 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);