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