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