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