]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
d986895affaeda9cd117b1dc9bc909c470a25f5a
[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 <stddef.h>
15 #include <stdint.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
25 #endif
26 #ifdef HAVE_SYS_STAT_H
27 #include <sys/stat.h>
28 #endif
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32
33 #ifdef HAVE_LINUX_FS_H
34 #include <linux/fs.h>
35 #endif
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
38 #endif
39
40 #ifdef HAVE_TM_TM_GMTOFF
41 #include <time.h>
42 #endif
43
44 #include "bupsplit.h"
45
46 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
47 #define BUP_HAVE_FILE_ATTRS 1
48 #endif
49
50 /*
51  * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
52  * pretend we don't have it.
53  */
54 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
55 #undef HAVE_UTIMENSAT
56 #endif
57
58 #ifndef FS_NOCOW_FL
59 // Of course, this assumes it's a bitfield value.
60 #define FS_NOCOW_FL 0
61 #endif
62
63
64 typedef unsigned char byte;
65
66
67 typedef struct {
68     int istty2;
69 } state_t;
70
71 #if PY_MAJOR_VERSION < 3
72 static state_t state;
73 #  define get_state(x) (&state)
74 #else
75 #  define get_state(x) ((state_t *) PyModule_GetState(x))
76 #endif // PY_MAJOR_VERSION >= 3
77
78
79 #ifndef htonll
80 // This function should technically be macro'd out if it's going to be used
81 // more than ocasionally.  As of this writing, it'll actually never be called
82 // in real world bup scenarios (because our packs are < MAX_INT bytes).
83 static uint64_t htonll(uint64_t value)
84 {
85     static const int endian_test = 42;
86
87     if (*(char *)&endian_test == endian_test) // LSB-MSB
88         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
89     return value; // already in network byte order MSB-LSB
90 }
91 #endif
92
93
94 #define INTEGRAL_ASSIGNMENT_FITS(dest, src)                             \
95     ({                                                                  \
96         *(dest) = (src);                                                \
97         *(dest) == (src) && (*(dest) < 1) == ((src) < 1);               \
98     })
99
100
101 // At the moment any code that calls INTGER_TO_PY() will have to
102 // disable -Wtautological-compare for clang.  See below.
103
104 #define INTEGER_TO_PY(x) \
105     (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
106
107
108
109 #if PY_MAJOR_VERSION < 3
110 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
111                                 const char *name)
112 {
113     const long tmp = PyInt_AsLong(py);
114     if (tmp == -1 && 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     if (tmp < 0)
122     {
123         PyErr_Format(PyExc_OverflowError,
124                      "negative %s cannot be converted to unsigned long", name);
125         return 0;
126     }
127     *x = tmp;
128     return 1;
129 }
130 #endif
131
132
133 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
134 {
135 #if PY_MAJOR_VERSION < 3
136     if (PyInt_Check(py))
137         return bup_ulong_from_pyint(x, py, name);
138 #endif
139
140     if (!PyLong_Check(py))
141     {
142         PyErr_Format(PyExc_TypeError, "expected integer %s", name);
143         return 0;
144     }
145
146     const unsigned long tmp = PyLong_AsUnsignedLong(py);
147     if (PyErr_Occurred())
148     {
149         if (PyErr_ExceptionMatches(PyExc_OverflowError))
150             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
151                          name);
152         return 0;
153     }
154     *x = tmp;
155     return 1;
156 }
157
158
159 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
160 {
161     unsigned long tmp;
162     if (!bup_ulong_from_py(&tmp, py, name))
163         return 0;
164
165     if (tmp > UINT_MAX)
166     {
167         PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
168         return 0;
169     }
170     *x = tmp;
171     return 1;
172 }
173
174 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
175                               const char *name)
176 {
177 #if PY_MAJOR_VERSION < 3
178     if (PyInt_Check(py))
179     {
180         unsigned long tmp;
181         if (bup_ulong_from_pyint(&tmp, py, name))
182         {
183             *x = tmp;
184             return 1;
185         }
186         return 0;
187     }
188 #endif
189
190     if (!PyLong_Check(py))
191     {
192         PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
193         return 0;
194     }
195
196     const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
197     if (tmp == (unsigned long long) -1 && PyErr_Occurred())
198     {
199         if (PyErr_ExceptionMatches(PyExc_OverflowError))
200             PyErr_Format(PyExc_OverflowError,
201                          "%s too big for unsigned long long", name);
202         return 0;
203     }
204     *x = tmp;
205     return 1;
206 }
207
208
209 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
210 {
211     PyObject *py_s1, *py_s2;  // This is really a PyBytes/PyString
212     if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
213         return NULL;
214     char *s1, *s2;
215     Py_ssize_t s1_len, s2_len;
216     if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
217         return NULL;
218     if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
219         return NULL;
220     const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
221     const int cmp = memcmp(s1, s2, n);
222     if (cmp != 0)
223         return PyLong_FromLong(cmp);
224     if (s1_len == s2_len)
225         return PyLong_FromLong(0);;
226     return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
227 }
228
229
230 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
231 #if __WIN32__ || __CYGWIN__
232
233 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
234 static void unpythonize_argv(void) { }
235
236 #else // not __WIN32__
237
238 // For some reason this isn't declared in Python.h
239 extern void Py_GetArgcArgv(int *argc, char ***argv);
240
241 static void unpythonize_argv(void)
242 {
243     int argc, i;
244     char **argv, *arge;
245     
246     Py_GetArgcArgv(&argc, &argv);
247     
248     for (i = 0; i < argc-1; i++)
249     {
250         if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
251         {
252             // The argv block doesn't work the way we expected; it's unsafe
253             // to mess with it.
254             return;
255         }
256     }
257     
258     arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
259     
260     if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
261     {
262         char *p;
263         size_t len, diff;
264         p = strrchr(argv[1], '/');
265         if (p)
266         {
267             p++;
268             diff = p - argv[0];
269             len = arge - p;
270             memmove(argv[0], p, len);
271             memset(arge - diff, 0, diff);
272             for (i = 0; i < argc; i++)
273                 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
274         }
275     }
276 }
277
278 #endif // not __WIN32__ or __CYGWIN__
279
280
281 static int write_all(int fd, const void *buf, const size_t count)
282 {
283     size_t written = 0;
284     while (written < count)
285     {
286         const ssize_t rc = write(fd, buf + written, count - written);
287         if (rc == -1)
288             return -1;
289         written += rc;
290     }
291     return 0;
292 }
293
294
295 static int uadd(unsigned long long *dest,
296                 const unsigned long long x,
297                 const unsigned long long y)
298 {
299     const unsigned long long result = x + y;
300     if (result < x || result < y)
301         return 0;
302     *dest = result;
303     return 1;
304 }
305
306
307 static PyObject *append_sparse_region(const int fd, unsigned long long n)
308 {
309     while (n)
310     {
311         off_t new_off;
312         if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
313             new_off = INT_MAX;
314         const off_t off = lseek(fd, new_off, SEEK_CUR);
315         if (off == (off_t) -1)
316             return PyErr_SetFromErrno(PyExc_IOError);
317         n -= new_off;
318     }
319     return NULL;
320 }
321
322
323 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
324                                      const int fd,
325                                      unsigned long long prev_pending,
326                                      const unsigned long long count)
327 {
328     // Add count additional sparse zeros to prev_pending and store the
329     // result in new_pending, or if the total won't fit in
330     // new_pending, write some of the zeros to fd sparsely, and store
331     // the remaining sum in new_pending.
332     if (!uadd(new_pending, prev_pending, count))
333     {
334         PyObject *err = append_sparse_region(fd, prev_pending);
335         if (err != NULL)
336             return err;
337         *new_pending = count;
338     }
339     return NULL;
340 }
341
342
343 static byte* find_not_zero(const byte * const start, const byte * const end)
344 {
345     // Return a pointer to first non-zero byte between start and end,
346     // or end if there isn't one.
347     assert(start <= end);
348     const unsigned char *cur = start;
349     while (cur < end && *cur == 0)
350         cur++;
351     return (byte *) cur;
352 }
353
354
355 static byte* find_trailing_zeros(const byte * const start,
356                                  const byte * const end)
357 {
358     // Return a pointer to the start of any trailing run of zeros, or
359     // end if there isn't one.
360     assert(start <= end);
361     if (start == end)
362         return (byte *) end;
363     const byte * cur = end;
364     while (cur > start && *--cur == 0) {}
365     if (*cur == 0)
366         return (byte *) cur;
367     else
368         return (byte *) (cur + 1);
369 }
370
371
372 static byte *find_non_sparse_end(const byte * const start,
373                                  const byte * const end,
374                                  const unsigned long long min_len)
375 {
376     // Return the first pointer to a min_len sparse block in [start,
377     // end) if there is one, otherwise a pointer to the start of any
378     // trailing run of zeros.  If there are no trailing zeros, return
379     // end.
380     if (start == end)
381         return (byte *) end;
382     assert(start < end);
383     assert(min_len);
384     // Probe in min_len jumps, searching backward from the jump
385     // destination for a non-zero byte.  If such a byte is found, move
386     // just past it and try again.
387     const byte *candidate = start;
388     // End of any run of zeros, starting at candidate, that we've already seen
389     const byte *end_of_known_zeros = candidate;
390     while (end - candidate >= min_len) // Handle all min_len candidate blocks
391     {
392         const byte * const probe_end = candidate + min_len;
393         const byte * const trailing_zeros =
394             find_trailing_zeros(end_of_known_zeros, probe_end);
395         if (trailing_zeros == probe_end)
396             end_of_known_zeros = candidate = probe_end;
397         else if (trailing_zeros == end_of_known_zeros)
398         {
399             assert(candidate >= start);
400             assert(candidate <= end);
401             assert(*candidate == 0);
402             return (byte *) candidate;
403         }
404         else
405         {
406             candidate = trailing_zeros;
407             end_of_known_zeros = probe_end;
408         }
409     }
410
411     if (candidate == end)
412         return (byte *) end;
413
414     // No min_len sparse run found, search backward from end
415     const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
416                                                             end);
417
418     if (trailing_zeros == end_of_known_zeros)
419     {
420         assert(candidate >= start);
421         assert(candidate < end);
422         assert(*candidate == 0);
423         assert(end - candidate < min_len);
424         return (byte *) candidate;
425     }
426
427     if (trailing_zeros == end)
428     {
429         assert(*(end - 1) != 0);
430         return (byte *) end;
431     }
432
433     assert(end - trailing_zeros < min_len);
434     assert(trailing_zeros >= start);
435     assert(trailing_zeros < end);
436     assert(*trailing_zeros == 0);
437     return (byte *) trailing_zeros;
438 }
439
440
441 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
442 {
443     int fd;
444     unsigned char *buf = NULL;
445     Py_ssize_t sbuf_len;
446     PyObject *py_min_sparse_len, *py_prev_sparse_len;
447     if (!PyArg_ParseTuple(args, "it#OO",
448                           &fd, &buf, &sbuf_len,
449                           &py_min_sparse_len, &py_prev_sparse_len))
450         return NULL;
451     unsigned long long min_sparse_len, prev_sparse_len, buf_len;
452     if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
453         return NULL;
454     if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
455         return NULL;
456     if (sbuf_len < 0)
457         return PyErr_Format(PyExc_ValueError, "negative bufer length");
458     if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
459         return PyErr_Format(PyExc_OverflowError, "buffer length too large");
460
461     const byte * block = buf; // Start of pending block
462     const byte * const end = buf + buf_len;
463     unsigned long long zeros = prev_sparse_len;
464     while (1)
465     {
466         assert(block <= end);
467         if (block == end)
468             return PyLong_FromUnsignedLongLong(zeros);
469
470         if (*block != 0)
471         {
472             // Look for the end of block, i.e. the next sparse run of
473             // at least min_sparse_len zeros, or the end of the
474             // buffer.
475             const byte * const probe = find_non_sparse_end(block + 1, end,
476                                                            min_sparse_len);
477             // Either at end of block, or end of non-sparse; write pending data
478             PyObject *err = append_sparse_region(fd, zeros);
479             if (err != NULL)
480                 return err;
481             int rc = write_all(fd, block, probe - block);
482             if (rc)
483                 return PyErr_SetFromErrno(PyExc_IOError);
484
485             if (end - probe < min_sparse_len)
486                 zeros = end - probe;
487             else
488                 zeros = min_sparse_len;
489             block = probe + zeros;
490         }
491         else // *block == 0
492         {
493             // Should be in the first loop iteration, a sparse run of
494             // zeros, or nearly at the end of the block (within
495             // min_sparse_len).
496             const byte * const zeros_end = find_not_zero(block, end);
497             PyObject *err = record_sparse_zeros(&zeros, fd,
498                                                 zeros, zeros_end - block);
499             if (err != NULL)
500                 return err;
501             assert(block <= zeros_end);
502             block = zeros_end;
503         }
504     }
505 }
506
507
508 static PyObject *selftest(PyObject *self, PyObject *args)
509 {
510     if (!PyArg_ParseTuple(args, ""))
511         return NULL;
512     
513     return Py_BuildValue("i", !bupsplit_selftest());
514 }
515
516
517 static PyObject *blobbits(PyObject *self, PyObject *args)
518 {
519     if (!PyArg_ParseTuple(args, ""))
520         return NULL;
521     return Py_BuildValue("i", BUP_BLOBBITS);
522 }
523
524
525 static PyObject *splitbuf(PyObject *self, PyObject *args)
526 {
527     unsigned char *buf = NULL;
528     Py_ssize_t len = 0;
529     int out = 0, bits = -1;
530
531     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
532         return NULL;
533     assert(len <= INT_MAX);
534     out = bupsplit_find_ofs(buf, len, &bits);
535     if (out) assert(bits >= BUP_BLOBBITS);
536     return Py_BuildValue("ii", out, bits);
537 }
538
539
540 static PyObject *bitmatch(PyObject *self, PyObject *args)
541 {
542     unsigned char *buf1 = NULL, *buf2 = NULL;
543     Py_ssize_t len1 = 0, len2 = 0;
544     Py_ssize_t byte;
545     int bit;
546
547     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
548         return NULL;
549     
550     bit = 0;
551     for (byte = 0; byte < len1 && byte < len2; byte++)
552     {
553         int b1 = buf1[byte], b2 = buf2[byte];
554         if (b1 != b2)
555         {
556             for (bit = 0; bit < 8; bit++)
557                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
558                     break;
559             break;
560         }
561     }
562     
563     assert(byte <= (INT_MAX >> 3));
564     return Py_BuildValue("i", byte*8 + bit);
565 }
566
567
568 static PyObject *firstword(PyObject *self, PyObject *args)
569 {
570     unsigned char *buf = NULL;
571     Py_ssize_t len = 0;
572     uint32_t v;
573
574     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
575         return NULL;
576     
577     if (len < 4)
578         return NULL;
579     
580     v = ntohl(*(uint32_t *)buf);
581     return PyLong_FromUnsignedLong(v);
582 }
583
584
585 #define BLOOM2_HEADERLEN 16
586
587 static void to_bloom_address_bitmask4(const unsigned char *buf,
588         const int nbits, uint64_t *v, unsigned char *bitmask)
589 {
590     int bit;
591     uint32_t high;
592     uint64_t raw, mask;
593
594     memcpy(&high, buf, 4);
595     mask = (1<<nbits) - 1;
596     raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
597     bit = (raw >> (37-nbits)) & 0x7;
598     *v = (raw >> (40-nbits)) & mask;
599     *bitmask = 1 << bit;
600 }
601
602 static void to_bloom_address_bitmask5(const unsigned char *buf,
603         const int nbits, uint32_t *v, unsigned char *bitmask)
604 {
605     int bit;
606     uint32_t high;
607     uint32_t raw, mask;
608
609     memcpy(&high, buf, 4);
610     mask = (1<<nbits) - 1;
611     raw = ntohl(high);
612     bit = (raw >> (29-nbits)) & 0x7;
613     *v = (raw >> (32-nbits)) & mask;
614     *bitmask = 1 << bit;
615 }
616
617 #define BLOOM_SET_BIT(name, address, otype) \
618 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
619 {\
620     unsigned char bitmask;\
621     otype v;\
622     address(buf, nbits, &v, &bitmask);\
623     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
624 }
625 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
626 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
627
628
629 #define BLOOM_GET_BIT(name, address, otype) \
630 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
631 {\
632     unsigned char bitmask;\
633     otype v;\
634     address(buf, nbits, &v, &bitmask);\
635     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
636 }
637 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
638 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
639
640
641 static PyObject *bloom_add(PyObject *self, PyObject *args)
642 {
643     unsigned char *sha = NULL, *bloom = NULL;
644     unsigned char *end;
645     Py_ssize_t len = 0, blen = 0;
646     int nbits = 0, k = 0;
647
648     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
649         return NULL;
650
651     if (blen < 16+(1<<nbits) || len % 20 != 0)
652         return NULL;
653
654     if (k == 5)
655     {
656         if (nbits > 29)
657             return NULL;
658         for (end = sha + len; sha < end; sha += 20/k)
659             bloom_set_bit5(bloom, sha, nbits);
660     }
661     else if (k == 4)
662     {
663         if (nbits > 37)
664             return NULL;
665         for (end = sha + len; sha < end; sha += 20/k)
666             bloom_set_bit4(bloom, sha, nbits);
667     }
668     else
669         return NULL;
670
671
672     return Py_BuildValue("n", len/20);
673 }
674
675 static PyObject *bloom_contains(PyObject *self, PyObject *args)
676 {
677     unsigned char *sha = NULL, *bloom = NULL;
678     Py_ssize_t len = 0, blen = 0;
679     int nbits = 0, k = 0;
680     unsigned char *end;
681     int steps;
682
683     if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
684         return NULL;
685
686     if (len != 20)
687         return NULL;
688
689     if (k == 5)
690     {
691         if (nbits > 29)
692             return NULL;
693         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
694             if (!bloom_get_bit5(bloom, sha, nbits))
695                 return Py_BuildValue("Oi", Py_None, steps);
696     }
697     else if (k == 4)
698     {
699         if (nbits > 37)
700             return NULL;
701         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
702             if (!bloom_get_bit4(bloom, sha, nbits))
703                 return Py_BuildValue("Oi", Py_None, steps);
704     }
705     else
706         return NULL;
707
708     return Py_BuildValue("ii", 1, k);
709 }
710
711
712 static uint32_t _extract_bits(unsigned char *buf, int nbits)
713 {
714     uint32_t v, mask;
715
716     mask = (1<<nbits) - 1;
717     v = ntohl(*(uint32_t *)buf);
718     v = (v >> (32-nbits)) & mask;
719     return v;
720 }
721
722
723 static PyObject *extract_bits(PyObject *self, PyObject *args)
724 {
725     unsigned char *buf = NULL;
726     Py_ssize_t len = 0;
727     int nbits = 0;
728
729     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
730         return NULL;
731     
732     if (len < 4)
733         return NULL;
734     
735     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
736 }
737
738
739 struct sha {
740     unsigned char bytes[20];
741 };
742
743
744 struct idx {
745     unsigned char *map;
746     struct sha *cur;
747     struct sha *end;
748     uint32_t *cur_name;
749     Py_ssize_t bytes;
750     int name_base;
751 };
752
753
754 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
755 {
756     int i;
757     for (i = 0; i < sizeof(struct sha); i++)
758         if (sha1->bytes[i] != sha2->bytes[i])
759             return sha1->bytes[i] - sha2->bytes[i];
760     return 0;
761 }
762
763
764 static void _fix_idx_order(struct idx **idxs, int *last_i)
765 {
766     struct idx *idx;
767     int low, mid, high, c = 0;
768
769     idx = idxs[*last_i];
770     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
771     {
772         idxs[*last_i] = NULL;
773         PyMem_Free(idx);
774         --*last_i;
775         return;
776     }
777     if (*last_i == 0)
778         return;
779
780     low = *last_i-1;
781     mid = *last_i;
782     high = 0;
783     while (low >= high)
784     {
785         mid = (low + high) / 2;
786         c = _cmp_sha(idx->cur, idxs[mid]->cur);
787         if (c < 0)
788             high = mid + 1;
789         else if (c > 0)
790             low = mid - 1;
791         else
792             break;
793     }
794     if (c < 0)
795         ++mid;
796     if (mid == *last_i)
797         return;
798     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
799     idxs[mid] = idx;
800 }
801
802
803 static uint32_t _get_idx_i(struct idx *idx)
804 {
805     if (idx->cur_name == NULL)
806         return idx->name_base;
807     return ntohl(*idx->cur_name) + idx->name_base;
808 }
809
810 #define MIDX4_HEADERLEN 12
811
812 static PyObject *merge_into(PyObject *self, PyObject *args)
813 {
814     PyObject *py_total, *ilist = NULL;
815     unsigned char *fmap = NULL;
816     struct sha *sha_ptr, *sha_start = NULL;
817     uint32_t *table_ptr, *name_ptr, *name_start;
818     struct idx **idxs = NULL;
819     Py_ssize_t flen = 0;
820     int bits = 0, i;
821     unsigned int total;
822     uint32_t count, prefix;
823     int num_i;
824     int last_i;
825
826     if (!PyArg_ParseTuple(args, "w#iOO",
827                           &fmap, &flen, &bits, &py_total, &ilist))
828         return NULL;
829
830     if (!bup_uint_from_py(&total, py_total, "total"))
831         return NULL;
832
833     num_i = PyList_Size(ilist);
834     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
835
836     for (i = 0; i < num_i; i++)
837     {
838         long len, sha_ofs, name_map_ofs;
839         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
840         PyObject *itup = PyList_GetItem(ilist, i);
841         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
842                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
843             return NULL;
844         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
845         idxs[i]->end = &idxs[i]->cur[len];
846         if (name_map_ofs)
847             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
848         else
849             idxs[i]->cur_name = NULL;
850     }
851     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
852     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
853     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
854
855     last_i = num_i-1;
856     count = 0;
857     prefix = 0;
858     while (last_i >= 0)
859     {
860         struct idx *idx;
861         uint32_t new_prefix;
862         if (count % 102424 == 0 && get_state(self)->istty2)
863             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
864                     count*100.0/total, count, total);
865         idx = idxs[last_i];
866         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
867         while (prefix < new_prefix)
868             table_ptr[prefix++] = htonl(count);
869         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
870         *name_ptr++ = htonl(_get_idx_i(idx));
871         ++idx->cur;
872         if (idx->cur_name != NULL)
873             ++idx->cur_name;
874         _fix_idx_order(idxs, &last_i);
875         ++count;
876     }
877     while (prefix < (1<<bits))
878         table_ptr[prefix++] = htonl(count);
879     assert(count == total);
880     assert(prefix == (1<<bits));
881     assert(sha_ptr == sha_start+count);
882     assert(name_ptr == name_start+count);
883
884     PyMem_Free(idxs);
885     return PyLong_FromUnsignedLong(count);
886 }
887
888 #define FAN_ENTRIES 256
889
890 static PyObject *write_idx(PyObject *self, PyObject *args)
891 {
892     char *filename = NULL;
893     PyObject *py_total, *idx = NULL;
894     PyObject *part;
895     unsigned char *fmap = NULL;
896     Py_ssize_t flen = 0;
897     unsigned int total = 0;
898     uint32_t count;
899     int i, j, ofs64_count;
900     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
901     uint64_t *ofs64_ptr;
902     struct sha *sha_ptr;
903
904     if (!PyArg_ParseTuple(args, "sw#OO",
905                           &filename, &fmap, &flen, &idx, &py_total))
906         return NULL;
907
908     if (!bup_uint_from_py(&total, py_total, "total"))
909         return NULL;
910
911     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
912         return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
913                              FAN_ENTRIES);
914
915     const char idx_header[] = "\377tOc\0\0\0\002";
916     memcpy (fmap, idx_header, sizeof(idx_header) - 1);
917
918     fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
919     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
920     crc_ptr = (uint32_t *)&sha_ptr[total];
921     ofs_ptr = (uint32_t *)&crc_ptr[total];
922     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
923
924     count = 0;
925     ofs64_count = 0;
926     for (i = 0; i < FAN_ENTRIES; ++i)
927     {
928         int plen;
929         part = PyList_GET_ITEM(idx, i);
930         PyList_Sort(part);
931         plen = PyList_GET_SIZE(part);
932         count += plen;
933         *fan_ptr++ = htonl(count);
934         for (j = 0; j < plen; ++j)
935         {
936             unsigned char *sha = NULL;
937             Py_ssize_t sha_len = 0;
938             PyObject *crc_py, *ofs_py;
939             unsigned int crc;
940             unsigned PY_LONG_LONG ofs_ull;
941             uint64_t ofs;
942             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
943                                   &sha, &sha_len, &crc_py, &ofs_py))
944                 return NULL;
945             if(!bup_uint_from_py(&crc, crc_py, "crc"))
946                 return NULL;
947             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
948                 return NULL;
949             assert(crc <= UINT32_MAX);
950             assert(ofs_ull <= UINT64_MAX);
951             ofs = ofs_ull;
952             if (sha_len != sizeof(struct sha))
953                 return NULL;
954             memcpy(sha_ptr++, sha, sizeof(struct sha));
955             *crc_ptr++ = htonl(crc);
956             if (ofs > 0x7fffffff)
957             {
958                 *ofs64_ptr++ = htonll(ofs);
959                 ofs = 0x80000000 | ofs64_count++;
960             }
961             *ofs_ptr++ = htonl((uint32_t)ofs);
962         }
963     }
964
965     int rc = msync(fmap, flen, MS_ASYNC);
966     if (rc != 0)
967         return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
968
969     return PyLong_FromUnsignedLong(count);
970 }
971
972
973 // I would have made this a lower-level function that just fills in a buffer
974 // with random values, and then written those values from python.  But that's
975 // about 20% slower in my tests, and since we typically generate random
976 // numbers for benchmarking other parts of bup, any slowness in generating
977 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
978 // pseudorandom bytes much except for this anyway.
979 static PyObject *write_random(PyObject *self, PyObject *args)
980 {
981     uint32_t buf[1024/4];
982     int fd = -1, seed = 0, verbose = 0;
983     ssize_t ret;
984     long long len = 0, kbytes = 0, written = 0;
985
986     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
987         return NULL;
988     
989     srandom(seed);
990     
991     for (kbytes = 0; kbytes < len/1024; kbytes++)
992     {
993         unsigned i;
994         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
995             buf[i] = random();
996         ret = write(fd, buf, sizeof(buf));
997         if (ret < 0)
998             ret = 0;
999         written += ret;
1000         if (ret < (int)sizeof(buf))
1001             break;
1002         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1003             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1004     }
1005     
1006     // handle non-multiples of 1024
1007     if (len % 1024)
1008     {
1009         unsigned i;
1010         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1011             buf[i] = random();
1012         ret = write(fd, buf, len % 1024);
1013         if (ret < 0)
1014             ret = 0;
1015         written += ret;
1016     }
1017     
1018     if (kbytes/1024 > 0)
1019         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1020     return Py_BuildValue("L", written);
1021 }
1022
1023
1024 static PyObject *random_sha(PyObject *self, PyObject *args)
1025 {
1026     static int seeded = 0;
1027     uint32_t shabuf[20/4];
1028     int i;
1029     
1030     if (!seeded)
1031     {
1032         assert(sizeof(shabuf) == 20);
1033         srandom(time(NULL));
1034         seeded = 1;
1035     }
1036     
1037     if (!PyArg_ParseTuple(args, ""))
1038         return NULL;
1039     
1040     memset(shabuf, 0, sizeof(shabuf));
1041     for (i=0; i < 20/4; i++)
1042         shabuf[i] = random();
1043     return Py_BuildValue("s#", shabuf, 20);
1044 }
1045
1046
1047 static int _open_noatime(const char *filename, int attrs)
1048 {
1049     int attrs_noatime, fd;
1050     attrs |= O_RDONLY;
1051 #ifdef O_NOFOLLOW
1052     attrs |= O_NOFOLLOW;
1053 #endif
1054 #ifdef O_LARGEFILE
1055     attrs |= O_LARGEFILE;
1056 #endif
1057     attrs_noatime = attrs;
1058 #ifdef O_NOATIME
1059     attrs_noatime |= O_NOATIME;
1060 #endif
1061     fd = open(filename, attrs_noatime);
1062     if (fd < 0 && errno == EPERM)
1063     {
1064         // older Linux kernels would return EPERM if you used O_NOATIME
1065         // and weren't the file's owner.  This pointless restriction was
1066         // relaxed eventually, but we have to handle it anyway.
1067         // (VERY old kernels didn't recognized O_NOATIME, but they would
1068         // just harmlessly ignore it, so this branch won't trigger)
1069         fd = open(filename, attrs);
1070     }
1071     return fd;
1072 }
1073
1074
1075 static PyObject *open_noatime(PyObject *self, PyObject *args)
1076 {
1077     char *filename = NULL;
1078     int fd;
1079     if (!PyArg_ParseTuple(args, "s", &filename))
1080         return NULL;
1081     fd = _open_noatime(filename, 0);
1082     if (fd < 0)
1083         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1084     return Py_BuildValue("i", fd);
1085 }
1086
1087
1088 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1089 {
1090     int fd = -1;
1091     long long llofs, lllen = 0;
1092     if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1093         return NULL;
1094     off_t ofs, len;
1095     if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1096         return PyErr_Format(PyExc_OverflowError,
1097                             "fadvise offset overflows off_t");
1098     if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1099         return PyErr_Format(PyExc_OverflowError,
1100                             "fadvise length overflows off_t");
1101 #ifdef POSIX_FADV_DONTNEED
1102     posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1103 #endif    
1104     return Py_BuildValue("");
1105 }
1106
1107
1108 // Currently the Linux kernel and FUSE disagree over the type for
1109 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS.  The kernel actually uses int,
1110 // but FUSE chose long (matching the declaration in linux/fs.h).  So
1111 // if you use int, and then traverse a FUSE filesystem, you may
1112 // corrupt the stack.  But if you use long, then you may get invalid
1113 // results on big-endian systems.
1114 //
1115 // For now, we just use long, and then disable Linux attrs entirely
1116 // (with a warning) in helpers.py on systems that are affected.
1117
1118 #ifdef BUP_HAVE_FILE_ATTRS
1119 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1120 {
1121     int rc;
1122     unsigned long attr;
1123     char *path;
1124     int fd;
1125
1126     if (!PyArg_ParseTuple(args, "s", &path))
1127         return NULL;
1128
1129     fd = _open_noatime(path, O_NONBLOCK);
1130     if (fd == -1)
1131         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1132
1133     attr = 0;  // Handle int/long mismatch (see above)
1134     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1135     if (rc == -1)
1136     {
1137         close(fd);
1138         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1139     }
1140     close(fd);
1141     assert(attr <= UINT_MAX);  // Kernel type is actually int
1142     return PyLong_FromUnsignedLong(attr);
1143 }
1144 #endif /* def BUP_HAVE_FILE_ATTRS */
1145
1146
1147
1148 #ifdef BUP_HAVE_FILE_ATTRS
1149 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1150 {
1151     int rc;
1152     unsigned long orig_attr;
1153     unsigned int attr;
1154     char *path;
1155     PyObject *py_attr;
1156     int fd;
1157
1158     if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1159         return NULL;
1160
1161     if (!bup_uint_from_py(&attr, py_attr, "attr"))
1162         return NULL;
1163
1164     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1165     if (fd == -1)
1166         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1167
1168     // Restrict attr to modifiable flags acdeijstuADST -- see
1169     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
1170     // in pf.c flags_array[].
1171     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1172     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1173     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1174     | FS_TOPDIR_FL | FS_NOCOW_FL;
1175
1176     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1177     orig_attr = 0; // Handle int/long mismatch (see above)
1178     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1179     if (rc == -1)
1180     {
1181         close(fd);
1182         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1183     }
1184     assert(orig_attr <= UINT_MAX);  // Kernel type is actually int
1185     attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1186
1187     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1188     if (rc == -1)
1189     {
1190         close(fd);
1191         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1192     }
1193
1194     close(fd);
1195     return Py_BuildValue("O", Py_None);
1196 }
1197 #endif /* def BUP_HAVE_FILE_ATTRS */
1198
1199
1200 #ifndef HAVE_UTIMENSAT
1201 #ifndef HAVE_UTIMES
1202 #error "cannot find utimensat or utimes()"
1203 #endif
1204 #ifndef HAVE_LUTIMES
1205 #error "cannot find utimensat or lutimes()"
1206 #endif
1207 #endif
1208
1209 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1210     ({                                                     \
1211         int result = 0;                                                 \
1212         *(overflow) = 0;                                                \
1213         const long long lltmp = PyLong_AsLongLong(pylong);              \
1214         if (lltmp == -1 && PyErr_Occurred())                            \
1215         {                                                               \
1216             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
1217             {                                                           \
1218                 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1219                 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1220                 {                                                       \
1221                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
1222                     {                                                   \
1223                         PyErr_Clear();                                  \
1224                         *(overflow) = 1;                                \
1225                     }                                                   \
1226                 }                                                       \
1227                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
1228                     result = 1;                                         \
1229                 else                                                    \
1230                     *(overflow) = 1;                                    \
1231             }                                                           \
1232         }                                                               \
1233         else                                                            \
1234         {                                                               \
1235             if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
1236                 result = 1;                                             \
1237             else                                                        \
1238                 *(overflow) = 1;                                        \
1239         }                                                               \
1240         result;                                                         \
1241         })
1242
1243
1244 #ifdef HAVE_UTIMENSAT
1245
1246 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1247 {
1248     int rc;
1249     int fd, flag;
1250     char *path;
1251     PyObject *access_py, *modification_py;
1252     struct timespec ts[2];
1253
1254     if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1255                           &fd,
1256                           &path,
1257                           &access_py, &(ts[0].tv_nsec),
1258                           &modification_py, &(ts[1].tv_nsec),
1259                           &flag))
1260         return NULL;
1261
1262     int overflow;
1263     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1264     {
1265         if (overflow)
1266             PyErr_SetString(PyExc_ValueError,
1267                             "unable to convert access time seconds for utimensat");
1268         return NULL;
1269     }
1270     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1271     {
1272         if (overflow)
1273             PyErr_SetString(PyExc_ValueError,
1274                             "unable to convert modification time seconds for utimensat");
1275         return NULL;
1276     }
1277     rc = utimensat(fd, path, ts, flag);
1278     if (rc != 0)
1279         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1280
1281     return Py_BuildValue("O", Py_None);
1282 }
1283
1284 #endif /* def HAVE_UTIMENSAT */
1285
1286
1287 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1288
1289 static int bup_parse_xutimes_args(char **path,
1290                                   struct timeval tv[2],
1291                                   PyObject *args)
1292 {
1293     PyObject *access_py, *modification_py;
1294     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1295
1296     if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1297                           path,
1298                           &access_py, &access_us,
1299                           &modification_py, &modification_us))
1300         return 0;
1301
1302     int overflow;
1303     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1304     {
1305         if (overflow)
1306             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1307         return 0;
1308     }
1309     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1310     {
1311         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1312         return 0;
1313     }
1314     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1315     {
1316         if (overflow)
1317             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1318         return 0;
1319     }
1320     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1321     {
1322         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1323         return 0;
1324     }
1325     return 1;
1326 }
1327
1328 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1329
1330
1331 #ifdef HAVE_UTIMES
1332 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1333 {
1334     char *path;
1335     struct timeval tv[2];
1336     if (!bup_parse_xutimes_args(&path, tv, args))
1337         return NULL;
1338     int rc = utimes(path, tv);
1339     if (rc != 0)
1340         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1341     return Py_BuildValue("O", Py_None);
1342 }
1343 #endif /* def HAVE_UTIMES */
1344
1345
1346 #ifdef HAVE_LUTIMES
1347 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1348 {
1349     char *path;
1350     struct timeval tv[2];
1351     if (!bup_parse_xutimes_args(&path, tv, args))
1352         return NULL;
1353     int rc = lutimes(path, tv);
1354     if (rc != 0)
1355         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1356
1357     return Py_BuildValue("O", Py_None);
1358 }
1359 #endif /* def HAVE_LUTIMES */
1360
1361
1362 #ifdef HAVE_STAT_ST_ATIM
1363 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1364 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1365 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1366 #elif defined HAVE_STAT_ST_ATIMENSEC
1367 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1368 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1369 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1370 #else
1371 # define BUP_STAT_ATIME_NS(st) 0
1372 # define BUP_STAT_MTIME_NS(st) 0
1373 # define BUP_STAT_CTIME_NS(st) 0
1374 #endif
1375
1376
1377 #pragma clang diagnostic push
1378 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1379
1380 static PyObject *stat_struct_to_py(const struct stat *st,
1381                                    const char *filename,
1382                                    int fd)
1383 {
1384     // We can check the known (via POSIX) signed and unsigned types at
1385     // compile time, but not (easily) the unspecified types, so handle
1386     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1387     // long.
1388     return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1389                          INTEGER_TO_PY(st->st_mode),
1390                          (unsigned PY_LONG_LONG) st->st_ino,
1391                          INTEGER_TO_PY(st->st_dev),
1392                          INTEGER_TO_PY(st->st_nlink),
1393                          INTEGER_TO_PY(st->st_uid),
1394                          INTEGER_TO_PY(st->st_gid),
1395                          INTEGER_TO_PY(st->st_rdev),
1396                          (PY_LONG_LONG) st->st_size,
1397                          INTEGER_TO_PY(st->st_atime),
1398                          (long) BUP_STAT_ATIME_NS(st),
1399                          INTEGER_TO_PY(st->st_mtime),
1400                          (long) BUP_STAT_MTIME_NS(st),
1401                          INTEGER_TO_PY(st->st_ctime),
1402                          (long) BUP_STAT_CTIME_NS(st));
1403 }
1404
1405 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1406
1407 static PyObject *bup_stat(PyObject *self, PyObject *args)
1408 {
1409     int rc;
1410     char *filename;
1411
1412     if (!PyArg_ParseTuple(args, "s", &filename))
1413         return NULL;
1414
1415     struct stat st;
1416     rc = stat(filename, &st);
1417     if (rc != 0)
1418         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1419     return stat_struct_to_py(&st, filename, 0);
1420 }
1421
1422
1423 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1424 {
1425     int rc;
1426     char *filename;
1427
1428     if (!PyArg_ParseTuple(args, "s", &filename))
1429         return NULL;
1430
1431     struct stat st;
1432     rc = lstat(filename, &st);
1433     if (rc != 0)
1434         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1435     return stat_struct_to_py(&st, filename, 0);
1436 }
1437
1438
1439 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1440 {
1441     int rc, fd;
1442
1443     if (!PyArg_ParseTuple(args, "i", &fd))
1444         return NULL;
1445
1446     struct stat st;
1447     rc = fstat(fd, &st);
1448     if (rc != 0)
1449         return PyErr_SetFromErrno(PyExc_OSError);
1450     return stat_struct_to_py(&st, NULL, fd);
1451 }
1452
1453
1454 #ifdef HAVE_TM_TM_GMTOFF
1455 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1456 {
1457     long long lltime;
1458     time_t ttime;
1459     if (!PyArg_ParseTuple(args, "L", &lltime))
1460         return NULL;
1461     if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1462         return PyErr_Format(PyExc_OverflowError, "time value too large");
1463
1464     struct tm tm;
1465     tzset();
1466     if(localtime_r(&ttime, &tm) == NULL)
1467         return PyErr_SetFromErrno(PyExc_OSError);
1468
1469     // Match the Python struct_time values.
1470     return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1471                          1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1472                          tm.tm_hour, tm.tm_min, tm.tm_sec,
1473                          tm.tm_wday, tm.tm_yday + 1,
1474                          tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1475 }
1476 #endif /* def HAVE_TM_TM_GMTOFF */
1477
1478
1479 #ifdef BUP_MINCORE_BUF_TYPE
1480 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1481 {
1482     const char *src;
1483     Py_ssize_t src_ssize;
1484     Py_buffer dest;
1485     PyObject *py_src_n, *py_src_off, *py_dest_off;
1486     if (!PyArg_ParseTuple(args, "s#OOw*O",
1487                           &src, &src_ssize, &py_src_n, &py_src_off,
1488                           &dest, &py_dest_off))
1489         return NULL;
1490
1491     unsigned long long src_size, src_n, src_off, dest_size, dest_off;
1492     if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1493           && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1494           && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1495         return NULL;
1496
1497     if (!INTEGRAL_ASSIGNMENT_FITS(&src_size, src_ssize))
1498         return PyErr_Format(PyExc_OverflowError, "invalid src size");
1499     unsigned long long src_region_end;
1500
1501     if (!uadd(&src_region_end, src_off, src_n))
1502         return PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1503     if (src_region_end > src_size)
1504         return PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1505
1506     if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len))
1507         return PyErr_Format(PyExc_OverflowError, "invalid dest size");
1508     if (dest_off > dest_size)
1509         return PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1510
1511     size_t length;
1512     if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n))
1513         return PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1514     int rc = mincore((void *)(src + src_off), src_n,
1515                      (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1516     if (rc != 0)
1517         return PyErr_SetFromErrno(PyExc_OSError);
1518     return Py_BuildValue("O", Py_None);
1519 }
1520 #endif /* def BUP_MINCORE_BUF_TYPE */
1521
1522
1523 static PyMethodDef helper_methods[] = {
1524     { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1525       "Write buf excepting zeros at the end. Return trailing zero count." },
1526     { "selftest", selftest, METH_VARARGS,
1527         "Check that the rolling checksum rolls correctly (for unit tests)." },
1528     { "blobbits", blobbits, METH_VARARGS,
1529         "Return the number of bits in the rolling checksum." },
1530     { "splitbuf", splitbuf, METH_VARARGS,
1531         "Split a list of strings based on a rolling checksum." },
1532     { "bitmatch", bitmatch, METH_VARARGS,
1533         "Count the number of matching prefix bits between two strings." },
1534     { "firstword", firstword, METH_VARARGS,
1535         "Return an int corresponding to the first 32 bits of buf." },
1536     { "bloom_contains", bloom_contains, METH_VARARGS,
1537         "Check if a bloom filter of 2^nbits bytes contains an object" },
1538     { "bloom_add", bloom_add, METH_VARARGS,
1539         "Add an object to a bloom filter of 2^nbits bytes" },
1540     { "extract_bits", extract_bits, METH_VARARGS,
1541         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1542     { "merge_into", merge_into, METH_VARARGS,
1543         "Merges a bunch of idx and midx files into a single midx." },
1544     { "write_idx", write_idx, METH_VARARGS,
1545         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1546     { "write_random", write_random, METH_VARARGS,
1547         "Write random bytes to the given file descriptor" },
1548     { "random_sha", random_sha, METH_VARARGS,
1549         "Return a random 20-byte string" },
1550     { "open_noatime", open_noatime, METH_VARARGS,
1551         "open() the given filename for read with O_NOATIME if possible" },
1552     { "fadvise_done", fadvise_done, METH_VARARGS,
1553         "Inform the kernel that we're finished with earlier parts of a file" },
1554 #ifdef BUP_HAVE_FILE_ATTRS
1555     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1556       "Return the Linux attributes for the given file." },
1557 #endif
1558 #ifdef BUP_HAVE_FILE_ATTRS
1559     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1560       "Set the Linux attributes for the given file." },
1561 #endif
1562 #ifdef HAVE_UTIMENSAT
1563     { "bup_utimensat", bup_utimensat, METH_VARARGS,
1564       "Change path timestamps with nanosecond precision (POSIX)." },
1565 #endif
1566 #ifdef HAVE_UTIMES
1567     { "bup_utimes", bup_utimes, METH_VARARGS,
1568       "Change path timestamps with microsecond precision." },
1569 #endif
1570 #ifdef HAVE_LUTIMES
1571     { "bup_lutimes", bup_lutimes, METH_VARARGS,
1572       "Change path timestamps with microsecond precision;"
1573       " don't follow symlinks." },
1574 #endif
1575     { "stat", bup_stat, METH_VARARGS,
1576       "Extended version of stat." },
1577     { "lstat", bup_lstat, METH_VARARGS,
1578       "Extended version of lstat." },
1579     { "fstat", bup_fstat, METH_VARARGS,
1580       "Extended version of fstat." },
1581 #ifdef HAVE_TM_TM_GMTOFF
1582     { "localtime", bup_localtime, METH_VARARGS,
1583       "Return struct_time elements plus the timezone offset and name." },
1584 #endif
1585     { "bytescmp", bup_bytescmp, METH_VARARGS,
1586       "Return a negative value if x < y, zero if equal, positive otherwise."},
1587 #ifdef BUP_MINCORE_BUF_TYPE
1588     { "mincore", bup_mincore, METH_VARARGS,
1589       "For mincore(src, src_n, src_off, dest, dest_off)"
1590       " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1591 #endif
1592     { NULL, NULL, 0, NULL },  // sentinel
1593 };
1594
1595 static int setup_module(PyObject *m)
1596 {
1597     // FIXME: migrate these tests to configure, or at least don't
1598     // possibly crash the whole application.  Check against the type
1599     // we're going to use when passing to python.  Other stat types
1600     // are tested at runtime.
1601     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1602     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1603     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1604     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1605     // Just be sure (relevant when passing timestamps back to Python above).
1606     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1607     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1608
1609     // Originally required by append_sparse_region()
1610     {
1611         off_t probe;
1612         if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1613         {
1614             fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1615             exit(1);
1616         }
1617     }
1618
1619     char *e;
1620 #pragma clang diagnostic push
1621 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1622     {
1623         PyObject *value;
1624         value = INTEGER_TO_PY(INT_MAX);
1625         PyObject_SetAttrString(m, "INT_MAX", value);
1626         Py_DECREF(value);
1627         value = INTEGER_TO_PY(UINT_MAX);
1628         PyObject_SetAttrString(m, "UINT_MAX", value);
1629         Py_DECREF(value);
1630     }
1631 #ifdef HAVE_UTIMENSAT
1632     {
1633         PyObject *value;
1634         value = INTEGER_TO_PY(AT_FDCWD);
1635         PyObject_SetAttrString(m, "AT_FDCWD", value);
1636         Py_DECREF(value);
1637         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1638         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1639         Py_DECREF(value);
1640         value = INTEGER_TO_PY(UTIME_NOW);
1641         PyObject_SetAttrString(m, "UTIME_NOW", value);
1642         Py_DECREF(value);
1643     }
1644 #endif
1645 #ifdef BUP_HAVE_MINCORE_INCORE
1646     {
1647         PyObject *value;
1648         value = INTEGER_TO_PY(MINCORE_INCORE);
1649         PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1650         Py_DECREF(value);
1651     }
1652 #endif
1653 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1654
1655     e = getenv("BUP_FORCE_TTY");
1656     get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1657     unpythonize_argv();
1658     return 1;
1659 }
1660
1661
1662 #if PY_MAJOR_VERSION < 3
1663
1664 PyMODINIT_FUNC init_helpers(void)
1665 {
1666     PyObject *m = Py_InitModule("_helpers", helper_methods);
1667     if (m == NULL)
1668         return;
1669
1670     if (!setup_module(m))
1671     {
1672         Py_DECREF(m);
1673         return;
1674     }
1675 }
1676
1677 # else // PY_MAJOR_VERSION >= 3
1678
1679 static struct PyModuleDef helpers_def = {
1680     PyModuleDef_HEAD_INIT,
1681     "_helpers",
1682     NULL,
1683     sizeof(state_t),
1684     helper_methods,
1685     NULL,
1686     NULL, // helpers_traverse,
1687     NULL, // helpers_clear,
1688     NULL
1689 };
1690
1691 PyMODINIT_FUNC PyInit__helpers(void)
1692 {
1693     PyObject *module = PyModule_Create(&helpers_def);
1694     if (module == NULL)
1695         return NULL;
1696     if (!setup_module(module))
1697     {
1698         Py_DECREF(module);
1699         return NULL;
1700     }
1701     return module;
1702 }
1703
1704 #endif // PY_MAJOR_VERSION >= 3