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