]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
af9d06f35273cabe4304d1142eb62d7b6e24cee8
[bup.git] / lib / bup / _helpers.c
1 #undef NDEBUG
2 #include "bupsplit.h"
3 #include <Python.h>
4 #include <assert.h>
5 #include <stdint.h>
6 #include <fcntl.h>
7 #include <arpa/inet.h>
8 #include <unistd.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11
12 static int istty2 = 0;
13
14 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
15 #if __WIN32__ || __CYGWIN__
16
17 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
18 static void unpythonize_argv(void) { }
19
20 #else // not __WIN32__
21
22 // For some reason this isn't declared in Python.h
23 extern void Py_GetArgcArgv(int *argc, char ***argv);
24
25 static void unpythonize_argv(void)
26 {
27     int argc, i;
28     char **argv, *arge;
29     
30     Py_GetArgcArgv(&argc, &argv);
31     
32     for (i = 0; i < argc-1; i++)
33     {
34         if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
35         {
36             // The argv block doesn't work the way we expected; it's unsafe
37             // to mess with it.
38             return;
39         }
40     }
41     
42     arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
43     
44     if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
45     {
46         char *p;
47         size_t len, diff;
48         p = strrchr(argv[1], '/');
49         if (p)
50         {
51             p++;
52             diff = p - argv[0];
53             len = arge - p;
54             memmove(argv[0], p, len);
55             memset(arge - diff, 0, diff);
56             for (i = 0; i < argc; i++)
57                 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
58         }
59     }
60 }
61
62 #endif // not __WIN32__ or __CYGWIN__
63
64
65 static PyObject *selftest(PyObject *self, PyObject *args)
66 {
67     if (!PyArg_ParseTuple(args, ""))
68         return NULL;
69     
70     return Py_BuildValue("i", !bupsplit_selftest());
71 }
72
73
74 static PyObject *blobbits(PyObject *self, PyObject *args)
75 {
76     if (!PyArg_ParseTuple(args, ""))
77         return NULL;
78     return Py_BuildValue("i", BUP_BLOBBITS);
79 }
80
81
82 static PyObject *splitbuf(PyObject *self, PyObject *args)
83 {
84     unsigned char *buf = NULL;
85     int len = 0, out = 0, bits = -1;
86
87     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
88         return NULL;
89     out = bupsplit_find_ofs(buf, len, &bits);
90     if (out) assert(bits >= BUP_BLOBBITS);
91     return Py_BuildValue("ii", out, bits);
92 }
93
94
95 static PyObject *bitmatch(PyObject *self, PyObject *args)
96 {
97     unsigned char *buf1 = NULL, *buf2 = NULL;
98     int len1 = 0, len2 = 0;
99     int byte, bit;
100
101     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
102         return NULL;
103     
104     bit = 0;
105     for (byte = 0; byte < len1 && byte < len2; byte++)
106     {
107         int b1 = buf1[byte], b2 = buf2[byte];
108         if (b1 != b2)
109         {
110             for (bit = 0; bit < 8; bit++)
111                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
112                     break;
113             break;
114         }
115     }
116     
117     return Py_BuildValue("i", byte*8 + bit);
118 }
119
120
121 static PyObject *firstword(PyObject *self, PyObject *args)
122 {
123     unsigned char *buf = NULL;
124     int len = 0;
125     uint32_t v;
126
127     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
128         return NULL;
129     
130     if (len < 4)
131         return NULL;
132     
133     v = ntohl(*(uint32_t *)buf);
134     return PyLong_FromUnsignedLong(v);
135 }
136
137
138 #define BLOOM2_HEADERLEN 16
139
140 typedef struct {
141     uint32_t high;
142     unsigned char low;
143 } bits40_t;
144
145 static void to_bloom_address_bitmask4(const bits40_t *buf,
146         const int nbits, uint64_t *v, unsigned char *bitmask)
147 {
148     int bit;
149     uint64_t raw, mask;
150
151     mask = (1<<nbits) - 1;
152     raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
153     bit = (raw >> (37-nbits)) & 0x7;
154     *v = (raw >> (40-nbits)) & mask;
155     *bitmask = 1 << bit;
156 }
157
158 static void to_bloom_address_bitmask5(const uint32_t *buf,
159         const int nbits, uint32_t *v, unsigned char *bitmask)
160 {
161     int bit;
162     uint32_t raw, mask;
163
164     mask = (1<<nbits) - 1;
165     raw = ntohl(*buf);
166     bit = (raw >> (29-nbits)) & 0x7;
167     *v = (raw >> (32-nbits)) & mask;
168     *bitmask = 1 << bit;
169 }
170
171 #define BLOOM_SET_BIT(name, address, itype, otype) \
172 static void name(unsigned char *bloom, const void *buf, const int nbits)\
173 {\
174     unsigned char bitmask;\
175     otype v;\
176     address((itype *)buf, nbits, &v, &bitmask);\
177     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
178 }
179 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
180 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
181
182
183 #define BLOOM_GET_BIT(name, address, itype, otype) \
184 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
185 {\
186     unsigned char bitmask;\
187     otype v;\
188     address((itype *)buf, nbits, &v, &bitmask);\
189     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
190 }
191 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
192 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
193
194
195 static PyObject *bloom_add(PyObject *self, PyObject *args)
196 {
197     unsigned char *sha = NULL, *bloom = NULL;
198     unsigned char *end;
199     int len = 0, blen = 0, nbits = 0, k = 0;
200
201     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
202         return NULL;
203
204     if (blen < 16+(1<<nbits) || len % 20 != 0)
205         return NULL;
206
207     if (k == 5)
208     {
209         if (nbits > 29)
210             return NULL;
211         for (end = sha + len; sha < end; sha += 20/k)
212             bloom_set_bit5(bloom, sha, nbits);
213     }
214     else if (k == 4)
215     {
216         if (nbits > 37)
217             return NULL;
218         for (end = sha + len; sha < end; sha += 20/k)
219             bloom_set_bit4(bloom, sha, nbits);
220     }
221     else
222         return NULL;
223
224
225     return Py_BuildValue("i", len/20);
226 }
227
228 static PyObject *bloom_contains(PyObject *self, PyObject *args)
229 {
230     unsigned char *sha = NULL, *bloom = NULL;
231     int len = 0, blen = 0, nbits = 0, k = 0;
232     unsigned char *end;
233     int steps;
234
235     if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
236         return NULL;
237
238     if (len != 20)
239         return NULL;
240
241     if (k == 5)
242     {
243         if (nbits > 29)
244             return NULL;
245         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
246             if (!bloom_get_bit5(bloom, sha, nbits))
247                 return Py_BuildValue("Oi", Py_None, steps);
248     }
249     else if (k == 4)
250     {
251         if (nbits > 37)
252             return NULL;
253         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
254             if (!bloom_get_bit4(bloom, sha, nbits))
255                 return Py_BuildValue("Oi", Py_None, steps);
256     }
257     else
258         return NULL;
259
260     return Py_BuildValue("Oi", Py_True, k);
261 }
262
263
264 static uint32_t _extract_bits(unsigned char *buf, int nbits)
265 {
266     uint32_t v, mask;
267
268     mask = (1<<nbits) - 1;
269     v = ntohl(*(uint32_t *)buf);
270     v = (v >> (32-nbits)) & mask;
271     return v;
272 }
273 static PyObject *extract_bits(PyObject *self, PyObject *args)
274 {
275     unsigned char *buf = NULL;
276     int len = 0, nbits = 0;
277
278     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
279         return NULL;
280     
281     if (len < 4)
282         return NULL;
283     
284     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
285 }
286
287
288 struct sha {
289     unsigned char bytes[20];
290 };
291 struct idx {
292     unsigned char *map;
293     struct sha *cur;
294     struct sha *end;
295     uint32_t *cur_name;
296     long bytes;
297     int name_base;
298 };
299
300
301 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
302 {
303     int i;
304     for (i = 0; i < sizeof(struct sha); i++)
305         if (sha1->bytes[i] != sha2->bytes[i])
306             return sha1->bytes[i] - sha2->bytes[i];
307     return 0;
308 }
309
310
311 static void _fix_idx_order(struct idx **idxs, int *last_i)
312 {
313     struct idx *idx;
314     int low, mid, high, c = 0;
315
316     idx = idxs[*last_i];
317     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
318     {
319         idxs[*last_i] = NULL;
320         PyMem_Free(idx);
321         --*last_i;
322         return;
323     }
324     if (*last_i == 0)
325         return;
326
327     low = *last_i-1;
328     mid = *last_i;
329     high = 0;
330     while (low >= high)
331     {
332         mid = (low + high) / 2;
333         c = _cmp_sha(idx->cur, idxs[mid]->cur);
334         if (c < 0)
335             high = mid + 1;
336         else if (c > 0)
337             low = mid - 1;
338         else
339             break;
340     }
341     if (c < 0)
342         ++mid;
343     if (mid == *last_i)
344         return;
345     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
346     idxs[mid] = idx;
347 }
348
349
350 static uint32_t _get_idx_i(struct idx *idx)
351 {
352     if (idx->cur_name == NULL)
353         return idx->name_base;
354     return ntohl(*idx->cur_name) + idx->name_base;
355 }
356
357 #define MIDX4_HEADERLEN 12
358
359 static PyObject *merge_into(PyObject *self, PyObject *args)
360 {
361     PyObject *ilist = NULL;
362     unsigned char *fmap = NULL;
363     struct sha *sha_ptr, *sha_start, *last = NULL;
364     uint32_t *table_ptr, *name_ptr, *name_start;
365     struct idx **idxs = NULL;
366     int flen = 0, bits = 0, i;
367     uint32_t total, count, prefix;
368     int num_i;
369     int last_i;
370
371     if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
372         return NULL;
373
374     num_i = PyList_Size(ilist);
375     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
376
377     for (i = 0; i < num_i; i++)
378     {
379         long len, sha_ofs, name_map_ofs;
380         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
381         PyObject *itup = PyList_GetItem(ilist, i);
382         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
383                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
384             return NULL;
385         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
386         idxs[i]->end = &idxs[i]->cur[len];
387         if (name_map_ofs)
388             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
389         else
390             idxs[i]->cur_name = NULL;
391     }
392     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
393     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
394     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
395
396     last_i = num_i-1;
397     count = 0;
398     prefix = 0;
399     while (last_i >= 0)
400     {
401         struct idx *idx;
402         uint32_t new_prefix;
403         if (count % 102424 == 0 && istty2)
404             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
405                     count*100.0/total, count, total);
406         idx = idxs[last_i];
407         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
408         while (prefix < new_prefix)
409             table_ptr[prefix++] = htonl(count);
410         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
411         *name_ptr++ = htonl(_get_idx_i(idx));
412         last = idx->cur;
413         ++idx->cur;
414         if (idx->cur_name != NULL)
415             ++idx->cur_name;
416         _fix_idx_order(idxs, &last_i);
417         ++count;
418     }
419     while (prefix < (1<<bits))
420         table_ptr[prefix++] = htonl(count);
421     assert(count == total);
422     assert(prefix == (1<<bits));
423     assert(sha_ptr == sha_start+count);
424     assert(name_ptr == name_start+count);
425
426     PyMem_Free(idxs);
427     return PyLong_FromUnsignedLong(count);
428 }
429
430 // This function should technically be macro'd out if it's going to be used
431 // more than ocasionally.  As of this writing, it'll actually never be called
432 // in real world bup scenarios (because our packs are < MAX_INT bytes).
433 static uint64_t htonll(uint64_t value)
434 {
435     static const int endian_test = 42;
436
437     if (*(char *)&endian_test == endian_test) // LSB-MSB
438         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
439     return value; // already in network byte order MSB-LSB
440 }
441
442 #define PACK_IDX_V2_HEADERLEN 8
443 #define FAN_ENTRIES 256
444
445 static PyObject *write_idx(PyObject *self, PyObject *args)
446 {
447     PyObject *pf = NULL, *idx = NULL;
448     PyObject *part;
449     FILE *f;
450     unsigned char *fmap = NULL;
451     int flen = 0;
452     uint32_t total = 0;
453     uint32_t count;
454     int i, j, ofs64_count;
455     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
456     struct sha *sha_ptr;
457
458     if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
459         return NULL;
460
461     fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
462     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
463     crc_ptr = (uint32_t *)&sha_ptr[total];
464     ofs_ptr = (uint32_t *)&crc_ptr[total];
465     f = PyFile_AsFile(pf);
466
467     count = 0;
468     ofs64_count = 0;
469     for (i = 0; i < FAN_ENTRIES; ++i)
470     {
471         int plen;
472         part = PyList_GET_ITEM(idx, i);
473         PyList_Sort(part);
474         plen = PyList_GET_SIZE(part);
475         count += plen;
476         *fan_ptr++ = htonl(count);
477         for (j = 0; j < plen; ++j)
478         {
479             unsigned char *sha = NULL;
480             int sha_len = 0;
481             uint32_t crc = 0;
482             uint64_t ofs = 0;
483             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
484                                   &sha, &sha_len, &crc, &ofs))
485                 return NULL;
486             if (sha_len != sizeof(struct sha))
487                 return NULL;
488             memcpy(sha_ptr++, sha, sizeof(struct sha));
489             *crc_ptr++ = htonl(crc);
490             if (ofs > 0x7fffffff)
491             {
492                 uint64_t nofs = htonll(ofs);
493                 if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
494                     return PyErr_SetFromErrno(PyExc_OSError);
495                 ofs = 0x80000000 | ofs64_count++;
496             }
497             *ofs_ptr++ = htonl((uint32_t)ofs);
498         }
499     }
500     return PyLong_FromUnsignedLong(count);
501 }
502
503
504 // I would have made this a lower-level function that just fills in a buffer
505 // with random values, and then written those values from python.  But that's
506 // about 20% slower in my tests, and since we typically generate random
507 // numbers for benchmarking other parts of bup, any slowness in generating
508 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
509 // pseudorandom bytes much except for this anyway.
510 static PyObject *write_random(PyObject *self, PyObject *args)
511 {
512     uint32_t buf[1024/4];
513     int fd = -1, seed = 0, verbose = 0;
514     ssize_t ret;
515     long long len = 0, kbytes = 0, written = 0;
516
517     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
518         return NULL;
519     
520     srandom(seed);
521     
522     for (kbytes = 0; kbytes < len/1024; kbytes++)
523     {
524         unsigned i;
525         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
526             buf[i] = random();
527         ret = write(fd, buf, sizeof(buf));
528         if (ret < 0)
529             ret = 0;
530         written += ret;
531         if (ret < (int)sizeof(buf))
532             break;
533         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
534             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
535     }
536     
537     // handle non-multiples of 1024
538     if (len % 1024)
539     {
540         unsigned i;
541         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
542             buf[i] = random();
543         ret = write(fd, buf, len % 1024);
544         if (ret < 0)
545             ret = 0;
546         written += ret;
547     }
548     
549     if (kbytes/1024 > 0)
550         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
551     return Py_BuildValue("L", written);
552 }
553
554
555 static PyObject *random_sha(PyObject *self, PyObject *args)
556 {
557     static int seeded = 0;
558     uint32_t shabuf[20/4];
559     int i;
560     
561     if (!seeded)
562     {
563         assert(sizeof(shabuf) == 20);
564         srandom(time(NULL));
565         seeded = 1;
566     }
567     
568     if (!PyArg_ParseTuple(args, ""))
569         return NULL;
570     
571     memset(shabuf, 0, sizeof(shabuf));
572     for (i=0; i < 20/4; i++)
573         shabuf[i] = random();
574     return Py_BuildValue("s#", shabuf, 20);
575 }
576
577
578 static PyObject *open_noatime(PyObject *self, PyObject *args)
579 {
580     char *filename = NULL;
581     int attrs, attrs_noatime, fd;
582     if (!PyArg_ParseTuple(args, "s", &filename))
583         return NULL;
584     attrs = O_RDONLY;
585 #ifdef O_NOFOLLOW
586     attrs |= O_NOFOLLOW;
587 #endif
588 #ifdef O_LARGEFILE
589     attrs |= O_LARGEFILE;
590 #endif
591     attrs_noatime = attrs;
592 #ifdef O_NOATIME
593     attrs_noatime |= O_NOATIME;
594 #endif
595     fd = open(filename, attrs_noatime);
596     if (fd < 0 && errno == EPERM)
597     {
598         // older Linux kernels would return EPERM if you used O_NOATIME
599         // and weren't the file's owner.  This pointless restriction was
600         // relaxed eventually, but we have to handle it anyway.
601         // (VERY old kernels didn't recognized O_NOATIME, but they would
602         // just harmlessly ignore it, so this branch won't trigger)
603         fd = open(filename, attrs);
604     }
605     if (fd < 0)
606         return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
607     return Py_BuildValue("i", fd);
608 }
609
610
611 static PyObject *fadvise_done(PyObject *self, PyObject *args)
612 {
613     int fd = -1;
614     long long ofs = 0;
615     if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
616         return NULL;
617 #ifdef POSIX_FADV_DONTNEED
618     posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
619 #endif    
620     return Py_BuildValue("");
621 }
622
623
624 static PyMethodDef faster_methods[] = {
625     { "selftest", selftest, METH_VARARGS,
626         "Check that the rolling checksum rolls correctly (for unit tests)." },
627     { "blobbits", blobbits, METH_VARARGS,
628         "Return the number of bits in the rolling checksum." },
629     { "splitbuf", splitbuf, METH_VARARGS,
630         "Split a list of strings based on a rolling checksum." },
631     { "bitmatch", bitmatch, METH_VARARGS,
632         "Count the number of matching prefix bits between two strings." },
633     { "firstword", firstword, METH_VARARGS,
634         "Return an int corresponding to the first 32 bits of buf." },
635     { "bloom_contains", bloom_contains, METH_VARARGS,
636         "Check if a bloom filter of 2^nbits bytes contains an object" },
637     { "bloom_add", bloom_add, METH_VARARGS,
638         "Add an object to a bloom filter of 2^nbits bytes" },
639     { "extract_bits", extract_bits, METH_VARARGS,
640         "Take the first 'nbits' bits from 'buf' and return them as an int." },
641     { "merge_into", merge_into, METH_VARARGS,
642         "Merges a bunch of idx and midx files into a single midx." },
643     { "write_idx", write_idx, METH_VARARGS,
644         "Write a PackIdxV2 file from an idx list of lists of tuples" },
645     { "write_random", write_random, METH_VARARGS,
646         "Write random bytes to the given file descriptor" },
647     { "random_sha", random_sha, METH_VARARGS,
648         "Return a random 20-byte string" },
649     { "open_noatime", open_noatime, METH_VARARGS,
650         "open() the given filename for read with O_NOATIME if possible" },
651     { "fadvise_done", fadvise_done, METH_VARARGS,
652         "Inform the kernel that we're finished with earlier parts of a file" },
653     { NULL, NULL, 0, NULL },  // sentinel
654 };
655
656 PyMODINIT_FUNC init_helpers(void)
657 {
658     char *e = getenv("BUP_FORCE_TTY");
659     Py_InitModule("_helpers", faster_methods);
660     istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
661     unpythonize_argv();
662 }