]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
open_noatime bup_get_linux_file_attr: accommodate python 3
[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 INTEGER_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 int total = 0;
959     uint32_t count;
960     int i, j, ofs64_count;
961     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
962     uint64_t *ofs64_ptr;
963     struct sha *sha_ptr;
964
965     Py_buffer fmap;
966     if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
967                           &filename, &fmap, &idx, &py_total))
968         return NULL;
969
970     PyObject *result = NULL;
971
972     if (!bup_uint_from_py(&total, py_total, "total"))
973         goto clean_and_return;
974
975     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
976     {
977         result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
978                                FAN_ENTRIES);
979         goto clean_and_return;
980     }
981
982     const char idx_header[] = "\377tOc\0\0\0\002";
983     memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
984
985     fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
986     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
987     crc_ptr = (uint32_t *)&sha_ptr[total];
988     ofs_ptr = (uint32_t *)&crc_ptr[total];
989     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
990
991     count = 0;
992     ofs64_count = 0;
993     for (i = 0; i < FAN_ENTRIES; ++i)
994     {
995         int plen;
996         part = PyList_GET_ITEM(idx, i);
997         PyList_Sort(part);
998         plen = PyList_GET_SIZE(part);
999         count += plen;
1000         *fan_ptr++ = htonl(count);
1001         for (j = 0; j < plen; ++j)
1002         {
1003             unsigned char *sha = NULL;
1004             Py_ssize_t sha_len = 0;
1005             PyObject *crc_py, *ofs_py;
1006             unsigned int crc;
1007             unsigned PY_LONG_LONG ofs_ull;
1008             uint64_t ofs;
1009             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1010                                   &sha, &sha_len, &crc_py, &ofs_py))
1011                 goto clean_and_return;
1012             if(!bup_uint_from_py(&crc, crc_py, "crc"))
1013                 goto clean_and_return;
1014             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1015                 goto clean_and_return;
1016             assert(crc <= UINT32_MAX);
1017             assert(ofs_ull <= UINT64_MAX);
1018             ofs = ofs_ull;
1019             if (sha_len != sizeof(struct sha))
1020                 goto clean_and_return;
1021             memcpy(sha_ptr++, sha, sizeof(struct sha));
1022             *crc_ptr++ = htonl(crc);
1023             if (ofs > 0x7fffffff)
1024             {
1025                 *ofs64_ptr++ = htonll(ofs);
1026                 ofs = 0x80000000 | ofs64_count++;
1027             }
1028             *ofs_ptr++ = htonl((uint32_t)ofs);
1029         }
1030     }
1031
1032     int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1033     if (rc != 0)
1034     {
1035         result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1036         goto clean_and_return;
1037     }
1038
1039     result = PyLong_FromUnsignedLong(count);
1040
1041  clean_and_return:
1042     PyBuffer_Release(&fmap);
1043     return result;
1044 }
1045
1046
1047 // I would have made this a lower-level function that just fills in a buffer
1048 // with random values, and then written those values from python.  But that's
1049 // about 20% slower in my tests, and since we typically generate random
1050 // numbers for benchmarking other parts of bup, any slowness in generating
1051 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
1052 // pseudorandom bytes much except for this anyway.
1053 static PyObject *write_random(PyObject *self, PyObject *args)
1054 {
1055     uint32_t buf[1024/4];
1056     int fd = -1, seed = 0, verbose = 0;
1057     ssize_t ret;
1058     long long len = 0, kbytes = 0, written = 0;
1059
1060     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1061         return NULL;
1062     
1063     srandom(seed);
1064     
1065     for (kbytes = 0; kbytes < len/1024; kbytes++)
1066     {
1067         unsigned i;
1068         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1069             buf[i] = random();
1070         ret = write(fd, buf, sizeof(buf));
1071         if (ret < 0)
1072             ret = 0;
1073         written += ret;
1074         if (ret < (int)sizeof(buf))
1075             break;
1076         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1077             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1078     }
1079     
1080     // handle non-multiples of 1024
1081     if (len % 1024)
1082     {
1083         unsigned i;
1084         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1085             buf[i] = random();
1086         ret = write(fd, buf, len % 1024);
1087         if (ret < 0)
1088             ret = 0;
1089         written += ret;
1090     }
1091     
1092     if (kbytes/1024 > 0)
1093         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1094     return Py_BuildValue("L", written);
1095 }
1096
1097
1098 static PyObject *random_sha(PyObject *self, PyObject *args)
1099 {
1100     static int seeded = 0;
1101     uint32_t shabuf[20/4];
1102     int i;
1103     
1104     if (!seeded)
1105     {
1106         assert(sizeof(shabuf) == 20);
1107         srandom(time(NULL));
1108         seeded = 1;
1109     }
1110     
1111     if (!PyArg_ParseTuple(args, ""))
1112         return NULL;
1113     
1114     memset(shabuf, 0, sizeof(shabuf));
1115     for (i=0; i < 20/4; i++)
1116         shabuf[i] = random();
1117     return Py_BuildValue("s#", shabuf, 20);
1118 }
1119
1120
1121 static int _open_noatime(const char *filename, int attrs)
1122 {
1123     int attrs_noatime, fd;
1124     attrs |= O_RDONLY;
1125 #ifdef O_NOFOLLOW
1126     attrs |= O_NOFOLLOW;
1127 #endif
1128 #ifdef O_LARGEFILE
1129     attrs |= O_LARGEFILE;
1130 #endif
1131     attrs_noatime = attrs;
1132 #ifdef O_NOATIME
1133     attrs_noatime |= O_NOATIME;
1134 #endif
1135     fd = open(filename, attrs_noatime);
1136     if (fd < 0 && errno == EPERM)
1137     {
1138         // older Linux kernels would return EPERM if you used O_NOATIME
1139         // and weren't the file's owner.  This pointless restriction was
1140         // relaxed eventually, but we have to handle it anyway.
1141         // (VERY old kernels didn't recognized O_NOATIME, but they would
1142         // just harmlessly ignore it, so this branch won't trigger)
1143         fd = open(filename, attrs);
1144     }
1145     return fd;
1146 }
1147
1148
1149 static PyObject *open_noatime(PyObject *self, PyObject *args)
1150 {
1151     char *filename = NULL;
1152     int fd;
1153     if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1154         return NULL;
1155     fd = _open_noatime(filename, 0);
1156     if (fd < 0)
1157         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1158     return Py_BuildValue("i", fd);
1159 }
1160
1161
1162 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1163 {
1164     int fd = -1;
1165     long long llofs, lllen = 0;
1166     if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1167         return NULL;
1168     off_t ofs, len;
1169     if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1170         return PyErr_Format(PyExc_OverflowError,
1171                             "fadvise offset overflows off_t");
1172     if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1173         return PyErr_Format(PyExc_OverflowError,
1174                             "fadvise length overflows off_t");
1175 #ifdef POSIX_FADV_DONTNEED
1176     posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1177 #endif    
1178     return Py_BuildValue("");
1179 }
1180
1181
1182 // Currently the Linux kernel and FUSE disagree over the type for
1183 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS.  The kernel actually uses int,
1184 // but FUSE chose long (matching the declaration in linux/fs.h).  So
1185 // if you use int, and then traverse a FUSE filesystem, you may
1186 // corrupt the stack.  But if you use long, then you may get invalid
1187 // results on big-endian systems.
1188 //
1189 // For now, we just use long, and then disable Linux attrs entirely
1190 // (with a warning) in helpers.py on systems that are affected.
1191
1192 #ifdef BUP_HAVE_FILE_ATTRS
1193 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1194 {
1195     int rc;
1196     unsigned long attr;
1197     char *path;
1198     int fd;
1199
1200     if (!PyArg_ParseTuple(args, cstr_argf, &path))
1201         return NULL;
1202
1203     fd = _open_noatime(path, O_NONBLOCK);
1204     if (fd == -1)
1205         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1206
1207     attr = 0;  // Handle int/long mismatch (see above)
1208     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1209     if (rc == -1)
1210     {
1211         close(fd);
1212         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1213     }
1214     close(fd);
1215     assert(attr <= UINT_MAX);  // Kernel type is actually int
1216     return PyLong_FromUnsignedLong(attr);
1217 }
1218 #endif /* def BUP_HAVE_FILE_ATTRS */
1219
1220
1221
1222 #ifdef BUP_HAVE_FILE_ATTRS
1223 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1224 {
1225     int rc;
1226     unsigned long orig_attr;
1227     unsigned int attr;
1228     char *path;
1229     PyObject *py_attr;
1230     int fd;
1231
1232     if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1233         return NULL;
1234
1235     if (!bup_uint_from_py(&attr, py_attr, "attr"))
1236         return NULL;
1237
1238     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1239     if (fd == -1)
1240         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1241
1242     // Restrict attr to modifiable flags acdeijstuADST -- see
1243     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
1244     // in pf.c flags_array[].
1245     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1246     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1247     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1248     | FS_TOPDIR_FL | FS_NOCOW_FL;
1249
1250     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1251     orig_attr = 0; // Handle int/long mismatch (see above)
1252     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1253     if (rc == -1)
1254     {
1255         close(fd);
1256         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1257     }
1258     assert(orig_attr <= UINT_MAX);  // Kernel type is actually int
1259     attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1260
1261     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1262     if (rc == -1)
1263     {
1264         close(fd);
1265         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1266     }
1267
1268     close(fd);
1269     return Py_BuildValue("O", Py_None);
1270 }
1271 #endif /* def BUP_HAVE_FILE_ATTRS */
1272
1273
1274 #ifndef HAVE_UTIMENSAT
1275 #ifndef HAVE_UTIMES
1276 #error "cannot find utimensat or utimes()"
1277 #endif
1278 #ifndef HAVE_LUTIMES
1279 #error "cannot find utimensat or lutimes()"
1280 #endif
1281 #endif
1282
1283 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1284     ({                                                     \
1285         int result = 0;                                                 \
1286         *(overflow) = 0;                                                \
1287         const long long lltmp = PyLong_AsLongLong(pylong);              \
1288         if (lltmp == -1 && PyErr_Occurred())                            \
1289         {                                                               \
1290             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
1291             {                                                           \
1292                 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1293                 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1294                 {                                                       \
1295                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
1296                     {                                                   \
1297                         PyErr_Clear();                                  \
1298                         *(overflow) = 1;                                \
1299                     }                                                   \
1300                 }                                                       \
1301                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
1302                     result = 1;                                         \
1303                 else                                                    \
1304                     *(overflow) = 1;                                    \
1305             }                                                           \
1306         }                                                               \
1307         else                                                            \
1308         {                                                               \
1309             if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
1310                 result = 1;                                             \
1311             else                                                        \
1312                 *(overflow) = 1;                                        \
1313         }                                                               \
1314         result;                                                         \
1315         })
1316
1317
1318 #ifdef HAVE_UTIMENSAT
1319
1320 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1321 {
1322     int rc;
1323     int fd, flag;
1324     char *path;
1325     PyObject *access_py, *modification_py;
1326     struct timespec ts[2];
1327
1328     if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1329                           &fd,
1330                           &path,
1331                           &access_py, &(ts[0].tv_nsec),
1332                           &modification_py, &(ts[1].tv_nsec),
1333                           &flag))
1334         return NULL;
1335
1336     int overflow;
1337     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1338     {
1339         if (overflow)
1340             PyErr_SetString(PyExc_ValueError,
1341                             "unable to convert access time seconds for utimensat");
1342         return NULL;
1343     }
1344     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1345     {
1346         if (overflow)
1347             PyErr_SetString(PyExc_ValueError,
1348                             "unable to convert modification time seconds for utimensat");
1349         return NULL;
1350     }
1351     rc = utimensat(fd, path, ts, flag);
1352     if (rc != 0)
1353         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1354
1355     return Py_BuildValue("O", Py_None);
1356 }
1357
1358 #endif /* def HAVE_UTIMENSAT */
1359
1360
1361 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1362
1363 static int bup_parse_xutimes_args(char **path,
1364                                   struct timeval tv[2],
1365                                   PyObject *args)
1366 {
1367     PyObject *access_py, *modification_py;
1368     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1369
1370     if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1371                           path,
1372                           &access_py, &access_us,
1373                           &modification_py, &modification_us))
1374         return 0;
1375
1376     int overflow;
1377     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1378     {
1379         if (overflow)
1380             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1381         return 0;
1382     }
1383     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1384     {
1385         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1386         return 0;
1387     }
1388     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1389     {
1390         if (overflow)
1391             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1392         return 0;
1393     }
1394     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1395     {
1396         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1397         return 0;
1398     }
1399     return 1;
1400 }
1401
1402 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1403
1404
1405 #ifdef HAVE_UTIMES
1406 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1407 {
1408     char *path;
1409     struct timeval tv[2];
1410     if (!bup_parse_xutimes_args(&path, tv, args))
1411         return NULL;
1412     int rc = utimes(path, tv);
1413     if (rc != 0)
1414         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1415     return Py_BuildValue("O", Py_None);
1416 }
1417 #endif /* def HAVE_UTIMES */
1418
1419
1420 #ifdef HAVE_LUTIMES
1421 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1422 {
1423     char *path;
1424     struct timeval tv[2];
1425     if (!bup_parse_xutimes_args(&path, tv, args))
1426         return NULL;
1427     int rc = lutimes(path, tv);
1428     if (rc != 0)
1429         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1430
1431     return Py_BuildValue("O", Py_None);
1432 }
1433 #endif /* def HAVE_LUTIMES */
1434
1435
1436 #ifdef HAVE_STAT_ST_ATIM
1437 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1438 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1439 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1440 #elif defined HAVE_STAT_ST_ATIMENSEC
1441 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1442 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1443 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1444 #else
1445 # define BUP_STAT_ATIME_NS(st) 0
1446 # define BUP_STAT_MTIME_NS(st) 0
1447 # define BUP_STAT_CTIME_NS(st) 0
1448 #endif
1449
1450
1451 #pragma clang diagnostic push
1452 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1453
1454 static PyObject *stat_struct_to_py(const struct stat *st,
1455                                    const char *filename,
1456                                    int fd)
1457 {
1458     // We can check the known (via POSIX) signed and unsigned types at
1459     // compile time, but not (easily) the unspecified types, so handle
1460     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1461     // long.
1462     return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1463                          INTEGER_TO_PY(st->st_mode),
1464                          (unsigned PY_LONG_LONG) st->st_ino,
1465                          INTEGER_TO_PY(st->st_dev),
1466                          INTEGER_TO_PY(st->st_nlink),
1467                          INTEGER_TO_PY(st->st_uid),
1468                          INTEGER_TO_PY(st->st_gid),
1469                          INTEGER_TO_PY(st->st_rdev),
1470                          (PY_LONG_LONG) st->st_size,
1471                          INTEGER_TO_PY(st->st_atime),
1472                          (long) BUP_STAT_ATIME_NS(st),
1473                          INTEGER_TO_PY(st->st_mtime),
1474                          (long) BUP_STAT_MTIME_NS(st),
1475                          INTEGER_TO_PY(st->st_ctime),
1476                          (long) BUP_STAT_CTIME_NS(st));
1477 }
1478
1479 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1480
1481 static PyObject *bup_stat(PyObject *self, PyObject *args)
1482 {
1483     int rc;
1484     char *filename;
1485
1486     if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1487         return NULL;
1488
1489     struct stat st;
1490     rc = stat(filename, &st);
1491     if (rc != 0)
1492         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1493     return stat_struct_to_py(&st, filename, 0);
1494 }
1495
1496
1497 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1498 {
1499     int rc;
1500     char *filename;
1501
1502     if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1503         return NULL;
1504
1505     struct stat st;
1506     rc = lstat(filename, &st);
1507     if (rc != 0)
1508         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1509     return stat_struct_to_py(&st, filename, 0);
1510 }
1511
1512
1513 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1514 {
1515     int rc, fd;
1516
1517     if (!PyArg_ParseTuple(args, "i", &fd))
1518         return NULL;
1519
1520     struct stat st;
1521     rc = fstat(fd, &st);
1522     if (rc != 0)
1523         return PyErr_SetFromErrno(PyExc_OSError);
1524     return stat_struct_to_py(&st, NULL, fd);
1525 }
1526
1527
1528 #ifdef HAVE_TM_TM_GMTOFF
1529 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1530 {
1531     long long lltime;
1532     time_t ttime;
1533     if (!PyArg_ParseTuple(args, "L", &lltime))
1534         return NULL;
1535     if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1536         return PyErr_Format(PyExc_OverflowError, "time value too large");
1537
1538     struct tm tm;
1539     tzset();
1540     if(localtime_r(&ttime, &tm) == NULL)
1541         return PyErr_SetFromErrno(PyExc_OSError);
1542
1543     // Match the Python struct_time values.
1544     return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1545                          1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1546                          tm.tm_hour, tm.tm_min, tm.tm_sec,
1547                          tm.tm_wday, tm.tm_yday + 1,
1548                          tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1549 }
1550 #endif /* def HAVE_TM_TM_GMTOFF */
1551
1552
1553 #ifdef BUP_MINCORE_BUF_TYPE
1554 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1555 {
1556     Py_buffer src, dest;
1557     PyObject *py_src_n, *py_src_off, *py_dest_off;
1558
1559     if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1560                           &src, &py_src_n, &py_src_off,
1561                           &dest, &py_dest_off))
1562         return NULL;
1563
1564     PyObject *result = NULL;
1565
1566     unsigned long long src_n, src_off, dest_off;
1567     if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1568           && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1569           && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1570         goto clean_and_return;
1571
1572     unsigned long long src_region_end;
1573     if (!uadd(&src_region_end, src_off, src_n)) {
1574         result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1575         goto clean_and_return;
1576     }
1577     assert(src.len >= 0);
1578     if (src_region_end > (unsigned long long) src.len) {
1579         result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1580         goto clean_and_return;
1581     }
1582
1583     unsigned long long dest_size;
1584     if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1585         result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1586         goto clean_and_return;
1587     }
1588     if (dest_off > dest_size) {
1589         result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1590         goto clean_and_return;
1591     }
1592
1593     size_t length;
1594     if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1595         result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1596         goto clean_and_return;
1597     }
1598     int rc = mincore((void *)(src.buf + src_off), src_n,
1599                      (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1600     if (rc != 0) {
1601         result = PyErr_SetFromErrno(PyExc_OSError);
1602         goto clean_and_return;
1603     }
1604     result = Py_BuildValue("O", Py_None);
1605
1606  clean_and_return:
1607     PyBuffer_Release(&src);
1608     PyBuffer_Release(&dest);
1609     return result;
1610 }
1611 #endif /* def BUP_MINCORE_BUF_TYPE */
1612
1613
1614 static PyMethodDef helper_methods[] = {
1615     { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1616       "Write buf excepting zeros at the end. Return trailing zero count." },
1617     { "selftest", selftest, METH_VARARGS,
1618         "Check that the rolling checksum rolls correctly (for unit tests)." },
1619     { "blobbits", blobbits, METH_VARARGS,
1620         "Return the number of bits in the rolling checksum." },
1621     { "splitbuf", splitbuf, METH_VARARGS,
1622         "Split a list of strings based on a rolling checksum." },
1623     { "bitmatch", bitmatch, METH_VARARGS,
1624         "Count the number of matching prefix bits between two strings." },
1625     { "firstword", firstword, METH_VARARGS,
1626         "Return an int corresponding to the first 32 bits of buf." },
1627     { "bloom_contains", bloom_contains, METH_VARARGS,
1628         "Check if a bloom filter of 2^nbits bytes contains an object" },
1629     { "bloom_add", bloom_add, METH_VARARGS,
1630         "Add an object to a bloom filter of 2^nbits bytes" },
1631     { "extract_bits", extract_bits, METH_VARARGS,
1632         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1633     { "merge_into", merge_into, METH_VARARGS,
1634         "Merges a bunch of idx and midx files into a single midx." },
1635     { "write_idx", write_idx, METH_VARARGS,
1636         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1637     { "write_random", write_random, METH_VARARGS,
1638         "Write random bytes to the given file descriptor" },
1639     { "random_sha", random_sha, METH_VARARGS,
1640         "Return a random 20-byte string" },
1641     { "open_noatime", open_noatime, METH_VARARGS,
1642         "open() the given filename for read with O_NOATIME if possible" },
1643     { "fadvise_done", fadvise_done, METH_VARARGS,
1644         "Inform the kernel that we're finished with earlier parts of a file" },
1645 #ifdef BUP_HAVE_FILE_ATTRS
1646     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1647       "Return the Linux attributes for the given file." },
1648 #endif
1649 #ifdef BUP_HAVE_FILE_ATTRS
1650     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1651       "Set the Linux attributes for the given file." },
1652 #endif
1653 #ifdef HAVE_UTIMENSAT
1654     { "bup_utimensat", bup_utimensat, METH_VARARGS,
1655       "Change path timestamps with nanosecond precision (POSIX)." },
1656 #endif
1657 #ifdef HAVE_UTIMES
1658     { "bup_utimes", bup_utimes, METH_VARARGS,
1659       "Change path timestamps with microsecond precision." },
1660 #endif
1661 #ifdef HAVE_LUTIMES
1662     { "bup_lutimes", bup_lutimes, METH_VARARGS,
1663       "Change path timestamps with microsecond precision;"
1664       " don't follow symlinks." },
1665 #endif
1666     { "stat", bup_stat, METH_VARARGS,
1667       "Extended version of stat." },
1668     { "lstat", bup_lstat, METH_VARARGS,
1669       "Extended version of lstat." },
1670     { "fstat", bup_fstat, METH_VARARGS,
1671       "Extended version of fstat." },
1672 #ifdef HAVE_TM_TM_GMTOFF
1673     { "localtime", bup_localtime, METH_VARARGS,
1674       "Return struct_time elements plus the timezone offset and name." },
1675 #endif
1676     { "bytescmp", bup_bytescmp, METH_VARARGS,
1677       "Return a negative value if x < y, zero if equal, positive otherwise."},
1678 #ifdef BUP_MINCORE_BUF_TYPE
1679     { "mincore", bup_mincore, METH_VARARGS,
1680       "For mincore(src, src_n, src_off, dest, dest_off)"
1681       " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1682 #endif
1683     { NULL, NULL, 0, NULL },  // sentinel
1684 };
1685
1686 static void test_integral_assignment_fits(void)
1687 {
1688     assert(sizeof(signed short) == sizeof(unsigned short));
1689     assert(sizeof(signed short) < sizeof(signed long long));
1690     assert(sizeof(signed short) < sizeof(unsigned long long));
1691     assert(sizeof(unsigned short) < sizeof(signed long long));
1692     assert(sizeof(unsigned short) < sizeof(unsigned long long));
1693     {
1694         signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1695         unsigned short us, usmax = USHRT_MAX;
1696         signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1697         unsigned long long ullmax = ULLONG_MAX;
1698
1699         assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1700         assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1701         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1702         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1703         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1704         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1705
1706         assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1707         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1708         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1709         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1710         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1711     }
1712 }
1713
1714 static int setup_module(PyObject *m)
1715 {
1716     // FIXME: migrate these tests to configure, or at least don't
1717     // possibly crash the whole application.  Check against the type
1718     // we're going to use when passing to python.  Other stat types
1719     // are tested at runtime.
1720     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1721     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1722     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1723     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1724     // Just be sure (relevant when passing timestamps back to Python above).
1725     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1726     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1727
1728     test_integral_assignment_fits();
1729
1730     // Originally required by append_sparse_region()
1731     {
1732         off_t probe;
1733         if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1734         {
1735             fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1736             exit(1);
1737         }
1738     }
1739
1740     char *e;
1741 #pragma clang diagnostic push
1742 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1743     {
1744         PyObject *value;
1745         value = INTEGER_TO_PY(INT_MAX);
1746         PyObject_SetAttrString(m, "INT_MAX", value);
1747         Py_DECREF(value);
1748         value = INTEGER_TO_PY(UINT_MAX);
1749         PyObject_SetAttrString(m, "UINT_MAX", value);
1750         Py_DECREF(value);
1751     }
1752 #ifdef HAVE_UTIMENSAT
1753     {
1754         PyObject *value;
1755         value = INTEGER_TO_PY(AT_FDCWD);
1756         PyObject_SetAttrString(m, "AT_FDCWD", value);
1757         Py_DECREF(value);
1758         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1759         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1760         Py_DECREF(value);
1761         value = INTEGER_TO_PY(UTIME_NOW);
1762         PyObject_SetAttrString(m, "UTIME_NOW", value);
1763         Py_DECREF(value);
1764     }
1765 #endif
1766 #ifdef BUP_HAVE_MINCORE_INCORE
1767     {
1768         PyObject *value;
1769         value = INTEGER_TO_PY(MINCORE_INCORE);
1770         PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1771         Py_DECREF(value);
1772     }
1773 #endif
1774 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1775
1776     e = getenv("BUP_FORCE_TTY");
1777     get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1778     unpythonize_argv();
1779     return 1;
1780 }
1781
1782
1783 #if PY_MAJOR_VERSION < 3
1784
1785 PyMODINIT_FUNC init_helpers(void)
1786 {
1787     PyObject *m = Py_InitModule("_helpers", helper_methods);
1788     if (m == NULL)
1789         return;
1790
1791     if (!setup_module(m))
1792     {
1793         Py_DECREF(m);
1794         return;
1795     }
1796 }
1797
1798 # else // PY_MAJOR_VERSION >= 3
1799
1800 static struct PyModuleDef helpers_def = {
1801     PyModuleDef_HEAD_INIT,
1802     "_helpers",
1803     NULL,
1804     sizeof(state_t),
1805     helper_methods,
1806     NULL,
1807     NULL, // helpers_traverse,
1808     NULL, // helpers_clear,
1809     NULL
1810 };
1811
1812 PyMODINIT_FUNC PyInit__helpers(void)
1813 {
1814     PyObject *module = PyModule_Create(&helpers_def);
1815     if (module == NULL)
1816         return NULL;
1817     if (!setup_module(module))
1818     {
1819         Py_DECREF(module);
1820         return NULL;
1821     }
1822     return module;
1823 }
1824
1825 #endif // PY_MAJOR_VERSION >= 3