]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
2af13bb27d595e17aa5786cf18b96e0a2f049d10
[bup.git] / lib / bup / _helpers.c
1 #define _LARGEFILE64_SOURCE 1
2 #define PY_SSIZE_T_CLEAN 1
3 #undef NDEBUG
4 #include "../../config/config.h"
5
6 // According to Python, its header has to go first:
7 //   http://docs.python.org/2/c-api/intro.html#include-files
8 #include <Python.h>
9
10 #include <assert.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <arpa/inet.h>
14 #include <stdint.h>
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <sys/mman.h>
18
19 #ifdef HAVE_SYS_TYPES_H
20 #include <sys/types.h>
21 #endif
22 #ifdef HAVE_SYS_STAT_H
23 #include <sys/stat.h>
24 #endif
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28
29 #ifdef HAVE_LINUX_FS_H
30 #include <linux/fs.h>
31 #endif
32 #ifdef HAVE_SYS_IOCTL_H
33 #include <sys/ioctl.h>
34 #endif
35
36 #include "bupsplit.h"
37
38 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
39 #define BUP_HAVE_FILE_ATTRS 1
40 #endif
41
42 #ifndef FS_NOCOW_FL
43 // Of course, this assumes it's a bitfield value.
44 #define FS_NOCOW_FL 0
45 #endif
46
47 static int istty2 = 0;
48
49 // At the moment any code that calls INTGER_TO_PY() will have to
50 // disable -Wtautological-compare for clang.  See below.
51
52 #define INTEGER_TO_PY(x) \
53     (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
54
55
56 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
57                                 const char *name)
58 {
59     const long tmp = PyInt_AsLong(py);
60     if (tmp == -1 && PyErr_Occurred())
61     {
62         if (PyErr_ExceptionMatches(PyExc_OverflowError))
63             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
64                          name);
65         return 0;
66     }
67     if (tmp < 0)
68     {
69         PyErr_Format(PyExc_OverflowError,
70                      "negative %s cannot be converted to unsigned long", name);
71         return 0;
72     }
73     *x = tmp;
74     return 1;
75 }
76
77
78 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
79 {
80     if (PyInt_Check(py))
81         return bup_ulong_from_pyint(x, py, name);
82
83     if (!PyLong_Check(py))
84     {
85         PyErr_Format(PyExc_TypeError, "expected integer %s", name);
86         return 0;
87     }
88
89     const unsigned long tmp = PyLong_AsUnsignedLong(py);
90     if (PyErr_Occurred())
91     {
92         if (PyErr_ExceptionMatches(PyExc_OverflowError))
93             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
94                          name);
95         return 0;
96     }
97     *x = tmp;
98     return 1;
99 }
100
101
102 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
103 {
104     unsigned long tmp;
105     if (!bup_ulong_from_py(&tmp, py, name))
106         return 0;
107
108     if (tmp > UINT_MAX)
109     {
110         PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
111         return 0;
112     }
113     *x = tmp;
114     return 1;
115 }
116
117 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
118                               const char *name)
119 {
120     if (PyInt_Check(py))
121     {
122         unsigned long tmp;
123         if (bup_ulong_from_pyint(&tmp, py, name))
124         {
125             *x = tmp;
126             return 1;
127         }
128         return 0;
129     }
130
131     if (!PyLong_Check(py))
132     {
133         PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
134         return 0;
135     }
136
137     const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
138     if (tmp == (unsigned long long) -1 && PyErr_Occurred())
139     {
140         if (PyErr_ExceptionMatches(PyExc_OverflowError))
141             PyErr_Format(PyExc_OverflowError,
142                          "%s too big for unsigned long long", name);
143         return 0;
144     }
145     *x = tmp;
146     return 1;
147 }
148
149
150 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
151 #if __WIN32__ || __CYGWIN__
152
153 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
154 static void unpythonize_argv(void) { }
155
156 #else // not __WIN32__
157
158 // For some reason this isn't declared in Python.h
159 extern void Py_GetArgcArgv(int *argc, char ***argv);
160
161 static void unpythonize_argv(void)
162 {
163     int argc, i;
164     char **argv, *arge;
165     
166     Py_GetArgcArgv(&argc, &argv);
167     
168     for (i = 0; i < argc-1; i++)
169     {
170         if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
171         {
172             // The argv block doesn't work the way we expected; it's unsafe
173             // to mess with it.
174             return;
175         }
176     }
177     
178     arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
179     
180     if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
181     {
182         char *p;
183         size_t len, diff;
184         p = strrchr(argv[1], '/');
185         if (p)
186         {
187             p++;
188             diff = p - argv[0];
189             len = arge - p;
190             memmove(argv[0], p, len);
191             memset(arge - diff, 0, diff);
192             for (i = 0; i < argc; i++)
193                 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
194         }
195     }
196 }
197
198 #endif // not __WIN32__ or __CYGWIN__
199
200
201 static PyObject *selftest(PyObject *self, PyObject *args)
202 {
203     if (!PyArg_ParseTuple(args, ""))
204         return NULL;
205     
206     return Py_BuildValue("i", !bupsplit_selftest());
207 }
208
209
210 static PyObject *blobbits(PyObject *self, PyObject *args)
211 {
212     if (!PyArg_ParseTuple(args, ""))
213         return NULL;
214     return Py_BuildValue("i", BUP_BLOBBITS);
215 }
216
217
218 static PyObject *splitbuf(PyObject *self, PyObject *args)
219 {
220     unsigned char *buf = NULL;
221     Py_ssize_t len = 0;
222     int out = 0, bits = -1;
223
224     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
225         return NULL;
226     assert(len <= INT_MAX);
227     out = bupsplit_find_ofs(buf, len, &bits);
228     if (out) assert(bits >= BUP_BLOBBITS);
229     return Py_BuildValue("ii", out, bits);
230 }
231
232
233 static PyObject *bitmatch(PyObject *self, PyObject *args)
234 {
235     unsigned char *buf1 = NULL, *buf2 = NULL;
236     Py_ssize_t len1 = 0, len2 = 0;
237     Py_ssize_t byte;
238     int bit;
239
240     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
241         return NULL;
242     
243     bit = 0;
244     for (byte = 0; byte < len1 && byte < len2; byte++)
245     {
246         int b1 = buf1[byte], b2 = buf2[byte];
247         if (b1 != b2)
248         {
249             for (bit = 0; bit < 8; bit++)
250                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
251                     break;
252             break;
253         }
254     }
255     
256     assert(byte <= (INT_MAX >> 3));
257     return Py_BuildValue("i", byte*8 + bit);
258 }
259
260
261 static PyObject *firstword(PyObject *self, PyObject *args)
262 {
263     unsigned char *buf = NULL;
264     Py_ssize_t len = 0;
265     uint32_t v;
266
267     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
268         return NULL;
269     
270     if (len < 4)
271         return NULL;
272     
273     v = ntohl(*(uint32_t *)buf);
274     return PyLong_FromUnsignedLong(v);
275 }
276
277
278 #define BLOOM2_HEADERLEN 16
279
280 static void to_bloom_address_bitmask4(const unsigned char *buf,
281         const int nbits, uint64_t *v, unsigned char *bitmask)
282 {
283     int bit;
284     uint32_t high;
285     uint64_t raw, mask;
286
287     memcpy(&high, buf, 4);
288     mask = (1<<nbits) - 1;
289     raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
290     bit = (raw >> (37-nbits)) & 0x7;
291     *v = (raw >> (40-nbits)) & mask;
292     *bitmask = 1 << bit;
293 }
294
295 static void to_bloom_address_bitmask5(const unsigned char *buf,
296         const int nbits, uint32_t *v, unsigned char *bitmask)
297 {
298     int bit;
299     uint32_t high;
300     uint32_t raw, mask;
301
302     memcpy(&high, buf, 4);
303     mask = (1<<nbits) - 1;
304     raw = ntohl(high);
305     bit = (raw >> (29-nbits)) & 0x7;
306     *v = (raw >> (32-nbits)) & mask;
307     *bitmask = 1 << bit;
308 }
309
310 #define BLOOM_SET_BIT(name, address, otype) \
311 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
312 {\
313     unsigned char bitmask;\
314     otype v;\
315     address(buf, nbits, &v, &bitmask);\
316     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
317 }
318 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
319 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
320
321
322 #define BLOOM_GET_BIT(name, address, otype) \
323 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
324 {\
325     unsigned char bitmask;\
326     otype v;\
327     address(buf, nbits, &v, &bitmask);\
328     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
329 }
330 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
331 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
332
333
334 static PyObject *bloom_add(PyObject *self, PyObject *args)
335 {
336     unsigned char *sha = NULL, *bloom = NULL;
337     unsigned char *end;
338     Py_ssize_t len = 0, blen = 0;
339     int nbits = 0, k = 0;
340
341     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
342         return NULL;
343
344     if (blen < 16+(1<<nbits) || len % 20 != 0)
345         return NULL;
346
347     if (k == 5)
348     {
349         if (nbits > 29)
350             return NULL;
351         for (end = sha + len; sha < end; sha += 20/k)
352             bloom_set_bit5(bloom, sha, nbits);
353     }
354     else if (k == 4)
355     {
356         if (nbits > 37)
357             return NULL;
358         for (end = sha + len; sha < end; sha += 20/k)
359             bloom_set_bit4(bloom, sha, nbits);
360     }
361     else
362         return NULL;
363
364
365     return Py_BuildValue("n", len/20);
366 }
367
368 static PyObject *bloom_contains(PyObject *self, PyObject *args)
369 {
370     unsigned char *sha = NULL, *bloom = NULL;
371     Py_ssize_t len = 0, blen = 0;
372     int nbits = 0, k = 0;
373     unsigned char *end;
374     int steps;
375
376     if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
377         return NULL;
378
379     if (len != 20)
380         return NULL;
381
382     if (k == 5)
383     {
384         if (nbits > 29)
385             return NULL;
386         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
387             if (!bloom_get_bit5(bloom, sha, nbits))
388                 return Py_BuildValue("Oi", Py_None, steps);
389     }
390     else if (k == 4)
391     {
392         if (nbits > 37)
393             return NULL;
394         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
395             if (!bloom_get_bit4(bloom, sha, nbits))
396                 return Py_BuildValue("Oi", Py_None, steps);
397     }
398     else
399         return NULL;
400
401     return Py_BuildValue("ii", 1, k);
402 }
403
404
405 static uint32_t _extract_bits(unsigned char *buf, int nbits)
406 {
407     uint32_t v, mask;
408
409     mask = (1<<nbits) - 1;
410     v = ntohl(*(uint32_t *)buf);
411     v = (v >> (32-nbits)) & mask;
412     return v;
413 }
414
415
416 static PyObject *extract_bits(PyObject *self, PyObject *args)
417 {
418     unsigned char *buf = NULL;
419     Py_ssize_t len = 0;
420     int nbits = 0;
421
422     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
423         return NULL;
424     
425     if (len < 4)
426         return NULL;
427     
428     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
429 }
430
431
432 struct sha {
433     unsigned char bytes[20];
434 };
435
436
437 struct idx {
438     unsigned char *map;
439     struct sha *cur;
440     struct sha *end;
441     uint32_t *cur_name;
442     Py_ssize_t bytes;
443     int name_base;
444 };
445
446
447 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
448 {
449     int i;
450     for (i = 0; i < sizeof(struct sha); i++)
451         if (sha1->bytes[i] != sha2->bytes[i])
452             return sha1->bytes[i] - sha2->bytes[i];
453     return 0;
454 }
455
456
457 static void _fix_idx_order(struct idx **idxs, int *last_i)
458 {
459     struct idx *idx;
460     int low, mid, high, c = 0;
461
462     idx = idxs[*last_i];
463     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
464     {
465         idxs[*last_i] = NULL;
466         PyMem_Free(idx);
467         --*last_i;
468         return;
469     }
470     if (*last_i == 0)
471         return;
472
473     low = *last_i-1;
474     mid = *last_i;
475     high = 0;
476     while (low >= high)
477     {
478         mid = (low + high) / 2;
479         c = _cmp_sha(idx->cur, idxs[mid]->cur);
480         if (c < 0)
481             high = mid + 1;
482         else if (c > 0)
483             low = mid - 1;
484         else
485             break;
486     }
487     if (c < 0)
488         ++mid;
489     if (mid == *last_i)
490         return;
491     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
492     idxs[mid] = idx;
493 }
494
495
496 static uint32_t _get_idx_i(struct idx *idx)
497 {
498     if (idx->cur_name == NULL)
499         return idx->name_base;
500     return ntohl(*idx->cur_name) + idx->name_base;
501 }
502
503 #define MIDX4_HEADERLEN 12
504
505 static PyObject *merge_into(PyObject *self, PyObject *args)
506 {
507     PyObject *py_total, *ilist = NULL;
508     unsigned char *fmap = NULL;
509     struct sha *sha_ptr, *sha_start = NULL;
510     uint32_t *table_ptr, *name_ptr, *name_start;
511     struct idx **idxs = NULL;
512     Py_ssize_t flen = 0;
513     int bits = 0, i;
514     unsigned int total;
515     uint32_t count, prefix;
516     int num_i;
517     int last_i;
518
519     if (!PyArg_ParseTuple(args, "w#iOO",
520                           &fmap, &flen, &bits, &py_total, &ilist))
521         return NULL;
522
523     if (!bup_uint_from_py(&total, py_total, "total"))
524         return NULL;
525
526     num_i = PyList_Size(ilist);
527     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
528
529     for (i = 0; i < num_i; i++)
530     {
531         long len, sha_ofs, name_map_ofs;
532         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
533         PyObject *itup = PyList_GetItem(ilist, i);
534         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
535                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
536             return NULL;
537         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
538         idxs[i]->end = &idxs[i]->cur[len];
539         if (name_map_ofs)
540             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
541         else
542             idxs[i]->cur_name = NULL;
543     }
544     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
545     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
546     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
547
548     last_i = num_i-1;
549     count = 0;
550     prefix = 0;
551     while (last_i >= 0)
552     {
553         struct idx *idx;
554         uint32_t new_prefix;
555         if (count % 102424 == 0 && istty2)
556             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
557                     count*100.0/total, count, total);
558         idx = idxs[last_i];
559         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
560         while (prefix < new_prefix)
561             table_ptr[prefix++] = htonl(count);
562         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
563         *name_ptr++ = htonl(_get_idx_i(idx));
564         ++idx->cur;
565         if (idx->cur_name != NULL)
566             ++idx->cur_name;
567         _fix_idx_order(idxs, &last_i);
568         ++count;
569     }
570     while (prefix < (1<<bits))
571         table_ptr[prefix++] = htonl(count);
572     assert(count == total);
573     assert(prefix == (1<<bits));
574     assert(sha_ptr == sha_start+count);
575     assert(name_ptr == name_start+count);
576
577     PyMem_Free(idxs);
578     return PyLong_FromUnsignedLong(count);
579 }
580
581 // This function should technically be macro'd out if it's going to be used
582 // more than ocasionally.  As of this writing, it'll actually never be called
583 // in real world bup scenarios (because our packs are < MAX_INT bytes).
584 static uint64_t htonll(uint64_t value)
585 {
586     static const int endian_test = 42;
587
588     if (*(char *)&endian_test == endian_test) // LSB-MSB
589         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
590     return value; // already in network byte order MSB-LSB
591 }
592
593 #define FAN_ENTRIES 256
594
595 static PyObject *write_idx(PyObject *self, PyObject *args)
596 {
597     char *filename = NULL;
598     PyObject *py_total, *idx = NULL;
599     PyObject *part;
600     unsigned char *fmap = NULL;
601     Py_ssize_t flen = 0;
602     unsigned int total = 0;
603     uint32_t count;
604     int i, j, ofs64_count;
605     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
606     uint64_t *ofs64_ptr;
607     struct sha *sha_ptr;
608
609     if (!PyArg_ParseTuple(args, "sw#OO",
610                           &filename, &fmap, &flen, &idx, &py_total))
611         return NULL;
612
613     if (!bup_uint_from_py(&total, py_total, "total"))
614         return NULL;
615
616     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
617         return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
618                              FAN_ENTRIES);
619
620     const char idx_header[] = "\377tOc\0\0\0\002";
621     memcpy (fmap, idx_header, sizeof(idx_header) - 1);
622
623     fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
624     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
625     crc_ptr = (uint32_t *)&sha_ptr[total];
626     ofs_ptr = (uint32_t *)&crc_ptr[total];
627     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
628
629     count = 0;
630     ofs64_count = 0;
631     for (i = 0; i < FAN_ENTRIES; ++i)
632     {
633         int plen;
634         part = PyList_GET_ITEM(idx, i);
635         PyList_Sort(part);
636         plen = PyList_GET_SIZE(part);
637         count += plen;
638         *fan_ptr++ = htonl(count);
639         for (j = 0; j < plen; ++j)
640         {
641             unsigned char *sha = NULL;
642             Py_ssize_t sha_len = 0;
643             PyObject *crc_py, *ofs_py;
644             unsigned int crc;
645             unsigned PY_LONG_LONG ofs_ull;
646             uint64_t ofs;
647             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
648                                   &sha, &sha_len, &crc_py, &ofs_py))
649                 return NULL;
650             if(!bup_uint_from_py(&crc, crc_py, "crc"))
651                 return NULL;
652             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
653                 return NULL;
654             assert(crc <= UINT32_MAX);
655             assert(ofs_ull <= UINT64_MAX);
656             ofs = ofs_ull;
657             if (sha_len != sizeof(struct sha))
658                 return NULL;
659             memcpy(sha_ptr++, sha, sizeof(struct sha));
660             *crc_ptr++ = htonl(crc);
661             if (ofs > 0x7fffffff)
662             {
663                 *ofs64_ptr++ = htonll(ofs);
664                 ofs = 0x80000000 | ofs64_count++;
665             }
666             *ofs_ptr++ = htonl((uint32_t)ofs);
667         }
668     }
669
670     int rc = msync(fmap, flen, MS_ASYNC);
671     if (rc != 0)
672         return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
673
674     return PyLong_FromUnsignedLong(count);
675 }
676
677
678 // I would have made this a lower-level function that just fills in a buffer
679 // with random values, and then written those values from python.  But that's
680 // about 20% slower in my tests, and since we typically generate random
681 // numbers for benchmarking other parts of bup, any slowness in generating
682 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
683 // pseudorandom bytes much except for this anyway.
684 static PyObject *write_random(PyObject *self, PyObject *args)
685 {
686     uint32_t buf[1024/4];
687     int fd = -1, seed = 0, verbose = 0;
688     ssize_t ret;
689     long long len = 0, kbytes = 0, written = 0;
690
691     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
692         return NULL;
693     
694     srandom(seed);
695     
696     for (kbytes = 0; kbytes < len/1024; kbytes++)
697     {
698         unsigned i;
699         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
700             buf[i] = random();
701         ret = write(fd, buf, sizeof(buf));
702         if (ret < 0)
703             ret = 0;
704         written += ret;
705         if (ret < (int)sizeof(buf))
706             break;
707         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
708             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
709     }
710     
711     // handle non-multiples of 1024
712     if (len % 1024)
713     {
714         unsigned i;
715         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
716             buf[i] = random();
717         ret = write(fd, buf, len % 1024);
718         if (ret < 0)
719             ret = 0;
720         written += ret;
721     }
722     
723     if (kbytes/1024 > 0)
724         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
725     return Py_BuildValue("L", written);
726 }
727
728
729 static PyObject *random_sha(PyObject *self, PyObject *args)
730 {
731     static int seeded = 0;
732     uint32_t shabuf[20/4];
733     int i;
734     
735     if (!seeded)
736     {
737         assert(sizeof(shabuf) == 20);
738         srandom(time(NULL));
739         seeded = 1;
740     }
741     
742     if (!PyArg_ParseTuple(args, ""))
743         return NULL;
744     
745     memset(shabuf, 0, sizeof(shabuf));
746     for (i=0; i < 20/4; i++)
747         shabuf[i] = random();
748     return Py_BuildValue("s#", shabuf, 20);
749 }
750
751
752 static int _open_noatime(const char *filename, int attrs)
753 {
754     int attrs_noatime, fd;
755     attrs |= O_RDONLY;
756 #ifdef O_NOFOLLOW
757     attrs |= O_NOFOLLOW;
758 #endif
759 #ifdef O_LARGEFILE
760     attrs |= O_LARGEFILE;
761 #endif
762     attrs_noatime = attrs;
763 #ifdef O_NOATIME
764     attrs_noatime |= O_NOATIME;
765 #endif
766     fd = open(filename, attrs_noatime);
767     if (fd < 0 && errno == EPERM)
768     {
769         // older Linux kernels would return EPERM if you used O_NOATIME
770         // and weren't the file's owner.  This pointless restriction was
771         // relaxed eventually, but we have to handle it anyway.
772         // (VERY old kernels didn't recognized O_NOATIME, but they would
773         // just harmlessly ignore it, so this branch won't trigger)
774         fd = open(filename, attrs);
775     }
776     return fd;
777 }
778
779
780 static PyObject *open_noatime(PyObject *self, PyObject *args)
781 {
782     char *filename = NULL;
783     int fd;
784     if (!PyArg_ParseTuple(args, "s", &filename))
785         return NULL;
786     fd = _open_noatime(filename, 0);
787     if (fd < 0)
788         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
789     return Py_BuildValue("i", fd);
790 }
791
792
793 static PyObject *fadvise_done(PyObject *self, PyObject *args)
794 {
795     int fd = -1;
796     long long ofs = 0;
797     if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
798         return NULL;
799 #ifdef POSIX_FADV_DONTNEED
800     posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
801 #endif    
802     return Py_BuildValue("");
803 }
804
805
806 #ifdef BUP_HAVE_FILE_ATTRS
807 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
808 {
809     int rc;
810     unsigned int attr;
811     char *path;
812     int fd;
813
814     if (!PyArg_ParseTuple(args, "s", &path))
815         return NULL;
816
817     fd = _open_noatime(path, O_NONBLOCK);
818     if (fd == -1)
819         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
820
821     attr = 0;
822     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
823     if (rc == -1)
824     {
825         close(fd);
826         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
827     }
828
829     close(fd);
830     return Py_BuildValue("I", attr);
831 }
832 #endif /* def BUP_HAVE_FILE_ATTRS */
833
834
835
836 #ifdef BUP_HAVE_FILE_ATTRS
837 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
838 {
839     int rc;
840     unsigned int orig_attr, attr;
841     char *path;
842     PyObject *py_attr;
843     int fd;
844
845     if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
846         return NULL;
847
848     if (!bup_uint_from_py(&attr, py_attr, "attr"))
849         return NULL;
850
851     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
852     if (fd == -1)
853         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
854
855     // Restrict attr to modifiable flags acdeijstuADST -- see
856     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
857     // in pf.c flags_array[].
858     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
859     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
860     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
861     | FS_TOPDIR_FL | FS_NOCOW_FL;
862
863     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
864     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
865     if (rc == -1)
866     {
867         close(fd);
868         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
869     }
870     attr |= (orig_attr & FS_EXTENT_FL);
871
872     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
873     if (rc == -1)
874     {
875         close(fd);
876         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
877     }
878
879     close(fd);
880     return Py_BuildValue("O", Py_None);
881 }
882 #endif /* def BUP_HAVE_FILE_ATTRS */
883
884
885 #ifndef HAVE_UTIMENSAT
886 #ifndef HAVE_UTIMES
887 #error "cannot find utimensat or utimes()"
888 #endif
889 #ifndef HAVE_LUTIMES
890 #error "cannot find utimensat or lutimes()"
891 #endif
892 #endif
893
894
895 #define INTEGRAL_ASSIGNMENT_FITS(dest, src)                             \
896     ({                                                                  \
897         *(dest) = (src);                                                \
898         *(dest) == (src) && (*(dest) < 1) == ((src) < 1);               \
899     })
900
901
902 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
903     ({                                                     \
904         int result = 0;                                                 \
905         *(overflow) = 0;                                                \
906         const long long ltmp = PyLong_AsLongLong(pylong);               \
907         if (ltmp == -1 && PyErr_Occurred())                             \
908         {                                                               \
909             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
910             {                                                           \
911                 const unsigned long ultmp = PyLong_AsUnsignedLongLong(pylong); \
912                 if (ultmp == (unsigned long long) -1 && PyErr_Occurred()) \
913                 {                                                       \
914                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
915                     {                                                   \
916                         PyErr_Clear();                                  \
917                         *(overflow) = 1;                                \
918                     }                                                   \
919                 }                                                       \
920                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ultmp))            \
921                     result = 1;                                         \
922                 else                                                    \
923                     *(overflow) = 1;                                    \
924             }                                                           \
925         }                                                               \
926         else                                                            \
927         {                                                               \
928             if (INTEGRAL_ASSIGNMENT_FITS((dest), ltmp))                 \
929                 result = 1;                                             \
930             else                                                        \
931                 *(overflow) = 1;                                        \
932         }                                                               \
933         result;                                                         \
934         })
935
936
937 #ifdef HAVE_UTIMENSAT
938
939 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
940 {
941     int rc;
942     int fd, flag;
943     char *path;
944     PyObject *access_py, *modification_py;
945     struct timespec ts[2];
946
947     if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
948                           &fd,
949                           &path,
950                           &access_py, &(ts[0].tv_nsec),
951                           &modification_py, &(ts[1].tv_nsec),
952                           &flag))
953         return NULL;
954
955     int overflow;
956     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
957     {
958         if (overflow)
959             PyErr_SetString(PyExc_ValueError,
960                             "unable to convert access time seconds for utimensat");
961         return NULL;
962     }
963     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
964     {
965         if (overflow)
966             PyErr_SetString(PyExc_ValueError,
967                             "unable to convert modification time seconds for utimensat");
968         return NULL;
969     }
970     rc = utimensat(fd, path, ts, flag);
971     if (rc != 0)
972         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
973
974     return Py_BuildValue("O", Py_None);
975 }
976
977 #endif /* def HAVE_UTIMENSAT */
978
979
980 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
981
982 static int bup_parse_xutimes_args(char **path,
983                                   struct timeval tv[2],
984                                   PyObject *args)
985 {
986     PyObject *access_py, *modification_py;
987     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
988
989     if (!PyArg_ParseTuple(args, "s((OL)(OL))",
990                           path,
991                           &access_py, &access_us,
992                           &modification_py, &modification_us))
993         return 0;
994
995     int overflow;
996     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
997     {
998         if (overflow)
999             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1000         return 0;
1001     }
1002     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1003     {
1004         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1005         return 0;
1006     }
1007     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1008     {
1009         if (overflow)
1010             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1011         return 0;
1012     }
1013     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1014     {
1015         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1016         return 0;
1017     }
1018     return 1;
1019 }
1020
1021 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1022
1023
1024 #ifdef HAVE_UTIMES
1025 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1026 {
1027     char *path;
1028     struct timeval tv[2];
1029     if (!bup_parse_xutimes_args(&path, tv, args))
1030         return NULL;
1031     int rc = utimes(path, tv);
1032     if (rc != 0)
1033         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1034     return Py_BuildValue("O", Py_None);
1035 }
1036 #endif /* def HAVE_UTIMES */
1037
1038
1039 #ifdef HAVE_LUTIMES
1040 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1041 {
1042     char *path;
1043     struct timeval tv[2];
1044     if (!bup_parse_xutimes_args(&path, tv, args))
1045         return NULL;
1046     int rc = lutimes(path, tv);
1047     if (rc != 0)
1048         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1049
1050     return Py_BuildValue("O", Py_None);
1051 }
1052 #endif /* def HAVE_LUTIMES */
1053
1054
1055 #ifdef HAVE_STAT_ST_ATIM
1056 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1057 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1058 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1059 #elif defined HAVE_STAT_ST_ATIMENSEC
1060 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1061 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1062 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1063 #else
1064 # define BUP_STAT_ATIME_NS(st) 0
1065 # define BUP_STAT_MTIME_NS(st) 0
1066 # define BUP_STAT_CTIME_NS(st) 0
1067 #endif
1068
1069
1070 #pragma clang diagnostic push
1071 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1072
1073 static PyObject *stat_struct_to_py(const struct stat *st,
1074                                    const char *filename,
1075                                    int fd)
1076 {
1077     // We can check the known (via POSIX) signed and unsigned types at
1078     // compile time, but not (easily) the unspecified types, so handle
1079     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1080     // long.
1081     return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1082                          INTEGER_TO_PY(st->st_mode),
1083                          (unsigned PY_LONG_LONG) st->st_ino,
1084                          INTEGER_TO_PY(st->st_dev),
1085                          INTEGER_TO_PY(st->st_nlink),
1086                          INTEGER_TO_PY(st->st_uid),
1087                          INTEGER_TO_PY(st->st_gid),
1088                          INTEGER_TO_PY(st->st_rdev),
1089                          (PY_LONG_LONG) st->st_size,
1090                          INTEGER_TO_PY(st->st_atime),
1091                          (long) BUP_STAT_ATIME_NS(st),
1092                          INTEGER_TO_PY(st->st_mtime),
1093                          (long) BUP_STAT_MTIME_NS(st),
1094                          INTEGER_TO_PY(st->st_ctime),
1095                          (long) BUP_STAT_CTIME_NS(st));
1096 }
1097
1098 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1099
1100 static PyObject *bup_stat(PyObject *self, PyObject *args)
1101 {
1102     int rc;
1103     char *filename;
1104
1105     if (!PyArg_ParseTuple(args, "s", &filename))
1106         return NULL;
1107
1108     struct stat st;
1109     rc = stat(filename, &st);
1110     if (rc != 0)
1111         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1112     return stat_struct_to_py(&st, filename, 0);
1113 }
1114
1115
1116 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1117 {
1118     int rc;
1119     char *filename;
1120
1121     if (!PyArg_ParseTuple(args, "s", &filename))
1122         return NULL;
1123
1124     struct stat st;
1125     rc = lstat(filename, &st);
1126     if (rc != 0)
1127         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1128     return stat_struct_to_py(&st, filename, 0);
1129 }
1130
1131
1132 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1133 {
1134     int rc, fd;
1135
1136     if (!PyArg_ParseTuple(args, "i", &fd))
1137         return NULL;
1138
1139     struct stat st;
1140     rc = fstat(fd, &st);
1141     if (rc != 0)
1142         return PyErr_SetFromErrno(PyExc_OSError);
1143     return stat_struct_to_py(&st, NULL, fd);
1144 }
1145
1146
1147 static PyMethodDef helper_methods[] = {
1148     { "selftest", selftest, METH_VARARGS,
1149         "Check that the rolling checksum rolls correctly (for unit tests)." },
1150     { "blobbits", blobbits, METH_VARARGS,
1151         "Return the number of bits in the rolling checksum." },
1152     { "splitbuf", splitbuf, METH_VARARGS,
1153         "Split a list of strings based on a rolling checksum." },
1154     { "bitmatch", bitmatch, METH_VARARGS,
1155         "Count the number of matching prefix bits between two strings." },
1156     { "firstword", firstword, METH_VARARGS,
1157         "Return an int corresponding to the first 32 bits of buf." },
1158     { "bloom_contains", bloom_contains, METH_VARARGS,
1159         "Check if a bloom filter of 2^nbits bytes contains an object" },
1160     { "bloom_add", bloom_add, METH_VARARGS,
1161         "Add an object to a bloom filter of 2^nbits bytes" },
1162     { "extract_bits", extract_bits, METH_VARARGS,
1163         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1164     { "merge_into", merge_into, METH_VARARGS,
1165         "Merges a bunch of idx and midx files into a single midx." },
1166     { "write_idx", write_idx, METH_VARARGS,
1167         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1168     { "write_random", write_random, METH_VARARGS,
1169         "Write random bytes to the given file descriptor" },
1170     { "random_sha", random_sha, METH_VARARGS,
1171         "Return a random 20-byte string" },
1172     { "open_noatime", open_noatime, METH_VARARGS,
1173         "open() the given filename for read with O_NOATIME if possible" },
1174     { "fadvise_done", fadvise_done, METH_VARARGS,
1175         "Inform the kernel that we're finished with earlier parts of a file" },
1176 #ifdef BUP_HAVE_FILE_ATTRS
1177     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1178       "Return the Linux attributes for the given file." },
1179 #endif
1180 #ifdef BUP_HAVE_FILE_ATTRS
1181     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1182       "Set the Linux attributes for the given file." },
1183 #endif
1184 #ifdef HAVE_UTIMENSAT
1185     { "bup_utimensat", bup_utimensat, METH_VARARGS,
1186       "Change path timestamps with nanosecond precision (POSIX)." },
1187 #endif
1188 #ifdef HAVE_UTIMES
1189     { "bup_utimes", bup_utimes, METH_VARARGS,
1190       "Change path timestamps with microsecond precision." },
1191 #endif
1192 #ifdef HAVE_LUTIMES
1193     { "bup_lutimes", bup_lutimes, METH_VARARGS,
1194       "Change path timestamps with microsecond precision;"
1195       " don't follow symlinks." },
1196 #endif
1197     { "stat", bup_stat, METH_VARARGS,
1198       "Extended version of stat." },
1199     { "lstat", bup_lstat, METH_VARARGS,
1200       "Extended version of lstat." },
1201     { "fstat", bup_fstat, METH_VARARGS,
1202       "Extended version of fstat." },
1203     { NULL, NULL, 0, NULL },  // sentinel
1204 };
1205
1206
1207 PyMODINIT_FUNC init_helpers(void)
1208 {
1209     // FIXME: migrate these tests to configure.  Check against the
1210     // type we're going to use when passing to python.  Other stat
1211     // types are tested at runtime.
1212     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1213     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1214     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1215     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1216     // Just be sure (relevant when passing timestamps back to Python above).
1217     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1218     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1219
1220     char *e;
1221     PyObject *m = Py_InitModule("_helpers", helper_methods);
1222     if (m == NULL)
1223         return;
1224
1225 #ifdef HAVE_UTIMENSAT
1226 #pragma clang diagnostic push
1227 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1228     {
1229         PyObject *value;
1230         value = INTEGER_TO_PY(AT_FDCWD);
1231         PyObject_SetAttrString(m, "AT_FDCWD", value);
1232         Py_DECREF(value);
1233         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1234         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1235         Py_DECREF(value);
1236         value = INTEGER_TO_PY(UTIME_NOW);
1237         PyObject_SetAttrString(m, "UTIME_NOW", value);
1238         Py_DECREF(value);
1239     }
1240 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1241 #endif
1242
1243     e = getenv("BUP_FORCE_TTY");
1244     istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1245     unpythonize_argv();
1246 }