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 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
44 * pretend we don't have it.
46 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
51 // Of course, this assumes it's a bitfield value.
55 static int istty2 = 0;
59 // This function should technically be macro'd out if it's going to be used
60 // more than ocasionally. As of this writing, it'll actually never be called
61 // in real world bup scenarios (because our packs are < MAX_INT bytes).
62 static uint64_t htonll(uint64_t value)
64 static const int endian_test = 42;
66 if (*(char *)&endian_test == endian_test) // LSB-MSB
67 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
68 return value; // already in network byte order MSB-LSB
73 // At the moment any code that calls INTGER_TO_PY() will have to
74 // disable -Wtautological-compare for clang. See below.
76 #define INTEGER_TO_PY(x) \
77 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
80 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
83 const long tmp = PyInt_AsLong(py);
84 if (tmp == -1 && PyErr_Occurred())
86 if (PyErr_ExceptionMatches(PyExc_OverflowError))
87 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
93 PyErr_Format(PyExc_OverflowError,
94 "negative %s cannot be converted to unsigned long", name);
102 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
105 return bup_ulong_from_pyint(x, py, name);
107 if (!PyLong_Check(py))
109 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
113 const unsigned long tmp = PyLong_AsUnsignedLong(py);
114 if (PyErr_Occurred())
116 if (PyErr_ExceptionMatches(PyExc_OverflowError))
117 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
126 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
129 if (!bup_ulong_from_py(&tmp, py, name))
134 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
141 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
147 if (bup_ulong_from_pyint(&tmp, py, name))
155 if (!PyLong_Check(py))
157 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
161 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
162 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
164 if (PyErr_ExceptionMatches(PyExc_OverflowError))
165 PyErr_Format(PyExc_OverflowError,
166 "%s too big for unsigned long long", name);
174 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
175 #if __WIN32__ || __CYGWIN__
177 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
178 static void unpythonize_argv(void) { }
180 #else // not __WIN32__
182 // For some reason this isn't declared in Python.h
183 extern void Py_GetArgcArgv(int *argc, char ***argv);
185 static void unpythonize_argv(void)
190 Py_GetArgcArgv(&argc, &argv);
192 for (i = 0; i < argc-1; i++)
194 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
196 // The argv block doesn't work the way we expected; it's unsafe
202 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
204 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
208 p = strrchr(argv[1], '/');
214 memmove(argv[0], p, len);
215 memset(arge - diff, 0, diff);
216 for (i = 0; i < argc; i++)
217 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
222 #endif // not __WIN32__ or __CYGWIN__
225 static PyObject *selftest(PyObject *self, PyObject *args)
227 if (!PyArg_ParseTuple(args, ""))
230 return Py_BuildValue("i", !bupsplit_selftest());
234 static PyObject *blobbits(PyObject *self, PyObject *args)
236 if (!PyArg_ParseTuple(args, ""))
238 return Py_BuildValue("i", BUP_BLOBBITS);
242 static PyObject *splitbuf(PyObject *self, PyObject *args)
244 unsigned char *buf = NULL;
246 int out = 0, bits = -1;
248 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
250 assert(len <= INT_MAX);
251 out = bupsplit_find_ofs(buf, len, &bits);
252 if (out) assert(bits >= BUP_BLOBBITS);
253 return Py_BuildValue("ii", out, bits);
257 static PyObject *bitmatch(PyObject *self, PyObject *args)
259 unsigned char *buf1 = NULL, *buf2 = NULL;
260 Py_ssize_t len1 = 0, len2 = 0;
264 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
268 for (byte = 0; byte < len1 && byte < len2; byte++)
270 int b1 = buf1[byte], b2 = buf2[byte];
273 for (bit = 0; bit < 8; bit++)
274 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
280 assert(byte <= (INT_MAX >> 3));
281 return Py_BuildValue("i", byte*8 + bit);
285 static PyObject *firstword(PyObject *self, PyObject *args)
287 unsigned char *buf = NULL;
291 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
297 v = ntohl(*(uint32_t *)buf);
298 return PyLong_FromUnsignedLong(v);
302 #define BLOOM2_HEADERLEN 16
304 static void to_bloom_address_bitmask4(const unsigned char *buf,
305 const int nbits, uint64_t *v, unsigned char *bitmask)
311 memcpy(&high, buf, 4);
312 mask = (1<<nbits) - 1;
313 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
314 bit = (raw >> (37-nbits)) & 0x7;
315 *v = (raw >> (40-nbits)) & mask;
319 static void to_bloom_address_bitmask5(const unsigned char *buf,
320 const int nbits, uint32_t *v, unsigned char *bitmask)
326 memcpy(&high, buf, 4);
327 mask = (1<<nbits) - 1;
329 bit = (raw >> (29-nbits)) & 0x7;
330 *v = (raw >> (32-nbits)) & mask;
334 #define BLOOM_SET_BIT(name, address, otype) \
335 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
337 unsigned char bitmask;\
339 address(buf, nbits, &v, &bitmask);\
340 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
342 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
343 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
346 #define BLOOM_GET_BIT(name, address, otype) \
347 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
349 unsigned char bitmask;\
351 address(buf, nbits, &v, &bitmask);\
352 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
354 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
355 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
358 static PyObject *bloom_add(PyObject *self, PyObject *args)
360 unsigned char *sha = NULL, *bloom = NULL;
362 Py_ssize_t len = 0, blen = 0;
363 int nbits = 0, k = 0;
365 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
368 if (blen < 16+(1<<nbits) || len % 20 != 0)
375 for (end = sha + len; sha < end; sha += 20/k)
376 bloom_set_bit5(bloom, sha, nbits);
382 for (end = sha + len; sha < end; sha += 20/k)
383 bloom_set_bit4(bloom, sha, nbits);
389 return Py_BuildValue("n", len/20);
392 static PyObject *bloom_contains(PyObject *self, PyObject *args)
394 unsigned char *sha = NULL, *bloom = NULL;
395 Py_ssize_t len = 0, blen = 0;
396 int nbits = 0, k = 0;
400 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
410 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
411 if (!bloom_get_bit5(bloom, sha, nbits))
412 return Py_BuildValue("Oi", Py_None, steps);
418 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
419 if (!bloom_get_bit4(bloom, sha, nbits))
420 return Py_BuildValue("Oi", Py_None, steps);
425 return Py_BuildValue("ii", 1, k);
429 static uint32_t _extract_bits(unsigned char *buf, int nbits)
433 mask = (1<<nbits) - 1;
434 v = ntohl(*(uint32_t *)buf);
435 v = (v >> (32-nbits)) & mask;
440 static PyObject *extract_bits(PyObject *self, PyObject *args)
442 unsigned char *buf = NULL;
446 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
452 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
457 unsigned char bytes[20];
471 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
474 for (i = 0; i < sizeof(struct sha); i++)
475 if (sha1->bytes[i] != sha2->bytes[i])
476 return sha1->bytes[i] - sha2->bytes[i];
481 static void _fix_idx_order(struct idx **idxs, int *last_i)
484 int low, mid, high, c = 0;
487 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
489 idxs[*last_i] = NULL;
502 mid = (low + high) / 2;
503 c = _cmp_sha(idx->cur, idxs[mid]->cur);
515 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
520 static uint32_t _get_idx_i(struct idx *idx)
522 if (idx->cur_name == NULL)
523 return idx->name_base;
524 return ntohl(*idx->cur_name) + idx->name_base;
527 #define MIDX4_HEADERLEN 12
529 static PyObject *merge_into(PyObject *self, PyObject *args)
531 PyObject *py_total, *ilist = NULL;
532 unsigned char *fmap = NULL;
533 struct sha *sha_ptr, *sha_start = NULL;
534 uint32_t *table_ptr, *name_ptr, *name_start;
535 struct idx **idxs = NULL;
539 uint32_t count, prefix;
543 if (!PyArg_ParseTuple(args, "w#iOO",
544 &fmap, &flen, &bits, &py_total, &ilist))
547 if (!bup_uint_from_py(&total, py_total, "total"))
550 num_i = PyList_Size(ilist);
551 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
553 for (i = 0; i < num_i; i++)
555 long len, sha_ofs, name_map_ofs;
556 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
557 PyObject *itup = PyList_GetItem(ilist, i);
558 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
559 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
561 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
562 idxs[i]->end = &idxs[i]->cur[len];
564 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
566 idxs[i]->cur_name = NULL;
568 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
569 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
570 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
579 if (count % 102424 == 0 && istty2)
580 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
581 count*100.0/total, count, total);
583 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
584 while (prefix < new_prefix)
585 table_ptr[prefix++] = htonl(count);
586 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
587 *name_ptr++ = htonl(_get_idx_i(idx));
589 if (idx->cur_name != NULL)
591 _fix_idx_order(idxs, &last_i);
594 while (prefix < (1<<bits))
595 table_ptr[prefix++] = htonl(count);
596 assert(count == total);
597 assert(prefix == (1<<bits));
598 assert(sha_ptr == sha_start+count);
599 assert(name_ptr == name_start+count);
602 return PyLong_FromUnsignedLong(count);
605 #define FAN_ENTRIES 256
607 static PyObject *write_idx(PyObject *self, PyObject *args)
609 char *filename = NULL;
610 PyObject *py_total, *idx = NULL;
612 unsigned char *fmap = NULL;
614 unsigned int total = 0;
616 int i, j, ofs64_count;
617 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
621 if (!PyArg_ParseTuple(args, "sw#OO",
622 &filename, &fmap, &flen, &idx, &py_total))
625 if (!bup_uint_from_py(&total, py_total, "total"))
628 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
629 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
632 const char idx_header[] = "\377tOc\0\0\0\002";
633 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
635 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
636 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
637 crc_ptr = (uint32_t *)&sha_ptr[total];
638 ofs_ptr = (uint32_t *)&crc_ptr[total];
639 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
643 for (i = 0; i < FAN_ENTRIES; ++i)
646 part = PyList_GET_ITEM(idx, i);
648 plen = PyList_GET_SIZE(part);
650 *fan_ptr++ = htonl(count);
651 for (j = 0; j < plen; ++j)
653 unsigned char *sha = NULL;
654 Py_ssize_t sha_len = 0;
655 PyObject *crc_py, *ofs_py;
657 unsigned PY_LONG_LONG ofs_ull;
659 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
660 &sha, &sha_len, &crc_py, &ofs_py))
662 if(!bup_uint_from_py(&crc, crc_py, "crc"))
664 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
666 assert(crc <= UINT32_MAX);
667 assert(ofs_ull <= UINT64_MAX);
669 if (sha_len != sizeof(struct sha))
671 memcpy(sha_ptr++, sha, sizeof(struct sha));
672 *crc_ptr++ = htonl(crc);
673 if (ofs > 0x7fffffff)
675 *ofs64_ptr++ = htonll(ofs);
676 ofs = 0x80000000 | ofs64_count++;
678 *ofs_ptr++ = htonl((uint32_t)ofs);
682 int rc = msync(fmap, flen, MS_ASYNC);
684 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
686 return PyLong_FromUnsignedLong(count);
690 // I would have made this a lower-level function that just fills in a buffer
691 // with random values, and then written those values from python. But that's
692 // about 20% slower in my tests, and since we typically generate random
693 // numbers for benchmarking other parts of bup, any slowness in generating
694 // random bytes will make our benchmarks inaccurate. Plus nobody wants
695 // pseudorandom bytes much except for this anyway.
696 static PyObject *write_random(PyObject *self, PyObject *args)
698 uint32_t buf[1024/4];
699 int fd = -1, seed = 0, verbose = 0;
701 long long len = 0, kbytes = 0, written = 0;
703 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
708 for (kbytes = 0; kbytes < len/1024; kbytes++)
711 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
713 ret = write(fd, buf, sizeof(buf));
717 if (ret < (int)sizeof(buf))
719 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
720 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
723 // handle non-multiples of 1024
727 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
729 ret = write(fd, buf, len % 1024);
736 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
737 return Py_BuildValue("L", written);
741 static PyObject *random_sha(PyObject *self, PyObject *args)
743 static int seeded = 0;
744 uint32_t shabuf[20/4];
749 assert(sizeof(shabuf) == 20);
754 if (!PyArg_ParseTuple(args, ""))
757 memset(shabuf, 0, sizeof(shabuf));
758 for (i=0; i < 20/4; i++)
759 shabuf[i] = random();
760 return Py_BuildValue("s#", shabuf, 20);
764 static int _open_noatime(const char *filename, int attrs)
766 int attrs_noatime, fd;
772 attrs |= O_LARGEFILE;
774 attrs_noatime = attrs;
776 attrs_noatime |= O_NOATIME;
778 fd = open(filename, attrs_noatime);
779 if (fd < 0 && errno == EPERM)
781 // older Linux kernels would return EPERM if you used O_NOATIME
782 // and weren't the file's owner. This pointless restriction was
783 // relaxed eventually, but we have to handle it anyway.
784 // (VERY old kernels didn't recognized O_NOATIME, but they would
785 // just harmlessly ignore it, so this branch won't trigger)
786 fd = open(filename, attrs);
792 static PyObject *open_noatime(PyObject *self, PyObject *args)
794 char *filename = NULL;
796 if (!PyArg_ParseTuple(args, "s", &filename))
798 fd = _open_noatime(filename, 0);
800 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
801 return Py_BuildValue("i", fd);
805 static PyObject *fadvise_done(PyObject *self, PyObject *args)
809 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
811 #ifdef POSIX_FADV_DONTNEED
812 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
814 return Py_BuildValue("");
818 #ifdef BUP_HAVE_FILE_ATTRS
819 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
826 if (!PyArg_ParseTuple(args, "s", &path))
829 fd = _open_noatime(path, O_NONBLOCK);
831 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
834 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
838 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
842 return Py_BuildValue("I", attr);
844 #endif /* def BUP_HAVE_FILE_ATTRS */
848 #ifdef BUP_HAVE_FILE_ATTRS
849 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
852 unsigned int orig_attr, attr;
857 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
860 if (!bup_uint_from_py(&attr, py_attr, "attr"))
863 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
865 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
867 // Restrict attr to modifiable flags acdeijstuADST -- see
868 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
869 // in pf.c flags_array[].
870 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
871 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
872 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
873 | FS_TOPDIR_FL | FS_NOCOW_FL;
875 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
876 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
880 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
882 attr |= (orig_attr & FS_EXTENT_FL);
884 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
888 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
892 return Py_BuildValue("O", Py_None);
894 #endif /* def BUP_HAVE_FILE_ATTRS */
897 #ifndef HAVE_UTIMENSAT
899 #error "cannot find utimensat or utimes()"
902 #error "cannot find utimensat or lutimes()"
907 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
910 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
914 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
918 const long long lltmp = PyLong_AsLongLong(pylong); \
919 if (lltmp == -1 && PyErr_Occurred()) \
921 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
923 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
924 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
926 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
932 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
940 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
949 #ifdef HAVE_UTIMENSAT
951 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
956 PyObject *access_py, *modification_py;
957 struct timespec ts[2];
959 if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
962 &access_py, &(ts[0].tv_nsec),
963 &modification_py, &(ts[1].tv_nsec),
968 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
971 PyErr_SetString(PyExc_ValueError,
972 "unable to convert access time seconds for utimensat");
975 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
978 PyErr_SetString(PyExc_ValueError,
979 "unable to convert modification time seconds for utimensat");
982 rc = utimensat(fd, path, ts, flag);
984 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
986 return Py_BuildValue("O", Py_None);
989 #endif /* def HAVE_UTIMENSAT */
992 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
994 static int bup_parse_xutimes_args(char **path,
995 struct timeval tv[2],
998 PyObject *access_py, *modification_py;
999 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1001 if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1003 &access_py, &access_us,
1004 &modification_py, &modification_us))
1008 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1011 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1014 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1016 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1019 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1022 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1025 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1027 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1033 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1037 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1040 struct timeval tv[2];
1041 if (!bup_parse_xutimes_args(&path, tv, args))
1043 int rc = utimes(path, tv);
1045 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1046 return Py_BuildValue("O", Py_None);
1048 #endif /* def HAVE_UTIMES */
1052 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1055 struct timeval tv[2];
1056 if (!bup_parse_xutimes_args(&path, tv, args))
1058 int rc = lutimes(path, tv);
1060 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1062 return Py_BuildValue("O", Py_None);
1064 #endif /* def HAVE_LUTIMES */
1067 #ifdef HAVE_STAT_ST_ATIM
1068 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1069 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1070 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1071 #elif defined HAVE_STAT_ST_ATIMENSEC
1072 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1073 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1074 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1076 # define BUP_STAT_ATIME_NS(st) 0
1077 # define BUP_STAT_MTIME_NS(st) 0
1078 # define BUP_STAT_CTIME_NS(st) 0
1082 #pragma clang diagnostic push
1083 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1085 static PyObject *stat_struct_to_py(const struct stat *st,
1086 const char *filename,
1089 // We can check the known (via POSIX) signed and unsigned types at
1090 // compile time, but not (easily) the unspecified types, so handle
1091 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1093 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1094 INTEGER_TO_PY(st->st_mode),
1095 (unsigned PY_LONG_LONG) st->st_ino,
1096 INTEGER_TO_PY(st->st_dev),
1097 INTEGER_TO_PY(st->st_nlink),
1098 INTEGER_TO_PY(st->st_uid),
1099 INTEGER_TO_PY(st->st_gid),
1100 INTEGER_TO_PY(st->st_rdev),
1101 (PY_LONG_LONG) st->st_size,
1102 INTEGER_TO_PY(st->st_atime),
1103 (long) BUP_STAT_ATIME_NS(st),
1104 INTEGER_TO_PY(st->st_mtime),
1105 (long) BUP_STAT_MTIME_NS(st),
1106 INTEGER_TO_PY(st->st_ctime),
1107 (long) BUP_STAT_CTIME_NS(st));
1110 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1112 static PyObject *bup_stat(PyObject *self, PyObject *args)
1117 if (!PyArg_ParseTuple(args, "s", &filename))
1121 rc = stat(filename, &st);
1123 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1124 return stat_struct_to_py(&st, filename, 0);
1128 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1133 if (!PyArg_ParseTuple(args, "s", &filename))
1137 rc = lstat(filename, &st);
1139 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1140 return stat_struct_to_py(&st, filename, 0);
1144 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1148 if (!PyArg_ParseTuple(args, "i", &fd))
1152 rc = fstat(fd, &st);
1154 return PyErr_SetFromErrno(PyExc_OSError);
1155 return stat_struct_to_py(&st, NULL, fd);
1159 static PyMethodDef helper_methods[] = {
1160 { "selftest", selftest, METH_VARARGS,
1161 "Check that the rolling checksum rolls correctly (for unit tests)." },
1162 { "blobbits", blobbits, METH_VARARGS,
1163 "Return the number of bits in the rolling checksum." },
1164 { "splitbuf", splitbuf, METH_VARARGS,
1165 "Split a list of strings based on a rolling checksum." },
1166 { "bitmatch", bitmatch, METH_VARARGS,
1167 "Count the number of matching prefix bits between two strings." },
1168 { "firstword", firstword, METH_VARARGS,
1169 "Return an int corresponding to the first 32 bits of buf." },
1170 { "bloom_contains", bloom_contains, METH_VARARGS,
1171 "Check if a bloom filter of 2^nbits bytes contains an object" },
1172 { "bloom_add", bloom_add, METH_VARARGS,
1173 "Add an object to a bloom filter of 2^nbits bytes" },
1174 { "extract_bits", extract_bits, METH_VARARGS,
1175 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1176 { "merge_into", merge_into, METH_VARARGS,
1177 "Merges a bunch of idx and midx files into a single midx." },
1178 { "write_idx", write_idx, METH_VARARGS,
1179 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1180 { "write_random", write_random, METH_VARARGS,
1181 "Write random bytes to the given file descriptor" },
1182 { "random_sha", random_sha, METH_VARARGS,
1183 "Return a random 20-byte string" },
1184 { "open_noatime", open_noatime, METH_VARARGS,
1185 "open() the given filename for read with O_NOATIME if possible" },
1186 { "fadvise_done", fadvise_done, METH_VARARGS,
1187 "Inform the kernel that we're finished with earlier parts of a file" },
1188 #ifdef BUP_HAVE_FILE_ATTRS
1189 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1190 "Return the Linux attributes for the given file." },
1192 #ifdef BUP_HAVE_FILE_ATTRS
1193 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1194 "Set the Linux attributes for the given file." },
1196 #ifdef HAVE_UTIMENSAT
1197 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1198 "Change path timestamps with nanosecond precision (POSIX)." },
1201 { "bup_utimes", bup_utimes, METH_VARARGS,
1202 "Change path timestamps with microsecond precision." },
1205 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1206 "Change path timestamps with microsecond precision;"
1207 " don't follow symlinks." },
1209 { "stat", bup_stat, METH_VARARGS,
1210 "Extended version of stat." },
1211 { "lstat", bup_lstat, METH_VARARGS,
1212 "Extended version of lstat." },
1213 { "fstat", bup_fstat, METH_VARARGS,
1214 "Extended version of fstat." },
1215 { NULL, NULL, 0, NULL }, // sentinel
1219 PyMODINIT_FUNC init_helpers(void)
1221 // FIXME: migrate these tests to configure. Check against the
1222 // type we're going to use when passing to python. Other stat
1223 // types are tested at runtime.
1224 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1225 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1226 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1227 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1228 // Just be sure (relevant when passing timestamps back to Python above).
1229 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1230 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1233 PyObject *m = Py_InitModule("_helpers", helper_methods);
1237 #pragma clang diagnostic push
1238 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1239 #ifdef HAVE_UTIMENSAT
1242 value = INTEGER_TO_PY(AT_FDCWD);
1243 PyObject_SetAttrString(m, "AT_FDCWD", value);
1245 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1246 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1248 value = INTEGER_TO_PY(UTIME_NOW);
1249 PyObject_SetAttrString(m, "UTIME_NOW", value);
1255 const long arg_max = sysconf(_SC_ARG_MAX);
1258 fprintf(stderr, "Cannot find SC_ARG_MAX, please report a bug.\n");
1261 value = INTEGER_TO_PY(arg_max);
1262 PyObject_SetAttrString(m, "SC_ARG_MAX", value);
1265 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1267 e = getenv("BUP_FORCE_TTY");
1268 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);