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