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