1 #define _LARGEFILE64_SOURCE 1
2 #define PY_SSIZE_T_CLEAN 1
4 #include "../../config/config.h"
14 #ifdef HAVE_SYS_TYPES_H
15 #include <sys/types.h>
17 #ifdef HAVE_SYS_STAT_H
24 #ifdef HAVE_LINUX_FS_H
27 #ifdef HAVE_SYS_IOCTL_H
28 #include <sys/ioctl.h>
34 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
35 #define BUP_HAVE_FILE_ATTRS 1
39 // Of course, this assumes it's a bitfield value.
43 static int istty2 = 0;
45 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
46 #if __WIN32__ || __CYGWIN__
48 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
49 static void unpythonize_argv(void) { }
51 #else // not __WIN32__
53 // For some reason this isn't declared in Python.h
54 extern void Py_GetArgcArgv(int *argc, char ***argv);
56 static void unpythonize_argv(void)
61 Py_GetArgcArgv(&argc, &argv);
63 for (i = 0; i < argc-1; i++)
65 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
67 // The argv block doesn't work the way we expected; it's unsafe
73 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
75 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
79 p = strrchr(argv[1], '/');
85 memmove(argv[0], p, len);
86 memset(arge - diff, 0, diff);
87 for (i = 0; i < argc; i++)
88 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
93 #endif // not __WIN32__ or __CYGWIN__
96 static PyObject *selftest(PyObject *self, PyObject *args)
98 if (!PyArg_ParseTuple(args, ""))
101 return Py_BuildValue("i", !bupsplit_selftest());
105 static PyObject *blobbits(PyObject *self, PyObject *args)
107 if (!PyArg_ParseTuple(args, ""))
109 return Py_BuildValue("i", BUP_BLOBBITS);
113 static PyObject *splitbuf(PyObject *self, PyObject *args)
115 unsigned char *buf = NULL;
117 int out = 0, bits = -1;
119 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
121 assert(len <= INT_MAX);
122 out = bupsplit_find_ofs(buf, len, &bits);
123 if (out) assert(bits >= BUP_BLOBBITS);
124 return Py_BuildValue("ii", out, bits);
128 static PyObject *bitmatch(PyObject *self, PyObject *args)
130 unsigned char *buf1 = NULL, *buf2 = NULL;
131 Py_ssize_t len1 = 0, len2 = 0;
135 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
139 for (byte = 0; byte < len1 && byte < len2; byte++)
141 int b1 = buf1[byte], b2 = buf2[byte];
144 for (bit = 0; bit < 8; bit++)
145 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
151 assert(byte <= (INT_MAX >> 3));
152 return Py_BuildValue("i", byte*8 + bit);
156 static PyObject *firstword(PyObject *self, PyObject *args)
158 unsigned char *buf = NULL;
162 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
168 v = ntohl(*(uint32_t *)buf);
169 return PyLong_FromUnsignedLong(v);
173 #define BLOOM2_HEADERLEN 16
175 static void to_bloom_address_bitmask4(const unsigned char *buf,
176 const int nbits, uint64_t *v, unsigned char *bitmask)
182 memcpy(&high, buf, 4);
183 mask = (1<<nbits) - 1;
184 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
185 bit = (raw >> (37-nbits)) & 0x7;
186 *v = (raw >> (40-nbits)) & mask;
190 static void to_bloom_address_bitmask5(const unsigned char *buf,
191 const int nbits, uint32_t *v, unsigned char *bitmask)
197 memcpy(&high, buf, 4);
198 mask = (1<<nbits) - 1;
200 bit = (raw >> (29-nbits)) & 0x7;
201 *v = (raw >> (32-nbits)) & mask;
205 #define BLOOM_SET_BIT(name, address, otype) \
206 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
208 unsigned char bitmask;\
210 address(buf, nbits, &v, &bitmask);\
211 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
213 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
214 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
217 #define BLOOM_GET_BIT(name, address, otype) \
218 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
220 unsigned char bitmask;\
222 address(buf, nbits, &v, &bitmask);\
223 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
225 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
226 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
229 static PyObject *bloom_add(PyObject *self, PyObject *args)
231 unsigned char *sha = NULL, *bloom = NULL;
233 Py_ssize_t len = 0, blen = 0;
234 int nbits = 0, k = 0;
236 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
239 if (blen < 16+(1<<nbits) || len % 20 != 0)
246 for (end = sha + len; sha < end; sha += 20/k)
247 bloom_set_bit5(bloom, sha, nbits);
253 for (end = sha + len; sha < end; sha += 20/k)
254 bloom_set_bit4(bloom, sha, nbits);
260 return Py_BuildValue("n", len/20);
263 static PyObject *bloom_contains(PyObject *self, PyObject *args)
265 unsigned char *sha = NULL, *bloom = NULL;
266 Py_ssize_t len = 0, blen = 0;
267 int nbits = 0, k = 0;
271 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
281 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
282 if (!bloom_get_bit5(bloom, sha, nbits))
283 return Py_BuildValue("Oi", Py_None, steps);
289 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
290 if (!bloom_get_bit4(bloom, sha, nbits))
291 return Py_BuildValue("Oi", Py_None, steps);
296 return Py_BuildValue("ii", 1, k);
300 static uint32_t _extract_bits(unsigned char *buf, int nbits)
304 mask = (1<<nbits) - 1;
305 v = ntohl(*(uint32_t *)buf);
306 v = (v >> (32-nbits)) & mask;
311 static PyObject *extract_bits(PyObject *self, PyObject *args)
313 unsigned char *buf = NULL;
317 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
323 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
328 unsigned char bytes[20];
342 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
345 for (i = 0; i < sizeof(struct sha); i++)
346 if (sha1->bytes[i] != sha2->bytes[i])
347 return sha1->bytes[i] - sha2->bytes[i];
352 static void _fix_idx_order(struct idx **idxs, int *last_i)
355 int low, mid, high, c = 0;
358 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
360 idxs[*last_i] = NULL;
373 mid = (low + high) / 2;
374 c = _cmp_sha(idx->cur, idxs[mid]->cur);
386 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
391 static uint32_t _get_idx_i(struct idx *idx)
393 if (idx->cur_name == NULL)
394 return idx->name_base;
395 return ntohl(*idx->cur_name) + idx->name_base;
398 #define MIDX4_HEADERLEN 12
400 static PyObject *merge_into(PyObject *self, PyObject *args)
402 PyObject *ilist = NULL;
403 unsigned char *fmap = NULL;
404 struct sha *sha_ptr, *sha_start = NULL;
405 uint32_t *table_ptr, *name_ptr, *name_start;
406 struct idx **idxs = NULL;
410 uint32_t count, prefix;
414 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
417 num_i = PyList_Size(ilist);
418 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
420 for (i = 0; i < num_i; i++)
422 long len, sha_ofs, name_map_ofs;
423 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
424 PyObject *itup = PyList_GetItem(ilist, i);
425 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
426 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
428 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
429 idxs[i]->end = &idxs[i]->cur[len];
431 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
433 idxs[i]->cur_name = NULL;
435 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
436 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
437 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
446 if (count % 102424 == 0 && istty2)
447 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
448 count*100.0/total, count, total);
450 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
451 while (prefix < new_prefix)
452 table_ptr[prefix++] = htonl(count);
453 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
454 *name_ptr++ = htonl(_get_idx_i(idx));
456 if (idx->cur_name != NULL)
458 _fix_idx_order(idxs, &last_i);
461 while (prefix < (1<<bits))
462 table_ptr[prefix++] = htonl(count);
463 assert(count == total);
464 assert(prefix == (1<<bits));
465 assert(sha_ptr == sha_start+count);
466 assert(name_ptr == name_start+count);
469 return PyLong_FromUnsignedLong(count);
472 // This function should technically be macro'd out if it's going to be used
473 // more than ocasionally. As of this writing, it'll actually never be called
474 // in real world bup scenarios (because our packs are < MAX_INT bytes).
475 static uint64_t htonll(uint64_t value)
477 static const int endian_test = 42;
479 if (*(char *)&endian_test == endian_test) // LSB-MSB
480 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
481 return value; // already in network byte order MSB-LSB
484 #define FAN_ENTRIES 256
486 static PyObject *write_idx(PyObject *self, PyObject *args)
488 char *filename = NULL;
489 PyObject *idx = NULL;
491 unsigned char *fmap = NULL;
493 unsigned int total = 0;
495 int i, j, ofs64_count;
496 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
500 if (!PyArg_ParseTuple(args, "sw#OI", &filename, &fmap, &flen, &idx, &total))
503 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
504 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
507 const char idx_header[] = "\377tOc\0\0\0\002";
508 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
510 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
511 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
512 crc_ptr = (uint32_t *)&sha_ptr[total];
513 ofs_ptr = (uint32_t *)&crc_ptr[total];
514 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
518 for (i = 0; i < FAN_ENTRIES; ++i)
521 part = PyList_GET_ITEM(idx, i);
523 plen = PyList_GET_SIZE(part);
525 *fan_ptr++ = htonl(count);
526 for (j = 0; j < plen; ++j)
528 unsigned char *sha = NULL;
529 Py_ssize_t sha_len = 0;
530 unsigned int crc = 0;
531 unsigned PY_LONG_LONG ofs_py = 0;
533 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
534 &sha, &sha_len, &crc, &ofs_py))
536 assert(crc <= UINT32_MAX);
537 assert(ofs_py <= UINT64_MAX);
539 if (sha_len != sizeof(struct sha))
541 memcpy(sha_ptr++, sha, sizeof(struct sha));
542 *crc_ptr++ = htonl(crc);
543 if (ofs > 0x7fffffff)
545 *ofs64_ptr++ = htonll(ofs);
546 ofs = 0x80000000 | ofs64_count++;
548 *ofs_ptr++ = htonl((uint32_t)ofs);
552 int rc = msync(fmap, flen, MS_ASYNC);
554 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
556 return PyLong_FromUnsignedLong(count);
560 // I would have made this a lower-level function that just fills in a buffer
561 // with random values, and then written those values from python. But that's
562 // about 20% slower in my tests, and since we typically generate random
563 // numbers for benchmarking other parts of bup, any slowness in generating
564 // random bytes will make our benchmarks inaccurate. Plus nobody wants
565 // pseudorandom bytes much except for this anyway.
566 static PyObject *write_random(PyObject *self, PyObject *args)
568 uint32_t buf[1024/4];
569 int fd = -1, seed = 0, verbose = 0;
571 long long len = 0, kbytes = 0, written = 0;
573 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
578 for (kbytes = 0; kbytes < len/1024; kbytes++)
581 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
583 ret = write(fd, buf, sizeof(buf));
587 if (ret < (int)sizeof(buf))
589 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
590 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
593 // handle non-multiples of 1024
597 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
599 ret = write(fd, buf, len % 1024);
606 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
607 return Py_BuildValue("L", written);
611 static PyObject *random_sha(PyObject *self, PyObject *args)
613 static int seeded = 0;
614 uint32_t shabuf[20/4];
619 assert(sizeof(shabuf) == 20);
624 if (!PyArg_ParseTuple(args, ""))
627 memset(shabuf, 0, sizeof(shabuf));
628 for (i=0; i < 20/4; i++)
629 shabuf[i] = random();
630 return Py_BuildValue("s#", shabuf, 20);
634 static int _open_noatime(const char *filename, int attrs)
636 int attrs_noatime, fd;
642 attrs |= O_LARGEFILE;
644 attrs_noatime = attrs;
646 attrs_noatime |= O_NOATIME;
648 fd = open(filename, attrs_noatime);
649 if (fd < 0 && errno == EPERM)
651 // older Linux kernels would return EPERM if you used O_NOATIME
652 // and weren't the file's owner. This pointless restriction was
653 // relaxed eventually, but we have to handle it anyway.
654 // (VERY old kernels didn't recognized O_NOATIME, but they would
655 // just harmlessly ignore it, so this branch won't trigger)
656 fd = open(filename, attrs);
662 static PyObject *open_noatime(PyObject *self, PyObject *args)
664 char *filename = NULL;
666 if (!PyArg_ParseTuple(args, "s", &filename))
668 fd = _open_noatime(filename, 0);
670 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
671 return Py_BuildValue("i", fd);
675 static PyObject *fadvise_done(PyObject *self, PyObject *args)
679 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
681 #ifdef POSIX_FADV_DONTNEED
682 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
684 return Py_BuildValue("");
688 #ifdef BUP_HAVE_FILE_ATTRS
689 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
696 if (!PyArg_ParseTuple(args, "s", &path))
699 fd = _open_noatime(path, O_NONBLOCK);
701 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
704 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
708 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
712 return Py_BuildValue("k", attr);
714 #endif /* def BUP_HAVE_FILE_ATTRS */
717 #ifdef BUP_HAVE_FILE_ATTRS
718 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
721 unsigned long orig_attr, attr;
725 if (!PyArg_ParseTuple(args, "sk", &path, &attr))
728 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
730 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
732 // Restrict attr to modifiable flags acdeijstuADST -- see
733 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
734 // in pf.c flags_array[].
735 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
736 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
737 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
738 | FS_TOPDIR_FL | FS_NOCOW_FL;
740 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
741 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
745 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
747 attr |= (orig_attr & FS_EXTENT_FL);
749 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
753 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
757 return Py_BuildValue("O", Py_None);
759 #endif /* def BUP_HAVE_FILE_ATTRS */
762 #if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES) || defined(HAVE_LUTIMES)
764 static int bup_parse_xutime_args(char **path,
768 long *modification_ns,
769 PyObject *self, PyObject *args)
771 if (!PyArg_ParseTuple(args, "s((ll)(ll))",
774 modification, modification_ns))
779 PyErr_SetString(PyExc_ValueError, "access time is NaN");
782 else if (isinf(*access))
784 PyErr_SetString(PyExc_ValueError, "access time is infinite");
787 else if (isnan(*modification))
789 PyErr_SetString(PyExc_ValueError, "modification time is NaN");
792 else if (isinf(*modification))
794 PyErr_SetString(PyExc_ValueError, "modification time is infinite");
798 if (isnan(*access_ns))
800 PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
803 else if (isinf(*access_ns))
805 PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
808 else if (isnan(*modification_ns))
810 PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
813 else if (isinf(*modification_ns))
815 PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
822 #endif /* defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES)
823 || defined(HAVE_LUTIMES) */
826 #ifdef HAVE_UTIMENSAT
828 static PyObject *bup_xutime_ns(PyObject *self, PyObject *args,
833 long access, access_ns, modification, modification_ns;
834 struct timespec ts[2];
836 if (!bup_parse_xutime_args(&path, &access, &access_ns,
837 &modification, &modification_ns,
841 ts[0].tv_sec = access;
842 ts[0].tv_nsec = access_ns;
843 ts[1].tv_sec = modification;
844 ts[1].tv_nsec = modification_ns;
845 rc = utimensat(AT_FDCWD, path, ts,
846 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
848 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
850 return Py_BuildValue("O", Py_None);
854 #define BUP_HAVE_BUP_UTIME_NS 1
855 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
857 return bup_xutime_ns(self, args, 1);
861 #define BUP_HAVE_BUP_LUTIME_NS 1
862 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
864 return bup_xutime_ns(self, args, 0);
868 #else /* not defined(HAVE_UTIMENSAT) */
872 #define BUP_HAVE_BUP_UTIME_NS 1
873 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
877 long access, access_ns, modification, modification_ns;
878 struct timeval tv[2];
880 if (!bup_parse_xutime_args(&path, &access, &access_ns,
881 &modification, &modification_ns,
885 tv[0].tv_sec = access;
886 tv[0].tv_usec = access_ns / 1000;
887 tv[1].tv_sec = modification;
888 tv[1].tv_usec = modification_ns / 1000;
889 rc = utimes(path, tv);
891 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
893 return Py_BuildValue("O", Py_None);
895 #endif /* def HAVE_UTIMES */
899 #define BUP_HAVE_BUP_LUTIME_NS 1
900 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
904 long access, access_ns, modification, modification_ns;
905 struct timeval tv[2];
907 if (!bup_parse_xutime_args(&path, &access, &access_ns,
908 &modification, &modification_ns,
912 tv[0].tv_sec = access;
913 tv[0].tv_usec = access_ns / 1000;
914 tv[1].tv_sec = modification;
915 tv[1].tv_usec = modification_ns / 1000;
916 rc = lutimes(path, tv);
918 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
920 return Py_BuildValue("O", Py_None);
922 #endif /* def HAVE_LUTIMES */
925 #endif /* not defined(HAVE_UTIMENSAT) */
928 #ifdef HAVE_STAT_ST_ATIM
929 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
930 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
931 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
932 #elif defined HAVE_STAT_ST_ATIMENSEC
933 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
934 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
935 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
937 # define BUP_STAT_ATIME_NS(st) 0
938 # define BUP_STAT_MTIME_NS(st) 0
939 # define BUP_STAT_CTIME_NS(st) 0
943 static void set_invalid_timespec_msg(const char *field,
946 const char *filename,
949 if (filename != NULL)
950 PyErr_Format(PyExc_ValueError,
951 "invalid %s timespec (%lld %ld) for file \"%s\"",
952 field, sec, nsec, filename);
954 PyErr_Format(PyExc_ValueError,
955 "invalid %s timespec (%lld %ld) for file descriptor %d",
956 field, sec, nsec, fd);
960 static int normalize_timespec_values(const char *name,
963 const char *filename,
966 if (*nsec < -999999999 || *nsec > 999999999)
968 set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
973 if (*sec == LONG_MIN)
975 set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
985 static PyObject *stat_struct_to_py(const struct stat *st,
986 const char *filename,
989 long long atime = st->st_atime;
990 long long mtime = st->st_mtime;
991 long long ctime = st->st_ctime;
992 long atime_ns = BUP_STAT_ATIME_NS(st);
993 long mtime_ns = BUP_STAT_MTIME_NS(st);
994 long ctime_ns = BUP_STAT_CTIME_NS(st);
996 if (!normalize_timespec_values("atime", &atime, &atime_ns, filename, fd))
998 if (!normalize_timespec_values("mtime", &mtime, &mtime_ns, filename, fd))
1000 if (!normalize_timespec_values("ctime", &ctime, &ctime_ns, filename, fd))
1003 return Py_BuildValue("kkkkkkkk(Ll)(Ll)(Ll)",
1004 (unsigned long) st->st_mode,
1005 (unsigned long) st->st_ino,
1006 (unsigned long) st->st_dev,
1007 (unsigned long) st->st_nlink,
1008 (unsigned long) st->st_uid,
1009 (unsigned long) st->st_gid,
1010 (unsigned long) st->st_rdev,
1011 (unsigned long) st->st_size,
1021 static PyObject *bup_stat(PyObject *self, PyObject *args)
1026 if (!PyArg_ParseTuple(args, "s", &filename))
1030 rc = stat(filename, &st);
1032 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1033 return stat_struct_to_py(&st, filename, 0);
1037 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1042 if (!PyArg_ParseTuple(args, "s", &filename))
1046 rc = lstat(filename, &st);
1048 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1049 return stat_struct_to_py(&st, filename, 0);
1053 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1057 if (!PyArg_ParseTuple(args, "i", &fd))
1061 rc = fstat(fd, &st);
1063 return PyErr_SetFromErrno(PyExc_OSError);
1064 return stat_struct_to_py(&st, NULL, fd);
1068 static PyMethodDef helper_methods[] = {
1069 { "selftest", selftest, METH_VARARGS,
1070 "Check that the rolling checksum rolls correctly (for unit tests)." },
1071 { "blobbits", blobbits, METH_VARARGS,
1072 "Return the number of bits in the rolling checksum." },
1073 { "splitbuf", splitbuf, METH_VARARGS,
1074 "Split a list of strings based on a rolling checksum." },
1075 { "bitmatch", bitmatch, METH_VARARGS,
1076 "Count the number of matching prefix bits between two strings." },
1077 { "firstword", firstword, METH_VARARGS,
1078 "Return an int corresponding to the first 32 bits of buf." },
1079 { "bloom_contains", bloom_contains, METH_VARARGS,
1080 "Check if a bloom filter of 2^nbits bytes contains an object" },
1081 { "bloom_add", bloom_add, METH_VARARGS,
1082 "Add an object to a bloom filter of 2^nbits bytes" },
1083 { "extract_bits", extract_bits, METH_VARARGS,
1084 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1085 { "merge_into", merge_into, METH_VARARGS,
1086 "Merges a bunch of idx and midx files into a single midx." },
1087 { "write_idx", write_idx, METH_VARARGS,
1088 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1089 { "write_random", write_random, METH_VARARGS,
1090 "Write random bytes to the given file descriptor" },
1091 { "random_sha", random_sha, METH_VARARGS,
1092 "Return a random 20-byte string" },
1093 { "open_noatime", open_noatime, METH_VARARGS,
1094 "open() the given filename for read with O_NOATIME if possible" },
1095 { "fadvise_done", fadvise_done, METH_VARARGS,
1096 "Inform the kernel that we're finished with earlier parts of a file" },
1097 #ifdef BUP_HAVE_FILE_ATTRS
1098 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1099 "Return the Linux attributes for the given file." },
1101 #ifdef BUP_HAVE_FILE_ATTRS
1102 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1103 "Set the Linux attributes for the given file." },
1105 #ifdef BUP_HAVE_BUP_UTIME_NS
1106 { "bup_utime_ns", bup_utime_ns, METH_VARARGS,
1107 "Change path timestamps with up to nanosecond precision." },
1109 #ifdef BUP_HAVE_BUP_LUTIME_NS
1110 { "bup_lutime_ns", bup_lutime_ns, METH_VARARGS,
1111 "Change path timestamps with up to nanosecond precision;"
1112 " don't follow symlinks." },
1114 { "stat", bup_stat, METH_VARARGS,
1115 "Extended version of stat." },
1116 { "lstat", bup_lstat, METH_VARARGS,
1117 "Extended version of lstat." },
1118 { "fstat", bup_fstat, METH_VARARGS,
1119 "Extended version of fstat." },
1120 { NULL, NULL, 0, NULL }, // sentinel
1124 PyMODINIT_FUNC init_helpers(void)
1127 PyObject *m = Py_InitModule("_helpers", helper_methods);
1130 e = getenv("BUP_FORCE_TTY");
1131 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);