1 #define _LARGEFILE64_SOURCE 1
3 #include "../../config/config.h"
11 #include <sys/types.h>
19 #include <sys/ioctl.h>
22 static int istty2 = 0;
24 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
25 #if __WIN32__ || __CYGWIN__
27 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
28 static void unpythonize_argv(void) { }
30 #else // not __WIN32__
32 // For some reason this isn't declared in Python.h
33 extern void Py_GetArgcArgv(int *argc, char ***argv);
35 static void unpythonize_argv(void)
40 Py_GetArgcArgv(&argc, &argv);
42 for (i = 0; i < argc-1; i++)
44 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
46 // The argv block doesn't work the way we expected; it's unsafe
52 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
54 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
58 p = strrchr(argv[1], '/');
64 memmove(argv[0], p, len);
65 memset(arge - diff, 0, diff);
66 for (i = 0; i < argc; i++)
67 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
72 #endif // not __WIN32__ or __CYGWIN__
75 static PyObject *selftest(PyObject *self, PyObject *args)
77 if (!PyArg_ParseTuple(args, ""))
80 return Py_BuildValue("i", !bupsplit_selftest());
84 static PyObject *blobbits(PyObject *self, PyObject *args)
86 if (!PyArg_ParseTuple(args, ""))
88 return Py_BuildValue("i", BUP_BLOBBITS);
92 static PyObject *splitbuf(PyObject *self, PyObject *args)
94 unsigned char *buf = NULL;
95 int len = 0, out = 0, bits = -1;
97 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
99 out = bupsplit_find_ofs(buf, len, &bits);
100 if (out) assert(bits >= BUP_BLOBBITS);
101 return Py_BuildValue("ii", out, bits);
105 static PyObject *bitmatch(PyObject *self, PyObject *args)
107 unsigned char *buf1 = NULL, *buf2 = NULL;
108 int len1 = 0, len2 = 0;
111 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
115 for (byte = 0; byte < len1 && byte < len2; byte++)
117 int b1 = buf1[byte], b2 = buf2[byte];
120 for (bit = 0; bit < 8; bit++)
121 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
127 return Py_BuildValue("i", byte*8 + bit);
131 static PyObject *firstword(PyObject *self, PyObject *args)
133 unsigned char *buf = NULL;
137 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
143 v = ntohl(*(uint32_t *)buf);
144 return PyLong_FromUnsignedLong(v);
148 #define BLOOM2_HEADERLEN 16
155 static void to_bloom_address_bitmask4(const bits40_t *buf,
156 const int nbits, uint64_t *v, unsigned char *bitmask)
161 mask = (1<<nbits) - 1;
162 raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
163 bit = (raw >> (37-nbits)) & 0x7;
164 *v = (raw >> (40-nbits)) & mask;
168 static void to_bloom_address_bitmask5(const uint32_t *buf,
169 const int nbits, uint32_t *v, unsigned char *bitmask)
174 mask = (1<<nbits) - 1;
176 bit = (raw >> (29-nbits)) & 0x7;
177 *v = (raw >> (32-nbits)) & mask;
181 #define BLOOM_SET_BIT(name, address, itype, otype) \
182 static void name(unsigned char *bloom, const void *buf, const int nbits)\
184 unsigned char bitmask;\
186 address((itype *)buf, nbits, &v, &bitmask);\
187 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
189 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
190 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
193 #define BLOOM_GET_BIT(name, address, itype, otype) \
194 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
196 unsigned char bitmask;\
198 address((itype *)buf, nbits, &v, &bitmask);\
199 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
201 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
202 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
205 static PyObject *bloom_add(PyObject *self, PyObject *args)
207 unsigned char *sha = NULL, *bloom = NULL;
209 int len = 0, blen = 0, nbits = 0, k = 0;
211 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
214 if (blen < 16+(1<<nbits) || len % 20 != 0)
221 for (end = sha + len; sha < end; sha += 20/k)
222 bloom_set_bit5(bloom, sha, nbits);
228 for (end = sha + len; sha < end; sha += 20/k)
229 bloom_set_bit4(bloom, sha, nbits);
235 return Py_BuildValue("i", len/20);
238 static PyObject *bloom_contains(PyObject *self, PyObject *args)
240 unsigned char *sha = NULL, *bloom = NULL;
241 int len = 0, blen = 0, nbits = 0, k = 0;
245 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
255 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
256 if (!bloom_get_bit5(bloom, sha, nbits))
257 return Py_BuildValue("Oi", Py_None, steps);
263 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
264 if (!bloom_get_bit4(bloom, sha, nbits))
265 return Py_BuildValue("Oi", Py_None, steps);
270 return Py_BuildValue("ii", 1, k);
274 static uint32_t _extract_bits(unsigned char *buf, int nbits)
278 mask = (1<<nbits) - 1;
279 v = ntohl(*(uint32_t *)buf);
280 v = (v >> (32-nbits)) & mask;
283 static PyObject *extract_bits(PyObject *self, PyObject *args)
285 unsigned char *buf = NULL;
286 int len = 0, nbits = 0;
288 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
294 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
299 unsigned char bytes[20];
311 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
314 for (i = 0; i < sizeof(struct sha); i++)
315 if (sha1->bytes[i] != sha2->bytes[i])
316 return sha1->bytes[i] - sha2->bytes[i];
321 static void _fix_idx_order(struct idx **idxs, int *last_i)
324 int low, mid, high, c = 0;
327 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
329 idxs[*last_i] = NULL;
342 mid = (low + high) / 2;
343 c = _cmp_sha(idx->cur, idxs[mid]->cur);
355 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
360 static uint32_t _get_idx_i(struct idx *idx)
362 if (idx->cur_name == NULL)
363 return idx->name_base;
364 return ntohl(*idx->cur_name) + idx->name_base;
367 #define MIDX4_HEADERLEN 12
369 static PyObject *merge_into(PyObject *self, PyObject *args)
371 PyObject *ilist = NULL;
372 unsigned char *fmap = NULL;
373 struct sha *sha_ptr, *sha_start = NULL;
374 uint32_t *table_ptr, *name_ptr, *name_start;
375 struct idx **idxs = NULL;
376 int flen = 0, bits = 0, i;
377 uint32_t total, count, prefix;
381 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
384 num_i = PyList_Size(ilist);
385 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
387 for (i = 0; i < num_i; i++)
389 long len, sha_ofs, name_map_ofs;
390 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
391 PyObject *itup = PyList_GetItem(ilist, i);
392 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
393 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
395 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
396 idxs[i]->end = &idxs[i]->cur[len];
398 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
400 idxs[i]->cur_name = NULL;
402 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
403 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
404 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
413 if (count % 102424 == 0 && istty2)
414 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
415 count*100.0/total, count, total);
417 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
418 while (prefix < new_prefix)
419 table_ptr[prefix++] = htonl(count);
420 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
421 *name_ptr++ = htonl(_get_idx_i(idx));
423 if (idx->cur_name != NULL)
425 _fix_idx_order(idxs, &last_i);
428 while (prefix < (1<<bits))
429 table_ptr[prefix++] = htonl(count);
430 assert(count == total);
431 assert(prefix == (1<<bits));
432 assert(sha_ptr == sha_start+count);
433 assert(name_ptr == name_start+count);
436 return PyLong_FromUnsignedLong(count);
439 // This function should technically be macro'd out if it's going to be used
440 // more than ocasionally. As of this writing, it'll actually never be called
441 // in real world bup scenarios (because our packs are < MAX_INT bytes).
442 static uint64_t htonll(uint64_t value)
444 static const int endian_test = 42;
446 if (*(char *)&endian_test == endian_test) // LSB-MSB
447 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
448 return value; // already in network byte order MSB-LSB
451 #define PACK_IDX_V2_HEADERLEN 8
452 #define FAN_ENTRIES 256
454 static PyObject *write_idx(PyObject *self, PyObject *args)
456 PyObject *pf = NULL, *idx = NULL;
459 unsigned char *fmap = NULL;
463 int i, j, ofs64_count;
464 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
467 if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
470 fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
471 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
472 crc_ptr = (uint32_t *)&sha_ptr[total];
473 ofs_ptr = (uint32_t *)&crc_ptr[total];
474 f = PyFile_AsFile(pf);
478 for (i = 0; i < FAN_ENTRIES; ++i)
481 part = PyList_GET_ITEM(idx, i);
483 plen = PyList_GET_SIZE(part);
485 *fan_ptr++ = htonl(count);
486 for (j = 0; j < plen; ++j)
488 unsigned char *sha = NULL;
492 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
493 &sha, &sha_len, &crc, &ofs))
495 if (sha_len != sizeof(struct sha))
497 memcpy(sha_ptr++, sha, sizeof(struct sha));
498 *crc_ptr++ = htonl(crc);
499 if (ofs > 0x7fffffff)
501 uint64_t nofs = htonll(ofs);
502 if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
503 return PyErr_SetFromErrno(PyExc_OSError);
504 ofs = 0x80000000 | ofs64_count++;
506 *ofs_ptr++ = htonl((uint32_t)ofs);
509 return PyLong_FromUnsignedLong(count);
513 // I would have made this a lower-level function that just fills in a buffer
514 // with random values, and then written those values from python. But that's
515 // about 20% slower in my tests, and since we typically generate random
516 // numbers for benchmarking other parts of bup, any slowness in generating
517 // random bytes will make our benchmarks inaccurate. Plus nobody wants
518 // pseudorandom bytes much except for this anyway.
519 static PyObject *write_random(PyObject *self, PyObject *args)
521 uint32_t buf[1024/4];
522 int fd = -1, seed = 0, verbose = 0;
524 long long len = 0, kbytes = 0, written = 0;
526 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
531 for (kbytes = 0; kbytes < len/1024; kbytes++)
534 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
536 ret = write(fd, buf, sizeof(buf));
540 if (ret < (int)sizeof(buf))
542 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
543 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
546 // handle non-multiples of 1024
550 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
552 ret = write(fd, buf, len % 1024);
559 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
560 return Py_BuildValue("L", written);
564 static PyObject *random_sha(PyObject *self, PyObject *args)
566 static int seeded = 0;
567 uint32_t shabuf[20/4];
572 assert(sizeof(shabuf) == 20);
577 if (!PyArg_ParseTuple(args, ""))
580 memset(shabuf, 0, sizeof(shabuf));
581 for (i=0; i < 20/4; i++)
582 shabuf[i] = random();
583 return Py_BuildValue("s#", shabuf, 20);
587 static PyObject *open_noatime(PyObject *self, PyObject *args)
589 char *filename = NULL;
590 int attrs, attrs_noatime, fd;
591 if (!PyArg_ParseTuple(args, "s", &filename))
598 attrs |= O_LARGEFILE;
600 attrs_noatime = attrs;
602 attrs_noatime |= O_NOATIME;
604 fd = open(filename, attrs_noatime);
605 if (fd < 0 && errno == EPERM)
607 // older Linux kernels would return EPERM if you used O_NOATIME
608 // and weren't the file's owner. This pointless restriction was
609 // relaxed eventually, but we have to handle it anyway.
610 // (VERY old kernels didn't recognized O_NOATIME, but they would
611 // just harmlessly ignore it, so this branch won't trigger)
612 fd = open(filename, attrs);
615 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
616 return Py_BuildValue("i", fd);
620 static PyObject *fadvise_done(PyObject *self, PyObject *args)
624 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
626 #ifdef POSIX_FADV_DONTNEED
627 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
629 return Py_BuildValue("");
633 #if defined(linux) && defined(FS_IOC_GETFLAGS)
634 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
641 if (!PyArg_ParseTuple(args, "s", &path))
644 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
646 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
649 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
653 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
657 return Py_BuildValue("k", attr);
661 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
668 if (!PyArg_ParseTuple(args, "sk", &path, &attr))
671 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
673 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
675 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
679 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
683 return Py_BuildValue("O", Py_None);
685 #endif /* def linux */
687 #ifdef HAVE_UTIMENSAT
688 #if defined(_ATFILE_SOURCE) \
689 || _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
690 #define HAVE_BUP_UTIMENSAT 1
692 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
694 int rc, dirfd, flags;
696 long access, access_ns, modification, modification_ns;
697 struct timespec ts[2];
699 if (!PyArg_ParseTuple(args, "is((ll)(ll))i",
703 &modification, &modification_ns,
709 PyErr_SetString(PyExc_ValueError, "access time is NaN");
712 else if (isinf(access))
714 PyErr_SetString(PyExc_ValueError, "access time is infinite");
717 else if (isnan(modification))
719 PyErr_SetString(PyExc_ValueError, "modification time is NaN");
722 else if (isinf(modification))
724 PyErr_SetString(PyExc_ValueError, "modification time is infinite");
728 if (isnan(access_ns))
730 PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
733 else if (isinf(access_ns))
735 PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
738 else if (isnan(modification_ns))
740 PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
743 else if (isinf(modification_ns))
745 PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
749 ts[0].tv_sec = access;
750 ts[0].tv_nsec = access_ns;
751 ts[1].tv_sec = modification;
752 ts[1].tv_nsec = modification_ns;
754 rc = utimensat(dirfd, path, ts, flags);
756 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
758 return Py_BuildValue("O", Py_None);
761 #endif /* defined(_ATFILE_SOURCE)
762 || _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L */
763 #endif /* HAVE_UTIMENSAT */
765 static PyObject *stat_struct_to_py(const struct stat *st)
767 /* Enforce the current timespec nanosecond range expectations. */
768 if (st->st_atim.tv_nsec < 0 || st->st_atim.tv_nsec > 999999999)
770 PyErr_SetString(PyExc_ValueError, "invalid atime timespec nanoseconds");
773 if (st->st_mtim.tv_nsec < 0 || st->st_mtim.tv_nsec > 999999999)
775 PyErr_SetString(PyExc_ValueError, "invalid mtime timespec nanoseconds");
778 if (st->st_ctim.tv_nsec < 0 || st->st_ctim.tv_nsec > 999999999)
780 PyErr_SetString(PyExc_ValueError, "invalid ctime timespec nanoseconds");
784 return Py_BuildValue("kkkkkkkk(Ll)(Ll)(Ll)",
785 (unsigned long) st->st_mode,
786 (unsigned long) st->st_ino,
787 (unsigned long) st->st_dev,
788 (unsigned long) st->st_nlink,
789 (unsigned long) st->st_uid,
790 (unsigned long) st->st_gid,
791 (unsigned long) st->st_rdev,
792 (unsigned long) st->st_size,
793 (long long) st->st_atime,
794 (long) st->st_atim.tv_nsec,
795 (long long) st->st_mtime,
796 (long) st->st_mtim.tv_nsec,
797 (long long) st->st_ctime,
798 (long) st->st_ctim.tv_nsec);
802 static PyObject *bup_stat(PyObject *self, PyObject *args)
807 if (!PyArg_ParseTuple(args, "s", &filename))
811 rc = stat(filename, &st);
813 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
814 return stat_struct_to_py(&st);
818 static PyObject *bup_lstat(PyObject *self, PyObject *args)
823 if (!PyArg_ParseTuple(args, "s", &filename))
827 rc = lstat(filename, &st);
829 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
830 return stat_struct_to_py(&st);
834 static PyObject *bup_fstat(PyObject *self, PyObject *args)
838 if (!PyArg_ParseTuple(args, "i", &fd))
844 return PyErr_SetFromErrno(PyExc_OSError);
845 return stat_struct_to_py(&st);
849 static PyMethodDef helper_methods[] = {
850 { "selftest", selftest, METH_VARARGS,
851 "Check that the rolling checksum rolls correctly (for unit tests)." },
852 { "blobbits", blobbits, METH_VARARGS,
853 "Return the number of bits in the rolling checksum." },
854 { "splitbuf", splitbuf, METH_VARARGS,
855 "Split a list of strings based on a rolling checksum." },
856 { "bitmatch", bitmatch, METH_VARARGS,
857 "Count the number of matching prefix bits between two strings." },
858 { "firstword", firstword, METH_VARARGS,
859 "Return an int corresponding to the first 32 bits of buf." },
860 { "bloom_contains", bloom_contains, METH_VARARGS,
861 "Check if a bloom filter of 2^nbits bytes contains an object" },
862 { "bloom_add", bloom_add, METH_VARARGS,
863 "Add an object to a bloom filter of 2^nbits bytes" },
864 { "extract_bits", extract_bits, METH_VARARGS,
865 "Take the first 'nbits' bits from 'buf' and return them as an int." },
866 { "merge_into", merge_into, METH_VARARGS,
867 "Merges a bunch of idx and midx files into a single midx." },
868 { "write_idx", write_idx, METH_VARARGS,
869 "Write a PackIdxV2 file from an idx list of lists of tuples" },
870 { "write_random", write_random, METH_VARARGS,
871 "Write random bytes to the given file descriptor" },
872 { "random_sha", random_sha, METH_VARARGS,
873 "Return a random 20-byte string" },
874 { "open_noatime", open_noatime, METH_VARARGS,
875 "open() the given filename for read with O_NOATIME if possible" },
876 { "fadvise_done", fadvise_done, METH_VARARGS,
877 "Inform the kernel that we're finished with earlier parts of a file" },
878 #if defined(linux) && defined(FS_IOC_GETFLAGS)
879 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
880 "Return the Linux attributes for the given file." },
881 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
882 "Set the Linux attributes for the given file." },
884 #ifdef HAVE_BUP_UTIMENSAT
885 { "utimensat", bup_utimensat, METH_VARARGS,
886 "Change file timestamps with nanosecond precision." },
888 { "stat", bup_stat, METH_VARARGS,
889 "Extended version of stat." },
890 { "lstat", bup_lstat, METH_VARARGS,
891 "Extended version of lstat." },
892 { "fstat", bup_fstat, METH_VARARGS,
893 "Extended version of fstat." },
894 { NULL, NULL, 0, NULL }, // sentinel
898 PyMODINIT_FUNC init_helpers(void)
901 PyObject *m = Py_InitModule("_helpers", helper_methods);
904 #ifdef HAVE_BUP_UTIMENSAT
905 PyModule_AddObject(m, "AT_FDCWD", Py_BuildValue("i", AT_FDCWD));
906 PyModule_AddObject(m, "AT_SYMLINK_NOFOLLOW",
907 Py_BuildValue("i", AT_SYMLINK_NOFOLLOW));
909 e = getenv("BUP_FORCE_TTY");
910 istty2 = isatty(2) || (atoi(e ? e : "0") & 2);