1 #define _LARGEFILE64_SOURCE 1
16 #include <sys/ioctl.h>
23 static PyObject *selftest(PyObject *self, PyObject *args)
25 if (!PyArg_ParseTuple(args, ""))
28 return Py_BuildValue("i", !bupsplit_selftest());
32 static PyObject *blobbits(PyObject *self, PyObject *args)
34 if (!PyArg_ParseTuple(args, ""))
36 return Py_BuildValue("i", BUP_BLOBBITS);
40 static PyObject *splitbuf(PyObject *self, PyObject *args)
42 unsigned char *buf = NULL;
43 int len = 0, out = 0, bits = -1;
45 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
47 out = bupsplit_find_ofs(buf, len, &bits);
48 return Py_BuildValue("ii", out, bits);
52 static PyObject *bitmatch(PyObject *self, PyObject *args)
54 unsigned char *buf1 = NULL, *buf2 = NULL;
55 int len1 = 0, len2 = 0;
58 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
62 for (byte = 0; byte < len1 && byte < len2; byte++)
64 int b1 = buf1[byte], b2 = buf2[byte];
67 for (bit = 0; bit < 8; bit++)
68 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
74 return Py_BuildValue("i", byte*8 + bit);
78 static PyObject *firstword(PyObject *self, PyObject *args)
80 unsigned char *buf = NULL;
84 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
90 v = ntohl(*(uint32_t *)buf);
91 return PyLong_FromUnsignedLong(v);
101 static void to_bloom_address_bitmask4(const bits40_t *buf,
102 const int nbits, uint64_t *v, unsigned char *bitmask)
107 mask = (1<<nbits) - 1;
108 raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
109 bit = (raw >> (37-nbits)) & 0x7;
110 *v = (raw >> (40-nbits)) & mask;
114 static void to_bloom_address_bitmask5(const uint32_t *buf,
115 const int nbits, uint32_t *v, unsigned char *bitmask)
120 mask = (1<<nbits) - 1;
122 bit = (raw >> (29-nbits)) & 0x7;
123 *v = (raw >> (32-nbits)) & mask;
128 #define BLOOM_SET_BIT(name, address, itype, otype) \
129 static void name(unsigned char *bloom, const void *buf, const int nbits)\
131 unsigned char bitmask;\
133 address((itype *)buf, nbits, &v, &bitmask);\
134 bloom[16+v] |= bitmask;\
136 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
137 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
140 #define BLOOM_GET_BIT(name, address, itype, otype) \
141 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
143 unsigned char bitmask;\
145 address((itype *)buf, nbits, &v, &bitmask);\
146 return bloom[16+v] & bitmask;\
148 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
149 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
152 static PyObject *bloom_add(PyObject *self, PyObject *args)
154 unsigned char *sha = NULL, *bloom = NULL;
156 int len = 0, blen = 0, nbits = 0, k = 0;
158 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
161 if (blen < 16+(1<<nbits) || len % 20 != 0)
168 for (end = sha + len; sha < end; sha += 20/k)
169 bloom_set_bit5(bloom, sha, nbits);
175 for (end = sha + len; sha < end; sha += 20/k)
176 bloom_set_bit4(bloom, sha, nbits);
182 return Py_BuildValue("i", len/20);
185 static PyObject *bloom_contains(PyObject *self, PyObject *args)
187 unsigned char *sha = NULL, *bloom = NULL;
188 int len = 0, blen = 0, nbits = 0, k = 0;
192 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
202 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
203 if (!bloom_get_bit5(bloom, sha, nbits))
204 return Py_BuildValue("Oi", Py_None, steps);
210 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
211 if (!bloom_get_bit4(bloom, sha, nbits))
212 return Py_BuildValue("Oi", Py_None, steps);
217 return Py_BuildValue("Oi", Py_True, k);
221 static uint32_t _extract_bits(unsigned char *buf, int nbits)
225 mask = (1<<nbits) - 1;
226 v = ntohl(*(uint32_t *)buf);
227 v = (v >> (32-nbits)) & mask;
230 static PyObject *extract_bits(PyObject *self, PyObject *args)
232 unsigned char *buf = NULL;
233 int len = 0, nbits = 0;
235 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
241 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
246 unsigned char bytes[20];
258 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
261 for (i = 0; i < 20; i++)
262 if (sha1->bytes[i] != sha2->bytes[i])
263 return sha1->bytes[i] - sha2->bytes[i];
268 static void _fix_idx_order(struct idx **idxs, int *last_i)
271 int low, mid, high, c = 0;
274 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
276 idxs[*last_i] = NULL;
289 mid = (low + high) / 2;
290 c = _cmp_sha(idx->cur, idxs[mid]->cur);
302 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
307 static uint32_t _get_idx_i(struct idx *idx)
309 if (idx->cur_name == NULL)
310 return idx->name_base;
311 return ntohl(*idx->cur_name) + idx->name_base;
315 static PyObject *merge_into(PyObject *self, PyObject *args)
317 PyObject *ilist = NULL;
318 unsigned char *fmap = NULL;
319 struct sha *sha_ptr, *last = NULL;
320 uint32_t *table_ptr, *name_ptr;
321 struct idx **idxs = NULL;
322 int flen = 0, bits = 0, i;
323 uint32_t total, count, prefix;
327 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
330 num_i = PyList_Size(ilist);
331 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
333 for (i = 0; i < num_i; i++)
335 long len, sha_ofs, name_map_ofs;
336 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
337 PyObject *itup = PyList_GetItem(ilist, i);
338 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
339 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
341 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
342 idxs[i]->end = &idxs[i]->cur[len];
344 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
346 idxs[i]->cur_name = NULL;
348 table_ptr = (uint32_t *)&fmap[12];
349 sha_ptr = (struct sha *)&table_ptr[1<<bits];
350 name_ptr = (uint32_t *)&sha_ptr[total];
359 if (count % 102424 == 0 && istty)
360 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
361 count*100.0/total, count, total);
363 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
364 while (prefix < new_prefix)
365 table_ptr[prefix++] = htonl(count);
366 if (last == NULL || _cmp_sha(last, idx->cur) != 0)
368 memcpy(sha_ptr++, idx->cur, 20);
369 *name_ptr++ = htonl(_get_idx_i(idx));
373 if (idx->cur_name != NULL)
375 _fix_idx_order(idxs, &last_i);
378 table_ptr[prefix] = htonl(count);
381 return PyLong_FromUnsignedLong(count);
385 // I would have made this a lower-level function that just fills in a buffer
386 // with random values, and then written those values from python. But that's
387 // about 20% slower in my tests, and since we typically generate random
388 // numbers for benchmarking other parts of bup, any slowness in generating
389 // random bytes will make our benchmarks inaccurate. Plus nobody wants
390 // pseudorandom bytes much except for this anyway.
391 static PyObject *write_random(PyObject *self, PyObject *args)
393 uint32_t buf[1024/4];
394 int fd = -1, seed = 0, verbose = 0;
396 long long len = 0, kbytes = 0, written = 0;
398 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
403 for (kbytes = 0; kbytes < len/1024; kbytes++)
406 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
408 ret = write(fd, buf, sizeof(buf));
412 if (ret < (int)sizeof(buf))
414 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
415 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
418 // handle non-multiples of 1024
422 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
424 ret = write(fd, buf, len % 1024);
431 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
432 return Py_BuildValue("L", written);
436 static PyObject *random_sha(PyObject *self, PyObject *args)
438 static int seeded = 0;
439 uint32_t shabuf[20/4];
444 assert(sizeof(shabuf) == 20);
449 if (!PyArg_ParseTuple(args, ""))
452 memset(shabuf, 0, sizeof(shabuf));
453 for (i=0; i < 20/4; i++)
454 shabuf[i] = random();
455 return Py_BuildValue("s#", shabuf, 20);
459 static PyObject *open_noatime(PyObject *self, PyObject *args)
461 char *filename = NULL;
462 int attrs, attrs_noatime, fd;
463 if (!PyArg_ParseTuple(args, "s", &filename))
470 attrs |= O_LARGEFILE;
472 attrs_noatime = attrs;
474 attrs_noatime |= O_NOATIME;
476 fd = open(filename, attrs_noatime);
477 if (fd < 0 && errno == EPERM)
479 // older Linux kernels would return EPERM if you used O_NOATIME
480 // and weren't the file's owner. This pointless restriction was
481 // relaxed eventually, but we have to handle it anyway.
482 // (VERY old kernels didn't recognized O_NOATIME, but they would
483 // just harmlessly ignore it, so this branch won't trigger)
484 fd = open(filename, attrs);
487 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
488 return Py_BuildValue("i", fd);
492 static PyObject *fadvise_done(PyObject *self, PyObject *args)
496 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
498 #ifdef POSIX_FADV_DONTNEED
499 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
501 return Py_BuildValue("");
506 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
513 if (!PyArg_ParseTuple(args, "s", &path))
516 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
518 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
521 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
525 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
529 return Py_BuildValue("k", attr);
533 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
540 if (!PyArg_ParseTuple(args, "sk", &path, &attr))
543 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
545 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
547 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
551 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
557 #endif /* def linux */
560 #if defined(_ATFILE_SOURCE) \
561 || _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
562 #define HAVE_BUP_UTIMENSAT 1
564 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
566 int rc, dirfd, flags;
568 long access, access_ns, modification, modification_ns;
569 struct timespec ts[2];
571 if (!PyArg_ParseTuple(args, "is((ll)(ll))i",
575 &modification, &modification_ns,
581 PyErr_SetString(PyExc_ValueError, "access time is NaN");
584 else if (isinf(access))
586 PyErr_SetString(PyExc_ValueError, "access time is infinite");
589 else if (isnan(modification))
591 PyErr_SetString(PyExc_ValueError, "modification time is NaN");
594 else if (isinf(modification))
596 PyErr_SetString(PyExc_ValueError, "modification time is infinite");
600 if (isnan(access_ns))
602 PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
605 else if (isinf(access_ns))
607 PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
610 else if (isnan(modification_ns))
612 PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
615 else if (isinf(modification_ns))
617 PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
621 ts[0].tv_sec = access;
622 ts[0].tv_nsec = access_ns;
623 ts[1].tv_sec = modification;
624 ts[1].tv_nsec = modification_ns;
626 rc = utimensat(dirfd, path, ts, flags);
628 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
633 #endif /* defined(_ATFILE_SOURCE)
634 || _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L */
637 #ifdef linux /* and likely others */
639 #define HAVE_BUP_STAT 1
640 static PyObject *bup_stat(PyObject *self, PyObject *args)
645 if (!PyArg_ParseTuple(args, "s", &filename))
649 rc = stat(filename, &st);
651 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
653 return Py_BuildValue("kkkkkkkk"
657 (unsigned long) st.st_mode,
658 (unsigned long) st.st_ino,
659 (unsigned long) st.st_dev,
660 (unsigned long) st.st_nlink,
661 (unsigned long) st.st_uid,
662 (unsigned long) st.st_gid,
663 (unsigned long) st.st_rdev,
664 (unsigned long) st.st_size,
666 (long) st.st_atim.tv_nsec,
668 (long) st.st_mtim.tv_nsec,
670 (long) st.st_ctim.tv_nsec);
674 #define HAVE_BUP_LSTAT 1
675 static PyObject *bup_lstat(PyObject *self, PyObject *args)
680 if (!PyArg_ParseTuple(args, "s", &filename))
684 rc = lstat(filename, &st);
686 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
688 return Py_BuildValue("kkkkkkkk"
692 (unsigned long) st.st_mode,
693 (unsigned long) st.st_ino,
694 (unsigned long) st.st_dev,
695 (unsigned long) st.st_nlink,
696 (unsigned long) st.st_uid,
697 (unsigned long) st.st_gid,
698 (unsigned long) st.st_rdev,
699 (unsigned long) st.st_size,
701 (long) st.st_atim.tv_nsec,
703 (long) st.st_mtim.tv_nsec,
705 (long) st.st_ctim.tv_nsec);
709 #define HAVE_BUP_FSTAT 1
710 static PyObject *bup_fstat(PyObject *self, PyObject *args)
714 if (!PyArg_ParseTuple(args, "i", &fd))
720 return PyErr_SetFromErrno(PyExc_IOError);
722 return Py_BuildValue("kkkkkkkk"
726 (unsigned long) st.st_mode,
727 (unsigned long) st.st_ino,
728 (unsigned long) st.st_dev,
729 (unsigned long) st.st_nlink,
730 (unsigned long) st.st_uid,
731 (unsigned long) st.st_gid,
732 (unsigned long) st.st_rdev,
733 (unsigned long) st.st_size,
735 (long) st.st_atim.tv_nsec,
737 (long) st.st_mtim.tv_nsec,
739 (long) st.st_ctim.tv_nsec);
742 #endif /* def linux */
745 static PyMethodDef faster_methods[] = {
746 { "selftest", selftest, METH_VARARGS,
747 "Check that the rolling checksum rolls correctly (for unit tests)." },
748 { "blobbits", blobbits, METH_VARARGS,
749 "Return the number of bits in the rolling checksum." },
750 { "splitbuf", splitbuf, METH_VARARGS,
751 "Split a list of strings based on a rolling checksum." },
752 { "bitmatch", bitmatch, METH_VARARGS,
753 "Count the number of matching prefix bits between two strings." },
754 { "firstword", firstword, METH_VARARGS,
755 "Return an int corresponding to the first 32 bits of buf." },
756 { "bloom_contains", bloom_contains, METH_VARARGS,
757 "Check if a bloom filter of 2^nbits bytes contains an object" },
758 { "bloom_add", bloom_add, METH_VARARGS,
759 "Add an object to a bloom filter of 2^nbits bytes" },
760 { "extract_bits", extract_bits, METH_VARARGS,
761 "Take the first 'nbits' bits from 'buf' and return them as an int." },
762 { "merge_into", merge_into, METH_VARARGS,
763 "Merges a bunch of idx and midx files into a single midx." },
764 { "write_random", write_random, METH_VARARGS,
765 "Write random bytes to the given file descriptor" },
766 { "random_sha", random_sha, METH_VARARGS,
767 "Return a random 20-byte string" },
768 { "open_noatime", open_noatime, METH_VARARGS,
769 "open() the given filename for read with O_NOATIME if possible" },
770 { "fadvise_done", fadvise_done, METH_VARARGS,
771 "Inform the kernel that we're finished with earlier parts of a file" },
773 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
774 "Return the Linux attributes for the given file." },
775 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
776 "Set the Linux attributes for the given file." },
778 #ifdef HAVE_BUP_UTIMENSAT
779 { "utimensat", bup_utimensat, METH_VARARGS,
780 "Change file timestamps with nanosecond precision." },
783 { "stat", bup_stat, METH_VARARGS,
784 "Extended version of stat." },
786 #ifdef HAVE_BUP_LSTAT
787 { "lstat", bup_lstat, METH_VARARGS,
788 "Extended version of lstat." },
790 #ifdef HAVE_BUP_FSTAT
791 { "fstat", bup_fstat, METH_VARARGS,
792 "Extended version of fstat." },
794 { NULL, NULL, 0, NULL }, // sentinel
798 PyMODINIT_FUNC init_helpers(void)
800 PyObject *m = Py_InitModule("_helpers", faster_methods);
803 #ifdef HAVE_BUP_UTIMENSAT
804 PyModule_AddObject(m, "AT_FDCWD", Py_BuildValue("i", AT_FDCWD));
805 PyModule_AddObject(m, "AT_SYMLINK_NOFOLLOW",
806 Py_BuildValue("i", AT_SYMLINK_NOFOLLOW));
810 PyModule_AddObject(m, "_have_ns_fs_timestamps", Py_True);
813 PyModule_AddObject(m, "_have_ns_fs_timestamps", Py_False);
815 istty = isatty(2) || getenv("BUP_FORCE_TTY");