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