]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
b5a3c799489e72d051e4735e2207c75e91196a11
[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 //   http://docs.python.org/3/c-api/intro.html#include-files
9 #include <Python.h>
10
11 #include <arpa/inet.h>
12 #include <assert.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <grp.h>
16 #include <pwd.h>
17 #include <stddef.h>
18 #include <stdint.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22
23 #ifdef HAVE_SYS_MMAN_H
24 #include <sys/mman.h>
25 #endif
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #ifdef HAVE_SYS_STAT_H
30 #include <sys/stat.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #ifdef HAVE_SYS_TIME_H
36 #include <sys/time.h>
37 #endif
38
39 #ifdef HAVE_LINUX_FS_H
40 #include <linux/fs.h>
41 #endif
42 #ifdef HAVE_SYS_IOCTL_H
43 #include <sys/ioctl.h>
44 #endif
45
46 #ifdef HAVE_TM_TM_GMTOFF
47 #include <time.h>
48 #endif
49
50 #if defined(BUP_RL_EXPECTED_XOPEN_SOURCE) \
51     && (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < BUP_RL_EXPECTED_XOPEN_SOURCE)
52 # warning "_XOPEN_SOURCE version is incorrect for readline"
53 #endif
54
55 #ifdef BUP_HAVE_READLINE
56 # pragma GCC diagnostic push
57 # pragma GCC diagnostic ignored "-Wstrict-prototypes"
58 # ifdef BUP_READLINE_INCLUDES_IN_SUBDIR
59 #   include <readline/readline.h>
60 #   include <readline/history.h>
61 # else
62 #   include <readline.h>
63 #   include <history.h>
64 # endif
65 # pragma GCC diagnostic pop
66 #endif
67
68 #include "bupsplit.h"
69 #include "bup/intprops.h"
70
71 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
72 #define BUP_HAVE_FILE_ATTRS 1
73 #endif
74
75 #if PY_MAJOR_VERSION > 2
76 # define BUP_USE_PYTHON_UTIME 1
77 #endif
78
79 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
80 /*
81  * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
82  * pretend we don't have it.
83  */
84 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
85 #undef HAVE_UTIMENSAT
86 #endif
87 #endif // defined BUP_USE_PYTHON_UTIME
88
89 #ifndef FS_NOCOW_FL
90 // Of course, this assumes it's a bitfield value.
91 #define FS_NOCOW_FL 0
92 #endif
93
94
95 typedef unsigned char byte;
96
97
98 typedef struct {
99     int istty2;
100 } state_t;
101
102 // cstr_argf: for byte vectors without null characters (e.g. paths)
103 // rbuf_argf: for read-only byte vectors
104 // wbuf_argf: for mutable byte vectors
105
106 #if PY_MAJOR_VERSION < 3
107 static state_t state;
108 #  define get_state(x) (&state)
109 #  define cstr_argf "s"
110 #  define rbuf_argf "s#"
111 #  define wbuf_argf "s*"
112 #else
113 #  define get_state(x) ((state_t *) PyModule_GetState(x))
114 #  define cstr_argf "y"
115 #  define rbuf_argf "y#"
116 #  define wbuf_argf "y*"
117 #endif // PY_MAJOR_VERSION >= 3
118
119
120 static void *checked_calloc(size_t n, size_t size)
121 {
122     void *result = calloc(n, size);
123     if (!result)
124         PyErr_NoMemory();
125     return result;
126 }
127
128 static void *checked_malloc(size_t n, size_t size)
129 {
130     size_t total;
131     if (!INT_MULTIPLY_OK(n, size, &total))
132     {
133         PyErr_Format(PyExc_OverflowError,
134                      "request to allocate %zu items of size %zu is too large",
135                      n, size);
136         return NULL;
137     }
138     void *result = malloc(total);
139     if (!result)
140         return PyErr_NoMemory();
141     return result;
142 }
143
144
145 #ifndef htonll
146 // This function should technically be macro'd out if it's going to be used
147 // more than ocasionally.  As of this writing, it'll actually never be called
148 // in real world bup scenarios (because our packs are < MAX_INT bytes).
149 static uint64_t htonll(uint64_t value)
150 {
151     static const int endian_test = 42;
152
153     if (*(char *)&endian_test == endian_test) // LSB-MSB
154         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
155     return value; // already in network byte order MSB-LSB
156 }
157 #endif
158
159 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) INT_ADD_OK(src, 0, dest)
160
161 #define INTEGER_TO_PY(x) \
162     EXPR_SIGNED(x) ? PyLong_FromLongLong(x) : PyLong_FromUnsignedLongLong(x)
163
164 #if PY_MAJOR_VERSION < 3
165 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
166                                 const char *name)
167 {
168     const long tmp = PyInt_AsLong(py);
169     if (tmp == -1 && PyErr_Occurred())
170     {
171         if (PyErr_ExceptionMatches(PyExc_OverflowError))
172             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
173                          name);
174         return 0;
175     }
176     if (tmp < 0)
177     {
178         PyErr_Format(PyExc_OverflowError,
179                      "negative %s cannot be converted to unsigned long", name);
180         return 0;
181     }
182     *x = tmp;
183     return 1;
184 }
185 #endif
186
187
188 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
189 {
190 #if PY_MAJOR_VERSION < 3
191     if (PyInt_Check(py))
192         return bup_ulong_from_pyint(x, py, name);
193 #endif
194
195     if (!PyLong_Check(py))
196     {
197         PyErr_Format(PyExc_TypeError, "expected integer %s", name);
198         return 0;
199     }
200
201     const unsigned long tmp = PyLong_AsUnsignedLong(py);
202     if (PyErr_Occurred())
203     {
204         if (PyErr_ExceptionMatches(PyExc_OverflowError))
205             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
206                          name);
207         return 0;
208     }
209     *x = tmp;
210     return 1;
211 }
212
213
214 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
215 {
216     unsigned long tmp;
217     if (!bup_ulong_from_py(&tmp, py, name))
218         return 0;
219
220     if (tmp > UINT_MAX)
221     {
222         PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
223         return 0;
224     }
225     *x = (unsigned int) tmp;
226     return 1;
227 }
228
229 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
230                               const char *name)
231 {
232 #if PY_MAJOR_VERSION < 3
233     if (PyInt_Check(py))
234     {
235         unsigned long tmp;
236         if (bup_ulong_from_pyint(&tmp, py, name))
237         {
238             *x = tmp;
239             return 1;
240         }
241         return 0;
242     }
243 #endif
244
245     if (!PyLong_Check(py))
246     {
247         PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
248         return 0;
249     }
250
251     const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
252     if (tmp == (unsigned long long) -1 && PyErr_Occurred())
253     {
254         if (PyErr_ExceptionMatches(PyExc_OverflowError))
255             PyErr_Format(PyExc_OverflowError,
256                          "%s too big for unsigned long long", name);
257         return 0;
258     }
259     *x = tmp;
260     return 1;
261 }
262
263
264 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
265 {
266     PyObject *py_s1, *py_s2;  // This is really a PyBytes/PyString
267     if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
268         return NULL;
269     char *s1, *s2;
270     Py_ssize_t s1_len, s2_len;
271     if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
272         return NULL;
273     if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
274         return NULL;
275     const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
276     const int cmp = memcmp(s1, s2, n);
277     if (cmp != 0)
278         return PyLong_FromLong(cmp);
279     if (s1_len == s2_len)
280         return PyLong_FromLong(0);;
281     return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
282 }
283
284
285 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
286 {
287     unsigned char *bufx = NULL, *bufy = NULL;
288     Py_ssize_t bufx_len, bufx_ofs, bufx_n;
289     Py_ssize_t bufy_len, bufy_ofs, bufy_n;
290     if (!PyArg_ParseTuple(args,
291                           rbuf_argf "nn"
292                           rbuf_argf "nn",
293                           &bufx, &bufx_len, &bufx_ofs, &bufx_n,
294                           &bufy, &bufy_len, &bufy_ofs, &bufy_n))
295         return NULL;
296     if (bufx_ofs < 0)
297         return PyErr_Format(PyExc_ValueError, "negative x offset");
298     if (bufx_n < 0)
299         return PyErr_Format(PyExc_ValueError, "negative x extent");
300     if (bufx_ofs > bufx_len)
301         return PyErr_Format(PyExc_ValueError, "x offset greater than length");
302     if (bufx_n > bufx_len - bufx_ofs)
303         return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
304
305     if (bufy_ofs < 0)
306         return PyErr_Format(PyExc_ValueError, "negative y offset");
307     if (bufy_n < 0)
308         return PyErr_Format(PyExc_ValueError, "negative y extent");
309     if (bufy_ofs > bufy_len)
310         return PyErr_Format(PyExc_ValueError, "y offset greater than length");
311     if (bufy_n > bufy_len - bufy_ofs)
312         return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
313
314     if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
315         return PyErr_Format(PyExc_OverflowError, "result length too long");
316
317     PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
318     if (!result)
319         return PyErr_NoMemory();
320     char *buf = PyBytes_AS_STRING(result);
321     memcpy(buf, bufx + bufx_ofs, bufx_n);
322     memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
323     return result;
324 }
325
326
327 static int write_all(int fd, const void *buf, const size_t count)
328 {
329     size_t written = 0;
330     while (written < count)
331     {
332         const ssize_t rc = write(fd, buf + written, count - written);
333         if (rc == -1)
334             return -1;
335         written += rc;
336     }
337     return 0;
338 }
339
340
341 static inline int uadd(unsigned long long *dest,
342                        const unsigned long long x,
343                        const unsigned long long y)
344 {
345     return INT_ADD_OK(x, y, dest);
346 }
347
348
349 static PyObject *append_sparse_region(const int fd, unsigned long long n)
350 {
351     while (n)
352     {
353         off_t new_off;
354         if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
355             new_off = INT_MAX;
356         const off_t off = lseek(fd, new_off, SEEK_CUR);
357         if (off == (off_t) -1)
358             return PyErr_SetFromErrno(PyExc_IOError);
359         n -= new_off;
360     }
361     return NULL;
362 }
363
364
365 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
366                                      const int fd,
367                                      unsigned long long prev_pending,
368                                      const unsigned long long count)
369 {
370     // Add count additional sparse zeros to prev_pending and store the
371     // result in new_pending, or if the total won't fit in
372     // new_pending, write some of the zeros to fd sparsely, and store
373     // the remaining sum in new_pending.
374     if (!uadd(new_pending, prev_pending, count))
375     {
376         PyObject *err = append_sparse_region(fd, prev_pending);
377         if (err != NULL)
378             return err;
379         *new_pending = count;
380     }
381     return NULL;
382 }
383
384
385 static byte* find_not_zero(const byte * const start, const byte * const end)
386 {
387     // Return a pointer to first non-zero byte between start and end,
388     // or end if there isn't one.
389     assert(start <= end);
390     const unsigned char *cur = start;
391     while (cur < end && *cur == 0)
392         cur++;
393     return (byte *) cur;
394 }
395
396
397 static byte* find_trailing_zeros(const byte * const start,
398                                  const byte * const end)
399 {
400     // Return a pointer to the start of any trailing run of zeros, or
401     // end if there isn't one.
402     assert(start <= end);
403     if (start == end)
404         return (byte *) end;
405     const byte * cur = end;
406     while (cur > start && *--cur == 0) {}
407     if (*cur == 0)
408         return (byte *) cur;
409     else
410         return (byte *) (cur + 1);
411 }
412
413
414 static byte *find_non_sparse_end(const byte * const start,
415                                  const byte * const end,
416                                  const ptrdiff_t min_len)
417 {
418     // Return the first pointer to a min_len sparse block in [start,
419     // end) if there is one, otherwise a pointer to the start of any
420     // trailing run of zeros.  If there are no trailing zeros, return
421     // end.
422     if (start == end)
423         return (byte *) end;
424     assert(start < end);
425     assert(min_len);
426     // Probe in min_len jumps, searching backward from the jump
427     // destination for a non-zero byte.  If such a byte is found, move
428     // just past it and try again.
429     const byte *candidate = start;
430     // End of any run of zeros, starting at candidate, that we've already seen
431     const byte *end_of_known_zeros = candidate;
432     while (end - candidate >= min_len) // Handle all min_len candidate blocks
433     {
434         const byte * const probe_end = candidate + min_len;
435         const byte * const trailing_zeros =
436             find_trailing_zeros(end_of_known_zeros, probe_end);
437         if (trailing_zeros == probe_end)
438             end_of_known_zeros = candidate = probe_end;
439         else if (trailing_zeros == end_of_known_zeros)
440         {
441             assert(candidate >= start);
442             assert(candidate <= end);
443             assert(*candidate == 0);
444             return (byte *) candidate;
445         }
446         else
447         {
448             candidate = trailing_zeros;
449             end_of_known_zeros = probe_end;
450         }
451     }
452
453     if (candidate == end)
454         return (byte *) end;
455
456     // No min_len sparse run found, search backward from end
457     const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
458                                                             end);
459
460     if (trailing_zeros == end_of_known_zeros)
461     {
462         assert(candidate >= start);
463         assert(candidate < end);
464         assert(*candidate == 0);
465         assert(end - candidate < min_len);
466         return (byte *) candidate;
467     }
468
469     if (trailing_zeros == end)
470     {
471         assert(*(end - 1) != 0);
472         return (byte *) end;
473     }
474
475     assert(end - trailing_zeros < min_len);
476     assert(trailing_zeros >= start);
477     assert(trailing_zeros < end);
478     assert(*trailing_zeros == 0);
479     return (byte *) trailing_zeros;
480 }
481
482
483 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
484 {
485     int fd;
486     unsigned char *buf = NULL;
487     Py_ssize_t sbuf_len;
488     PyObject *py_min_sparse_len, *py_prev_sparse_len;
489     if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
490                           &fd, &buf, &sbuf_len,
491                           &py_min_sparse_len, &py_prev_sparse_len))
492         return NULL;
493     ptrdiff_t min_sparse_len;
494     unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
495     if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
496         return NULL;
497     if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
498         return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
499     if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
500         return NULL;
501     if (sbuf_len < 0)
502         return PyErr_Format(PyExc_ValueError, "negative bufer length");
503     if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
504         return PyErr_Format(PyExc_OverflowError, "buffer length too large");
505
506     const byte * block = buf; // Start of pending block
507     const byte * const end = buf + buf_len;
508     unsigned long long zeros = prev_sparse_len;
509     while (1)
510     {
511         assert(block <= end);
512         if (block == end)
513             return PyLong_FromUnsignedLongLong(zeros);
514
515         if (*block != 0)
516         {
517             // Look for the end of block, i.e. the next sparse run of
518             // at least min_sparse_len zeros, or the end of the
519             // buffer.
520             const byte * const probe = find_non_sparse_end(block + 1, end,
521                                                            min_sparse_len);
522             // Either at end of block, or end of non-sparse; write pending data
523             PyObject *err = append_sparse_region(fd, zeros);
524             if (err != NULL)
525                 return err;
526             int rc = write_all(fd, block, probe - block);
527             if (rc)
528                 return PyErr_SetFromErrno(PyExc_IOError);
529
530             if (end - probe < min_sparse_len)
531                 zeros = end - probe;
532             else
533                 zeros = min_sparse_len;
534             block = probe + zeros;
535         }
536         else // *block == 0
537         {
538             // Should be in the first loop iteration, a sparse run of
539             // zeros, or nearly at the end of the block (within
540             // min_sparse_len).
541             const byte * const zeros_end = find_not_zero(block, end);
542             PyObject *err = record_sparse_zeros(&zeros, fd,
543                                                 zeros, zeros_end - block);
544             if (err != NULL)
545                 return err;
546             assert(block <= zeros_end);
547             block = zeros_end;
548         }
549     }
550 }
551
552
553 static PyObject *selftest(PyObject *self, PyObject *args)
554 {
555     if (!PyArg_ParseTuple(args, ""))
556         return NULL;
557     
558     return Py_BuildValue("i", !bupsplit_selftest());
559 }
560
561
562 static PyObject *blobbits(PyObject *self, PyObject *args)
563 {
564     if (!PyArg_ParseTuple(args, ""))
565         return NULL;
566     return Py_BuildValue("i", BUP_BLOBBITS);
567 }
568
569
570 static PyObject *splitbuf(PyObject *self, PyObject *args)
571 {
572     // We stick to buffers in python 2 because they appear to be
573     // substantially smaller than memoryviews, and because
574     // zlib.compress() in python 2 can't accept a memoryview
575     // (cf. hashsplit.py).
576     int out = 0, bits = -1;
577     if (PY_MAJOR_VERSION > 2)
578     {
579         Py_buffer buf;
580         if (!PyArg_ParseTuple(args, "y*", &buf))
581             return NULL;
582         assert(buf.len <= INT_MAX);
583         out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
584         PyBuffer_Release(&buf);
585     }
586     else
587     {
588         unsigned char *buf = NULL;
589         Py_ssize_t len = 0;
590         if (!PyArg_ParseTuple(args, "t#", &buf, &len))
591             return NULL;
592         assert(len <= INT_MAX);
593         out = bupsplit_find_ofs(buf, (int) len, &bits);
594     }
595     if (out) assert(bits >= BUP_BLOBBITS);
596     return Py_BuildValue("ii", out, bits);
597 }
598
599
600 static PyObject *bitmatch(PyObject *self, PyObject *args)
601 {
602     unsigned char *buf1 = NULL, *buf2 = NULL;
603     Py_ssize_t len1 = 0, len2 = 0;
604     Py_ssize_t byte;
605     int bit;
606
607     if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
608         return NULL;
609     
610     bit = 0;
611     for (byte = 0; byte < len1 && byte < len2; byte++)
612     {
613         int b1 = buf1[byte], b2 = buf2[byte];
614         if (b1 != b2)
615         {
616             for (bit = 0; bit < 8; bit++)
617                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
618                     break;
619             break;
620         }
621     }
622     
623     unsigned long long result;
624     if (!INT_MULTIPLY_OK(byte, 8, &result)
625         || !INT_ADD_OK(result, bit, &result))
626     {
627         PyErr_Format(PyExc_OverflowError, "bitmatch bit count too large");
628         return NULL;
629     }
630     return PyLong_FromUnsignedLongLong(result);
631 }
632
633
634 static PyObject *firstword(PyObject *self, PyObject *args)
635 {
636     unsigned char *buf = NULL;
637     Py_ssize_t len = 0;
638     uint32_t v;
639
640     if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
641         return NULL;
642     
643     if (len < 4)
644         return NULL;
645     
646     v = ntohl(*(uint32_t *)buf);
647     return PyLong_FromUnsignedLong(v);
648 }
649
650
651 #define BLOOM2_HEADERLEN 16
652
653 static void to_bloom_address_bitmask4(const unsigned char *buf,
654         const int nbits, uint64_t *v, unsigned char *bitmask)
655 {
656     int bit;
657     uint32_t high;
658     uint64_t raw, mask;
659
660     memcpy(&high, buf, 4);
661     mask = (1<<nbits) - 1;
662     raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
663     bit = (raw >> (37-nbits)) & 0x7;
664     *v = (raw >> (40-nbits)) & mask;
665     *bitmask = 1 << bit;
666 }
667
668 static void to_bloom_address_bitmask5(const unsigned char *buf,
669         const int nbits, uint32_t *v, unsigned char *bitmask)
670 {
671     int bit;
672     uint32_t high;
673     uint32_t raw, mask;
674
675     memcpy(&high, buf, 4);
676     mask = (1<<nbits) - 1;
677     raw = ntohl(high);
678     bit = (raw >> (29-nbits)) & 0x7;
679     *v = (raw >> (32-nbits)) & mask;
680     *bitmask = 1 << bit;
681 }
682
683 #define BLOOM_SET_BIT(name, address, otype) \
684 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
685 {\
686     unsigned char bitmask;\
687     otype v;\
688     address(buf, nbits, &v, &bitmask);\
689     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
690 }
691 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
692 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
693
694
695 #define BLOOM_GET_BIT(name, address, otype) \
696 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
697 {\
698     unsigned char bitmask;\
699     otype v;\
700     address(buf, nbits, &v, &bitmask);\
701     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
702 }
703 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
704 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
705
706
707 static PyObject *bloom_add(PyObject *self, PyObject *args)
708 {
709     Py_buffer bloom, sha;
710     int nbits = 0, k = 0;
711     if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
712                           &bloom, &sha, &nbits, &k))
713         return NULL;
714
715     PyObject *result = NULL;
716
717     if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
718         goto clean_and_return;
719
720     if (k == 5)
721     {
722         if (nbits > 29)
723             goto clean_and_return;
724         unsigned char *cur = sha.buf;
725         unsigned char *end;
726         for (end = cur + sha.len; cur < end; cur += 20/k)
727             bloom_set_bit5(bloom.buf, cur, nbits);
728     }
729     else if (k == 4)
730     {
731         if (nbits > 37)
732             goto clean_and_return;
733         unsigned char *cur = sha.buf;
734         unsigned char *end = cur + sha.len;
735         for (; cur < end; cur += 20/k)
736             bloom_set_bit4(bloom.buf, cur, nbits);
737     }
738     else
739         goto clean_and_return;
740
741     result = Py_BuildValue("n", sha.len / 20);
742
743  clean_and_return:
744     PyBuffer_Release(&bloom);
745     PyBuffer_Release(&sha);
746     return result;
747 }
748
749 static PyObject *bloom_contains(PyObject *self, PyObject *args)
750 {
751     Py_buffer bloom;
752     unsigned char *sha = NULL;
753     Py_ssize_t len = 0;
754     int nbits = 0, k = 0;
755     if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
756                           &bloom, &sha, &len, &nbits, &k))
757         return NULL;
758
759     PyObject *result = NULL;
760
761     if (len != 20)
762         goto clean_and_return;
763
764     if (k == 5)
765     {
766         if (nbits > 29)
767             goto clean_and_return;
768         int steps;
769         unsigned char *end;
770         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
771             if (!bloom_get_bit5(bloom.buf, sha, nbits))
772             {
773                 result = Py_BuildValue("Oi", Py_None, steps);
774                 goto clean_and_return;
775             }
776     }
777     else if (k == 4)
778     {
779         if (nbits > 37)
780             goto clean_and_return;
781         int steps;
782         unsigned char *end;
783         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
784             if (!bloom_get_bit4(bloom.buf, sha, nbits))
785             {
786                 result = Py_BuildValue("Oi", Py_None, steps);
787                 goto clean_and_return;
788             }
789     }
790     else
791         goto clean_and_return;
792
793     result = Py_BuildValue("ii", 1, k);
794
795  clean_and_return:
796     PyBuffer_Release(&bloom);
797     return result;
798 }
799
800
801 static uint32_t _extract_bits(unsigned char *buf, int nbits)
802 {
803     uint32_t v, mask;
804
805     mask = (1<<nbits) - 1;
806     v = ntohl(*(uint32_t *)buf);
807     v = (v >> (32-nbits)) & mask;
808     return v;
809 }
810
811
812 static PyObject *extract_bits(PyObject *self, PyObject *args)
813 {
814     unsigned char *buf = NULL;
815     Py_ssize_t len = 0;
816     int nbits = 0;
817
818     if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
819         return NULL;
820     
821     if (len < 4)
822         return NULL;
823     
824     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
825 }
826
827
828 struct sha {
829     unsigned char bytes[20];
830 };
831
832 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
833 {
834     return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
835 }
836
837
838 struct idx {
839     unsigned char *map;
840     struct sha *cur;
841     struct sha *end;
842     uint32_t *cur_name;
843     Py_ssize_t bytes;
844     int name_base;
845 };
846
847 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
848 {
849     struct idx *idx;
850     Py_ssize_t low, mid, high;
851     int c = 0;
852
853     idx = idxs[*last_i];
854     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
855     {
856         idxs[*last_i] = NULL;
857         PyMem_Free(idx);
858         --*last_i;
859         return;
860     }
861     if (*last_i == 0)
862         return;
863
864     low = *last_i-1;
865     mid = *last_i;
866     high = 0;
867     while (low >= high)
868     {
869         mid = (low + high) / 2;
870         c = _cmp_sha(idx->cur, idxs[mid]->cur);
871         if (c < 0)
872             high = mid + 1;
873         else if (c > 0)
874             low = mid - 1;
875         else
876             break;
877     }
878     if (c < 0)
879         ++mid;
880     if (mid == *last_i)
881         return;
882     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
883     idxs[mid] = idx;
884 }
885
886
887 static uint32_t _get_idx_i(struct idx *idx)
888 {
889     if (idx->cur_name == NULL)
890         return idx->name_base;
891     return ntohl(*idx->cur_name) + idx->name_base;
892 }
893
894 #define MIDX4_HEADERLEN 12
895
896 static PyObject *merge_into(PyObject *self, PyObject *args)
897 {
898     struct sha *sha_ptr, *sha_start = NULL;
899     uint32_t *table_ptr, *name_ptr, *name_start;
900     int i;
901     unsigned int total;
902     uint32_t count, prefix;
903
904
905     Py_buffer fmap;
906     int bits;;
907     PyObject *py_total, *ilist = NULL;
908     if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
909                           &fmap, &bits, &py_total, &ilist))
910         return NULL;
911
912     PyObject *result = NULL;
913     struct idx **idxs = NULL;
914     Py_ssize_t num_i = 0;
915     int *idx_buf_init = NULL;
916     Py_buffer *idx_buf = NULL;
917
918     if (!bup_uint_from_py(&total, py_total, "total"))
919         goto clean_and_return;
920
921     num_i = PyList_Size(ilist);
922
923     if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
924         goto clean_and_return;
925     if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
926         goto clean_and_return;
927     if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
928         goto clean_and_return;
929
930     for (i = 0; i < num_i; i++)
931     {
932         long len, sha_ofs, name_map_ofs;
933         if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
934             goto clean_and_return;
935         PyObject *itup = PyList_GetItem(ilist, i);
936         if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
937                               &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
938                               &idxs[i]->name_base))
939             return NULL;
940         idx_buf_init[i] = 1;
941         idxs[i]->map = idx_buf[i].buf;
942         idxs[i]->bytes = idx_buf[i].len;
943         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
944         idxs[i]->end = &idxs[i]->cur[len];
945         if (name_map_ofs)
946             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
947         else
948             idxs[i]->cur_name = NULL;
949     }
950     table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
951     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
952     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
953
954     Py_ssize_t last_i = num_i - 1;
955     count = 0;
956     prefix = 0;
957     while (last_i >= 0)
958     {
959         struct idx *idx;
960         uint32_t new_prefix;
961         if (count % 102424 == 0 && get_state(self)->istty2)
962             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
963                     count*100.0/total, count, total);
964         idx = idxs[last_i];
965         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
966         while (prefix < new_prefix)
967             table_ptr[prefix++] = htonl(count);
968         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
969         *name_ptr++ = htonl(_get_idx_i(idx));
970         ++idx->cur;
971         if (idx->cur_name != NULL)
972             ++idx->cur_name;
973         _fix_idx_order(idxs, &last_i);
974         ++count;
975     }
976     while (prefix < ((uint32_t) 1 << bits))
977         table_ptr[prefix++] = htonl(count);
978     assert(count == total);
979     assert(prefix == ((uint32_t) 1 << bits));
980     assert(sha_ptr == sha_start+count);
981     assert(name_ptr == name_start+count);
982
983     result = PyLong_FromUnsignedLong(count);
984
985  clean_and_return:
986     if (idx_buf_init)
987     {
988         for (i = 0; i < num_i; i++)
989             if (idx_buf_init[i])
990                 PyBuffer_Release(&(idx_buf[i]));
991         free(idx_buf_init);
992         free(idx_buf);
993     }
994     if (idxs)
995     {
996         for (i = 0; i < num_i; i++)
997             free(idxs[i]);
998         free(idxs);
999     }
1000     PyBuffer_Release(&fmap);
1001     return result;
1002 }
1003
1004 #define FAN_ENTRIES 256
1005
1006 static PyObject *write_idx(PyObject *self, PyObject *args)
1007 {
1008     char *filename = NULL;
1009     PyObject *py_total, *idx = NULL;
1010     PyObject *part;
1011     unsigned int total = 0;
1012     uint32_t count;
1013     int i;
1014     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1015     uint64_t *ofs64_ptr;
1016     struct sha *sha_ptr;
1017
1018     Py_buffer fmap;
1019     if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1020                           &filename, &fmap, &idx, &py_total))
1021         return NULL;
1022
1023     PyObject *result = NULL;
1024
1025     if (!bup_uint_from_py(&total, py_total, "total"))
1026         goto clean_and_return;
1027
1028     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1029     {
1030         result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1031                                FAN_ENTRIES);
1032         goto clean_and_return;
1033     }
1034
1035     const char idx_header[] = "\377tOc\0\0\0\002";
1036     memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1037
1038     fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1039     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1040     crc_ptr = (uint32_t *)&sha_ptr[total];
1041     ofs_ptr = (uint32_t *)&crc_ptr[total];
1042     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1043
1044     count = 0;
1045     uint32_t ofs64_count = 0;
1046     for (i = 0; i < FAN_ENTRIES; ++i)
1047     {
1048         part = PyList_GET_ITEM(idx, i);
1049         PyList_Sort(part);
1050         uint32_t plen;
1051         if (!INTEGRAL_ASSIGNMENT_FITS(&plen, PyList_GET_SIZE(part))
1052             || UINT32_MAX - count < plen) {
1053             PyErr_Format(PyExc_OverflowError, "too many objects in index part");
1054             goto clean_and_return;
1055         }
1056         count += plen;
1057         *fan_ptr++ = htonl(count);
1058         uint32_t j;
1059         for (j = 0; j < plen; ++j)
1060         {
1061             unsigned char *sha = NULL;
1062             Py_ssize_t sha_len = 0;
1063             PyObject *crc_py, *ofs_py;
1064             unsigned int crc;
1065             unsigned PY_LONG_LONG ofs_ull;
1066             uint64_t ofs;
1067             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1068                                   &sha, &sha_len, &crc_py, &ofs_py))
1069                 goto clean_and_return;
1070             if(!bup_uint_from_py(&crc, crc_py, "crc"))
1071                 goto clean_and_return;
1072             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1073                 goto clean_and_return;
1074             assert(crc <= UINT32_MAX);
1075             assert(ofs_ull <= UINT64_MAX);
1076             ofs = ofs_ull;
1077             if (sha_len != sizeof(struct sha))
1078                 goto clean_and_return;
1079             memcpy(sha_ptr++, sha, sizeof(struct sha));
1080             *crc_ptr++ = htonl(crc);
1081             if (ofs > 0x7fffffff)
1082             {
1083                 *ofs64_ptr++ = htonll(ofs);
1084                 ofs = 0x80000000 | ofs64_count++;
1085             }
1086             *ofs_ptr++ = htonl((uint32_t)ofs);
1087         }
1088     }
1089
1090     int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1091     if (rc != 0)
1092     {
1093         result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1094         goto clean_and_return;
1095     }
1096
1097     result = PyLong_FromUnsignedLong(count);
1098
1099  clean_and_return:
1100     PyBuffer_Release(&fmap);
1101     return result;
1102 }
1103
1104
1105 // I would have made this a lower-level function that just fills in a buffer
1106 // with random values, and then written those values from python.  But that's
1107 // about 20% slower in my tests, and since we typically generate random
1108 // numbers for benchmarking other parts of bup, any slowness in generating
1109 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
1110 // pseudorandom bytes much except for this anyway.
1111 static PyObject *write_random(PyObject *self, PyObject *args)
1112 {
1113     uint32_t buf[1024/4];
1114     int fd = -1, seed = 0, verbose = 0;
1115     ssize_t ret;
1116     long long len = 0, kbytes = 0, written = 0;
1117
1118     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1119         return NULL;
1120     
1121     srandom(seed);
1122     
1123     for (kbytes = 0; kbytes < len/1024; kbytes++)
1124     {
1125         unsigned i;
1126         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1127             buf[i] = (uint32_t) random();
1128         ret = write(fd, buf, sizeof(buf));
1129         if (ret < 0)
1130             ret = 0;
1131         written += ret;
1132         if (ret < (int)sizeof(buf))
1133             break;
1134         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1135             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1136     }
1137     
1138     // handle non-multiples of 1024
1139     if (len % 1024)
1140     {
1141         unsigned i;
1142         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1143             buf[i] = (uint32_t) random();
1144         ret = write(fd, buf, len % 1024);
1145         if (ret < 0)
1146             ret = 0;
1147         written += ret;
1148     }
1149     
1150     if (kbytes/1024 > 0)
1151         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1152     return Py_BuildValue("L", written);
1153 }
1154
1155
1156 static PyObject *random_sha(PyObject *self, PyObject *args)
1157 {
1158     static int seeded = 0;
1159     uint32_t shabuf[20/4];
1160     int i;
1161     
1162     if (!seeded)
1163     {
1164         assert(sizeof(shabuf) == 20);
1165         srandom((unsigned int) time(NULL));
1166         seeded = 1;
1167     }
1168     
1169     if (!PyArg_ParseTuple(args, ""))
1170         return NULL;
1171     
1172     memset(shabuf, 0, sizeof(shabuf));
1173     for (i=0; i < 20/4; i++)
1174         shabuf[i] = (uint32_t) random();
1175     return Py_BuildValue(rbuf_argf, shabuf, 20);
1176 }
1177
1178
1179 static int _open_noatime(const char *filename, int attrs)
1180 {
1181     int attrs_noatime, fd;
1182     attrs |= O_RDONLY;
1183 #ifdef O_NOFOLLOW
1184     attrs |= O_NOFOLLOW;
1185 #endif
1186 #ifdef O_LARGEFILE
1187     attrs |= O_LARGEFILE;
1188 #endif
1189     attrs_noatime = attrs;
1190 #ifdef O_NOATIME
1191     attrs_noatime |= O_NOATIME;
1192 #endif
1193     fd = open(filename, attrs_noatime);
1194     if (fd < 0 && errno == EPERM)
1195     {
1196         // older Linux kernels would return EPERM if you used O_NOATIME
1197         // and weren't the file's owner.  This pointless restriction was
1198         // relaxed eventually, but we have to handle it anyway.
1199         // (VERY old kernels didn't recognized O_NOATIME, but they would
1200         // just harmlessly ignore it, so this branch won't trigger)
1201         fd = open(filename, attrs);
1202     }
1203     return fd;
1204 }
1205
1206
1207 static PyObject *open_noatime(PyObject *self, PyObject *args)
1208 {
1209     char *filename = NULL;
1210     int fd;
1211     if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1212         return NULL;
1213     fd = _open_noatime(filename, 0);
1214     if (fd < 0)
1215         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1216     return Py_BuildValue("i", fd);
1217 }
1218
1219
1220 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1221 {
1222     int fd = -1;
1223     long long llofs, lllen = 0;
1224     if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1225         return NULL;
1226     off_t ofs, len;
1227     if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1228         return PyErr_Format(PyExc_OverflowError,
1229                             "fadvise offset overflows off_t");
1230     if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1231         return PyErr_Format(PyExc_OverflowError,
1232                             "fadvise length overflows off_t");
1233 #ifdef POSIX_FADV_DONTNEED
1234     posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1235 #endif    
1236     return Py_BuildValue("");
1237 }
1238
1239
1240 // Currently the Linux kernel and FUSE disagree over the type for
1241 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS.  The kernel actually uses int,
1242 // but FUSE chose long (matching the declaration in linux/fs.h).  So
1243 // if you use int, and then traverse a FUSE filesystem, you may
1244 // corrupt the stack.  But if you use long, then you may get invalid
1245 // results on big-endian systems.
1246 //
1247 // For now, we just use long, and then disable Linux attrs entirely
1248 // (with a warning) in helpers.py on systems that are affected.
1249
1250 #ifdef BUP_HAVE_FILE_ATTRS
1251 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1252 {
1253     int rc;
1254     unsigned long attr;
1255     char *path;
1256     int fd;
1257
1258     if (!PyArg_ParseTuple(args, cstr_argf, &path))
1259         return NULL;
1260
1261     fd = _open_noatime(path, O_NONBLOCK);
1262     if (fd == -1)
1263         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1264
1265     attr = 0;  // Handle int/long mismatch (see above)
1266     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1267     if (rc == -1)
1268     {
1269         close(fd);
1270         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1271     }
1272     close(fd);
1273     assert(attr <= UINT_MAX);  // Kernel type is actually int
1274     return PyLong_FromUnsignedLong(attr);
1275 }
1276 #endif /* def BUP_HAVE_FILE_ATTRS */
1277
1278
1279
1280 #ifdef BUP_HAVE_FILE_ATTRS
1281 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1282 {
1283     int rc;
1284     unsigned long orig_attr;
1285     unsigned int attr;
1286     char *path;
1287     PyObject *py_attr;
1288     int fd;
1289
1290     if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1291         return NULL;
1292
1293     if (!bup_uint_from_py(&attr, py_attr, "attr"))
1294         return NULL;
1295
1296     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1297     if (fd == -1)
1298         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1299
1300     // Restrict attr to modifiable flags acdeijstuADST -- see
1301     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
1302     // in pf.c flags_array[].
1303     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1304     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1305     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1306     | FS_TOPDIR_FL | FS_NOCOW_FL;
1307
1308     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1309     orig_attr = 0; // Handle int/long mismatch (see above)
1310     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1311     if (rc == -1)
1312     {
1313         close(fd);
1314         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1315     }
1316     assert(orig_attr <= UINT_MAX);  // Kernel type is actually int
1317     attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1318
1319     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1320     if (rc == -1)
1321     {
1322         close(fd);
1323         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1324     }
1325
1326     close(fd);
1327     return Py_BuildValue("O", Py_None);
1328 }
1329 #endif /* def BUP_HAVE_FILE_ATTRS */
1330
1331
1332 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
1333 #ifndef HAVE_UTIMENSAT
1334 #ifndef HAVE_UTIMES
1335 #error "cannot find utimensat or utimes()"
1336 #endif
1337 #ifndef HAVE_LUTIMES
1338 #error "cannot find utimensat or lutimes()"
1339 #endif
1340 #endif
1341 #endif // defined BUP_USE_PYTHON_UTIME
1342
1343 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1344     ({                                                     \
1345         int result = 0;                                                 \
1346         *(overflow) = 0;                                                \
1347         const long long lltmp = PyLong_AsLongLong(pylong);              \
1348         if (lltmp == -1 && PyErr_Occurred())                            \
1349         {                                                               \
1350             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
1351             {                                                           \
1352                 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1353                 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1354                 {                                                       \
1355                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
1356                     {                                                   \
1357                         PyErr_Clear();                                  \
1358                         *(overflow) = 1;                                \
1359                     }                                                   \
1360                 }                                                       \
1361                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
1362                     result = 1;                                         \
1363                 else                                                    \
1364                     *(overflow) = 1;                                    \
1365             }                                                           \
1366         }                                                               \
1367         else                                                            \
1368         {                                                               \
1369             if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
1370                 result = 1;                                             \
1371             else                                                        \
1372                 *(overflow) = 1;                                        \
1373         }                                                               \
1374         result;                                                         \
1375         })
1376
1377
1378 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
1379 #ifdef HAVE_UTIMENSAT
1380
1381 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1382 {
1383     int rc;
1384     int fd, flag;
1385     char *path;
1386     PyObject *access_py, *modification_py;
1387     struct timespec ts[2];
1388
1389     if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1390                           &fd,
1391                           &path,
1392                           &access_py, &(ts[0].tv_nsec),
1393                           &modification_py, &(ts[1].tv_nsec),
1394                           &flag))
1395         return NULL;
1396
1397     int overflow;
1398     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1399     {
1400         if (overflow)
1401             PyErr_SetString(PyExc_ValueError,
1402                             "unable to convert access time seconds for utimensat");
1403         return NULL;
1404     }
1405     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1406     {
1407         if (overflow)
1408             PyErr_SetString(PyExc_ValueError,
1409                             "unable to convert modification time seconds for utimensat");
1410         return NULL;
1411     }
1412     rc = utimensat(fd, path, ts, flag);
1413     if (rc != 0)
1414         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1415
1416     return Py_BuildValue("O", Py_None);
1417 }
1418
1419 #endif /* def HAVE_UTIMENSAT */
1420
1421
1422 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1423
1424 static int bup_parse_xutimes_args(char **path,
1425                                   struct timeval tv[2],
1426                                   PyObject *args)
1427 {
1428     PyObject *access_py, *modification_py;
1429     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1430
1431     if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1432                           path,
1433                           &access_py, &access_us,
1434                           &modification_py, &modification_us))
1435         return 0;
1436
1437     int overflow;
1438     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1439     {
1440         if (overflow)
1441             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1442         return 0;
1443     }
1444     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1445     {
1446         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1447         return 0;
1448     }
1449     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1450     {
1451         if (overflow)
1452             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1453         return 0;
1454     }
1455     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1456     {
1457         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1458         return 0;
1459     }
1460     return 1;
1461 }
1462
1463 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1464
1465
1466 #ifdef HAVE_UTIMES
1467 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1468 {
1469     char *path;
1470     struct timeval tv[2];
1471     if (!bup_parse_xutimes_args(&path, tv, args))
1472         return NULL;
1473     int rc = utimes(path, tv);
1474     if (rc != 0)
1475         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1476     return Py_BuildValue("O", Py_None);
1477 }
1478 #endif /* def HAVE_UTIMES */
1479
1480
1481 #ifdef HAVE_LUTIMES
1482 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1483 {
1484     char *path;
1485     struct timeval tv[2];
1486     if (!bup_parse_xutimes_args(&path, tv, args))
1487         return NULL;
1488     int rc = lutimes(path, tv);
1489     if (rc != 0)
1490         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1491
1492     return Py_BuildValue("O", Py_None);
1493 }
1494 #endif /* def HAVE_LUTIMES */
1495
1496 #endif // defined BUP_USE_PYTHON_UTIME
1497
1498
1499 #ifdef HAVE_STAT_ST_ATIM
1500 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1501 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1502 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1503 #elif defined HAVE_STAT_ST_ATIMENSEC
1504 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1505 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1506 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1507 #else
1508 # define BUP_STAT_ATIME_NS(st) 0
1509 # define BUP_STAT_MTIME_NS(st) 0
1510 # define BUP_STAT_CTIME_NS(st) 0
1511 #endif
1512
1513
1514 static PyObject *stat_struct_to_py(const struct stat *st,
1515                                    const char *filename,
1516                                    int fd)
1517 {
1518     // We can check the known (via POSIX) signed and unsigned types at
1519     // compile time, but not (easily) the unspecified types, so handle
1520     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1521     // long.
1522     return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1523                          INTEGER_TO_PY(st->st_mode),
1524                          (unsigned PY_LONG_LONG) st->st_ino,
1525                          INTEGER_TO_PY(st->st_dev),
1526                          INTEGER_TO_PY(st->st_nlink),
1527                          INTEGER_TO_PY(st->st_uid),
1528                          INTEGER_TO_PY(st->st_gid),
1529                          INTEGER_TO_PY(st->st_rdev),
1530                          (PY_LONG_LONG) st->st_size,
1531                          INTEGER_TO_PY(st->st_atime),
1532                          (long) BUP_STAT_ATIME_NS(st),
1533                          INTEGER_TO_PY(st->st_mtime),
1534                          (long) BUP_STAT_MTIME_NS(st),
1535                          INTEGER_TO_PY(st->st_ctime),
1536                          (long) BUP_STAT_CTIME_NS(st));
1537 }
1538
1539
1540 static PyObject *bup_stat(PyObject *self, PyObject *args)
1541 {
1542     int rc;
1543     char *filename;
1544
1545     if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1546         return NULL;
1547
1548     struct stat st;
1549     rc = stat(filename, &st);
1550     if (rc != 0)
1551         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1552     return stat_struct_to_py(&st, filename, 0);
1553 }
1554
1555
1556 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1557 {
1558     int rc;
1559     char *filename;
1560
1561     if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1562         return NULL;
1563
1564     struct stat st;
1565     rc = lstat(filename, &st);
1566     if (rc != 0)
1567         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1568     return stat_struct_to_py(&st, filename, 0);
1569 }
1570
1571
1572 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1573 {
1574     int rc, fd;
1575
1576     if (!PyArg_ParseTuple(args, "i", &fd))
1577         return NULL;
1578
1579     struct stat st;
1580     rc = fstat(fd, &st);
1581     if (rc != 0)
1582         return PyErr_SetFromErrno(PyExc_OSError);
1583     return stat_struct_to_py(&st, NULL, fd);
1584 }
1585
1586
1587 #ifdef HAVE_TM_TM_GMTOFF
1588 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1589 {
1590     long long lltime;
1591     time_t ttime;
1592     if (!PyArg_ParseTuple(args, "L", &lltime))
1593         return NULL;
1594     if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1595         return PyErr_Format(PyExc_OverflowError, "time value too large");
1596
1597     struct tm tm;
1598     tzset();
1599     if(localtime_r(&ttime, &tm) == NULL)
1600         return PyErr_SetFromErrno(PyExc_OSError);
1601
1602     // Match the Python struct_time values.
1603     return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1604                          1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1605                          tm.tm_hour, tm.tm_min, tm.tm_sec,
1606                          tm.tm_wday, tm.tm_yday + 1,
1607                          tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1608 }
1609 #endif /* def HAVE_TM_TM_GMTOFF */
1610
1611
1612 #ifdef BUP_MINCORE_BUF_TYPE
1613 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1614 {
1615     Py_buffer src, dest;
1616     PyObject *py_src_n, *py_src_off, *py_dest_off;
1617
1618     if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1619                           &src, &py_src_n, &py_src_off,
1620                           &dest, &py_dest_off))
1621         return NULL;
1622
1623     PyObject *result = NULL;
1624
1625     unsigned long long src_n, src_off, dest_off;
1626     if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1627           && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1628           && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1629         goto clean_and_return;
1630
1631     unsigned long long src_region_end;
1632     if (!uadd(&src_region_end, src_off, src_n)) {
1633         result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1634         goto clean_and_return;
1635     }
1636     assert(src.len >= 0);
1637     if (src_region_end > (unsigned long long) src.len) {
1638         result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1639         goto clean_and_return;
1640     }
1641
1642     unsigned long long dest_size;
1643     if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1644         result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1645         goto clean_and_return;
1646     }
1647     if (dest_off > dest_size) {
1648         result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1649         goto clean_and_return;
1650     }
1651
1652     size_t length;
1653     if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1654         result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1655         goto clean_and_return;
1656     }
1657     int rc = mincore((void *)(src.buf + src_off), length,
1658                      (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1659     if (rc != 0) {
1660         result = PyErr_SetFromErrno(PyExc_OSError);
1661         goto clean_and_return;
1662     }
1663     result = Py_BuildValue("O", Py_None);
1664
1665  clean_and_return:
1666     PyBuffer_Release(&src);
1667     PyBuffer_Release(&dest);
1668     return result;
1669 }
1670 #endif /* def BUP_MINCORE_BUF_TYPE */
1671
1672 static unsigned int vuint_encode(long long val, char *buf)
1673 {
1674     unsigned int len = 0;
1675
1676     if (val < 0) {
1677         PyErr_SetString(PyExc_Exception, "vuints must not be negative");
1678         return 0;
1679     }
1680
1681     do {
1682         buf[len] = val & 0x7f;
1683
1684         val >>= 7;
1685         if (val)
1686             buf[len] |= 0x80;
1687
1688         len++;
1689     } while (val);
1690
1691     return len;
1692 }
1693
1694 static unsigned int vint_encode(long long val, char *buf)
1695 {
1696     unsigned int len = 1;
1697     char sign = 0;
1698
1699     if (val < 0) {
1700         sign = 0x40;
1701         val = -val;
1702     }
1703
1704     buf[0] = (val & 0x3f) | sign;
1705     val >>= 6;
1706     if (val)
1707         buf[0] |= 0x80;
1708
1709     while (val) {
1710         buf[len] = val & 0x7f;
1711         val >>= 7;
1712         if (val)
1713             buf[len] |= 0x80;
1714         len++;
1715     }
1716
1717     return len;
1718 }
1719
1720 static PyObject *bup_vuint_encode(PyObject *self, PyObject *args)
1721 {
1722     long long val;
1723     // size the buffer appropriately - need 8 bits to encode each 7
1724     char buf[(sizeof(val) + 1) / 7 * 8];
1725
1726     if (!PyArg_ParseTuple(args, "L", &val))
1727         return NULL;
1728
1729     unsigned int len = vuint_encode(val, buf);
1730     if (!len)
1731         return NULL;
1732
1733     return PyBytes_FromStringAndSize(buf, len);
1734 }
1735
1736 static PyObject *bup_vint_encode(PyObject *self, PyObject *args)
1737 {
1738     long long val;
1739     // size the buffer appropriately - need 8 bits to encode each 7
1740     char buf[(sizeof(val) + 1) / 7 * 8];
1741
1742     if (!PyArg_ParseTuple(args, "L", &val))
1743         return NULL;
1744
1745     return PyBytes_FromStringAndSize(buf, vint_encode(val, buf));
1746 }
1747
1748 static PyObject *tuple_from_cstrs(char **cstrs)
1749 {
1750     // Assumes list is null terminated
1751     size_t n = 0;
1752     while(cstrs[n] != NULL)
1753         n++;
1754
1755     Py_ssize_t sn;
1756     if (!INTEGRAL_ASSIGNMENT_FITS(&sn, n))
1757         return PyErr_Format(PyExc_OverflowError, "string array too large");
1758
1759     PyObject *result = PyTuple_New(sn);
1760     Py_ssize_t i = 0;
1761     for (i = 0; i < sn; i++)
1762     {
1763         PyObject *gname = Py_BuildValue(cstr_argf, cstrs[i]);
1764         if (gname == NULL)
1765         {
1766             Py_DECREF(result);
1767             return NULL;
1768         }
1769         PyTuple_SET_ITEM(result, i, gname);
1770     }
1771     return result;
1772 }
1773
1774 static PyObject *appropriate_errno_ex(void)
1775 {
1776     switch (errno) {
1777     case ENOMEM:
1778         return PyErr_NoMemory();
1779     case EIO:
1780     case EMFILE:
1781     case ENFILE:
1782         // In 3.3 IOError was merged into OSError.
1783         return PyErr_SetFromErrno(PyExc_IOError);
1784     default:
1785         return PyErr_SetFromErrno(PyExc_OSError);
1786     }
1787 }
1788
1789
1790 static PyObject *pwd_struct_to_py(const struct passwd *pwd)
1791 {
1792     // We can check the known (via POSIX) signed and unsigned types at
1793     // compile time, but not (easily) the unspecified types, so handle
1794     // those via INTEGER_TO_PY().
1795     if (pwd == NULL)
1796         Py_RETURN_NONE;
1797     return Py_BuildValue(cstr_argf cstr_argf "OO"
1798                          cstr_argf cstr_argf cstr_argf,
1799                          pwd->pw_name,
1800                          pwd->pw_passwd,
1801                          INTEGER_TO_PY(pwd->pw_uid),
1802                          INTEGER_TO_PY(pwd->pw_gid),
1803                          pwd->pw_gecos,
1804                          pwd->pw_dir,
1805                          pwd->pw_shell);
1806 }
1807
1808 static PyObject *bup_getpwuid(PyObject *self, PyObject *args)
1809 {
1810     unsigned long long py_uid;
1811     if (!PyArg_ParseTuple(args, "K", &py_uid))
1812         return NULL;
1813     uid_t uid;
1814     if (!INTEGRAL_ASSIGNMENT_FITS(&uid, py_uid))
1815         return PyErr_Format(PyExc_OverflowError, "uid too large for uid_t");
1816
1817     errno = 0;
1818     struct passwd *pwd = getpwuid(uid);
1819     if (!pwd && errno)
1820         return appropriate_errno_ex();
1821     return pwd_struct_to_py(pwd);
1822 }
1823
1824 static PyObject *bup_getpwnam(PyObject *self, PyObject *args)
1825 {
1826     PyObject *py_name;
1827     if (!PyArg_ParseTuple(args, "S", &py_name))
1828         return NULL;
1829
1830     char *name = PyBytes_AS_STRING(py_name);
1831     errno = 0;
1832     struct passwd *pwd = getpwnam(name);
1833     if (!pwd && errno)
1834         return appropriate_errno_ex();
1835     return pwd_struct_to_py(pwd);
1836 }
1837
1838 static PyObject *grp_struct_to_py(const struct group *grp)
1839 {
1840     // We can check the known (via POSIX) signed and unsigned types at
1841     // compile time, but not (easily) the unspecified types, so handle
1842     // those via INTEGER_TO_PY().
1843     if (grp == NULL)
1844         Py_RETURN_NONE;
1845
1846     PyObject *members = tuple_from_cstrs(grp->gr_mem);
1847     if (members == NULL)
1848         return NULL;
1849     return Py_BuildValue(cstr_argf cstr_argf "OO",
1850                          grp->gr_name,
1851                          grp->gr_passwd,
1852                          INTEGER_TO_PY(grp->gr_gid),
1853                          members);
1854 }
1855
1856 static PyObject *bup_getgrgid(PyObject *self, PyObject *args)
1857 {
1858     unsigned long long py_gid;
1859     if (!PyArg_ParseTuple(args, "K", &py_gid))
1860         return NULL;
1861     gid_t gid;
1862     if (!INTEGRAL_ASSIGNMENT_FITS(&gid, py_gid))
1863         return PyErr_Format(PyExc_OverflowError, "gid too large for gid_t");
1864
1865     errno = 0;
1866     struct group *grp = getgrgid(gid);
1867     if (!grp && errno)
1868         return appropriate_errno_ex();
1869     return grp_struct_to_py(grp);
1870 }
1871
1872 static PyObject *bup_getgrnam(PyObject *self, PyObject *args)
1873 {
1874     PyObject *py_name;
1875     if (!PyArg_ParseTuple(args, "S", &py_name))
1876         return NULL;
1877
1878     char *name = PyBytes_AS_STRING(py_name);
1879     errno = 0;
1880     struct group *grp = getgrnam(name);
1881     if (!grp && errno)
1882         return appropriate_errno_ex();
1883     return grp_struct_to_py(grp);
1884 }
1885
1886
1887 static PyObject *bup_gethostname(PyObject *mod, PyObject *ignore)
1888 {
1889 #ifdef HOST_NAME_MAX
1890     char buf[HOST_NAME_MAX + 1] = {};
1891 #else
1892     /* 'SUSv2 guarantees that "Host names are limited to 255 bytes".' */
1893     char buf[256] = {};
1894 #endif
1895
1896     if (gethostname(buf, sizeof(buf) - 1))
1897         return PyErr_SetFromErrno(PyExc_IOError);
1898     return PyBytes_FromString(buf);
1899 }
1900
1901
1902 #ifdef BUP_HAVE_READLINE
1903
1904 static char *cstr_from_bytes(PyObject *bytes)
1905 {
1906     char *buf;
1907     Py_ssize_t length;
1908     int rc = PyBytes_AsStringAndSize(bytes, &buf, &length);
1909     if (rc == -1)
1910         return NULL;
1911     size_t c_len;
1912     if (!INT_ADD_OK(length, 1, &c_len)) {
1913         PyErr_Format(PyExc_OverflowError,
1914                      "Cannot convert ssize_t sized bytes object (%zd) to C string",
1915                      length);
1916         return NULL;
1917     }
1918     char *result = checked_malloc(c_len, sizeof(char));
1919     if (!result)
1920         return NULL;
1921     memcpy(result, buf, length);
1922     result[length] = 0;
1923     return result;
1924 }
1925
1926 static char **cstrs_from_seq(PyObject *seq)
1927 {
1928     char **result = NULL;
1929     seq = PySequence_Fast(seq, "Cannot convert sequence items to C strings");
1930     if (!seq)
1931         return NULL;
1932
1933     const Py_ssize_t len = PySequence_Fast_GET_SIZE(seq);
1934     if (len > PY_SSIZE_T_MAX - 1) {
1935         PyErr_Format(PyExc_OverflowError,
1936                      "Sequence length %zd too large for conversion to C array",
1937                      len);
1938         goto finish;
1939     }
1940     result = checked_malloc(len + 1, sizeof(char *));
1941     if (!result)
1942         goto finish;
1943     Py_ssize_t i = 0;
1944     for (i = 0; i < len; i++)
1945     {
1946         PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
1947         if (!item)
1948             goto abandon_result;
1949         result[i] = cstr_from_bytes(item);
1950         if (!result[i]) {
1951             i--;
1952             goto abandon_result;
1953         }
1954     }
1955     result[len] = NULL;
1956     goto finish;
1957
1958  abandon_result:
1959     if (result) {
1960         for (; i > 0; i--)
1961             free(result[i]);
1962         free(result);
1963         result = NULL;
1964     }
1965  finish:
1966     Py_DECREF(seq);
1967     return result;
1968 }
1969
1970 static char* our_word_break_chars = NULL;
1971
1972 static PyObject *
1973 bup_set_completer_word_break_characters(PyObject *self, PyObject *args)
1974 {
1975     char *bytes;
1976     if (!PyArg_ParseTuple(args, cstr_argf, &bytes))
1977         return NULL;
1978     char *prev = our_word_break_chars;
1979     char *next = strdup(bytes);
1980     if (!next)
1981         return PyErr_NoMemory();
1982     our_word_break_chars = next;
1983     rl_completer_word_break_characters = next;
1984     if (prev)
1985         free(prev);
1986     Py_RETURN_NONE;
1987 }
1988
1989 static PyObject *
1990 bup_get_completer_word_break_characters(PyObject *self, PyObject *args)
1991 {
1992     return PyBytes_FromString(rl_completer_word_break_characters);
1993 }
1994
1995 static PyObject *bup_get_line_buffer(PyObject *self, PyObject *args)
1996 {
1997     return PyBytes_FromString(rl_line_buffer);
1998 }
1999
2000 static PyObject *
2001 bup_parse_and_bind(PyObject *self, PyObject *args)
2002 {
2003     char *bytes;
2004     if (!PyArg_ParseTuple(args, cstr_argf ":parse_and_bind", &bytes))
2005         return NULL;
2006     char *tmp = strdup(bytes); // Because it may modify the arg
2007     if (!tmp)
2008         return PyErr_NoMemory();
2009     int rc = rl_parse_and_bind(tmp);
2010     free(tmp);
2011     if (rc != 0)
2012         return PyErr_Format(PyExc_OSError,
2013                             "system rl_parse_and_bind failed (%d)", rc);
2014     Py_RETURN_NONE;
2015 }
2016
2017
2018 static PyObject *py_on_attempted_completion;
2019 static char **prev_completions;
2020
2021 static char **on_attempted_completion(const char *text, int start, int end)
2022 {
2023     if (!py_on_attempted_completion)
2024         return NULL;
2025
2026     char **result = NULL;
2027     PyObject *py_result = PyObject_CallFunction(py_on_attempted_completion,
2028                                                 cstr_argf "ii",
2029                                                 text, start, end);
2030     if (!py_result)
2031         return NULL;
2032     if (py_result != Py_None) {
2033         result = cstrs_from_seq(py_result);
2034         free(prev_completions);
2035         prev_completions = result;
2036     }
2037     Py_DECREF(py_result);
2038     return result;
2039 }
2040
2041 static PyObject *
2042 bup_set_attempted_completion_function(PyObject *self, PyObject *args)
2043 {
2044     PyObject *completer;
2045     if (!PyArg_ParseTuple(args, "O", &completer))
2046         return NULL;
2047
2048     PyObject *prev = py_on_attempted_completion;
2049     if (completer == Py_None)
2050     {
2051         py_on_attempted_completion = NULL;
2052         rl_attempted_completion_function = NULL;
2053     } else {
2054         py_on_attempted_completion = completer;
2055         rl_attempted_completion_function = on_attempted_completion;
2056         Py_INCREF(completer);
2057     }
2058     Py_XDECREF(prev);
2059     Py_RETURN_NONE;
2060 }
2061
2062
2063 static PyObject *py_on_completion_entry;
2064
2065 static char *on_completion_entry(const char *text, int state)
2066 {
2067     if (!py_on_completion_entry)
2068         return NULL;
2069
2070     PyObject *py_result = PyObject_CallFunction(py_on_completion_entry,
2071                                                 cstr_argf "i", text, state);
2072     if (!py_result)
2073         return NULL;
2074     char *result = (py_result == Py_None) ? NULL : cstr_from_bytes(py_result);
2075     Py_DECREF(py_result);
2076     return result;
2077 }
2078
2079 static PyObject *
2080 bup_set_completion_entry_function(PyObject *self, PyObject *args)
2081 {
2082     PyObject *completer;
2083     if (!PyArg_ParseTuple(args, "O", &completer))
2084         return NULL;
2085
2086     PyObject *prev = py_on_completion_entry;
2087     if (completer == Py_None) {
2088         py_on_completion_entry = NULL;
2089         rl_completion_entry_function = NULL;
2090     } else {
2091         py_on_completion_entry = completer;
2092         rl_completion_entry_function = on_completion_entry;
2093         Py_INCREF(completer);
2094     }
2095     Py_XDECREF(prev);
2096     Py_RETURN_NONE;
2097 }
2098
2099 static PyObject *
2100 bup_readline(PyObject *self, PyObject *args)
2101 {
2102     char *prompt;
2103     if (!PyArg_ParseTuple(args, cstr_argf, &prompt))
2104         return NULL;
2105     char *line = readline(prompt);
2106     if (!line)
2107         return PyErr_Format(PyExc_EOFError, "readline EOF");
2108     PyObject *result = PyBytes_FromString(line);
2109     free(line);
2110     return result;
2111 }
2112
2113 #endif // defined BUP_HAVE_READLINE
2114
2115 #if defined(HAVE_SYS_ACL_H) && \
2116     defined(HAVE_ACL_LIBACL_H) && \
2117     defined(HAVE_ACL_EXTENDED_FILE) && \
2118     defined(HAVE_ACL_GET_FILE) && \
2119     defined(HAVE_ACL_TO_ANY_TEXT) && \
2120     defined(HAVE_ACL_FROM_TEXT) && \
2121     defined(HAVE_ACL_SET_FILE)
2122 #define ACL_SUPPORT 1
2123 #include <sys/acl.h>
2124 #include <acl/libacl.h>
2125
2126 // Returns
2127 //   0 for success
2128 //  -1 for errors, with python exception set
2129 //  -2 for ignored errors (not supported)
2130 static int bup_read_acl_to_text(const char *name, acl_type_t type,
2131                                 char **txt, char **num)
2132 {
2133     acl_t acl;
2134
2135     acl = acl_get_file(name, type);
2136     if (!acl) {
2137         if (errno == EOPNOTSUPP || errno == ENOSYS)
2138             return -2;
2139         PyErr_SetFromErrno(PyExc_IOError);
2140         return -1;
2141     }
2142
2143     *num = NULL;
2144     *txt = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE);
2145     if (*txt)
2146         *num = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE | TEXT_NUMERIC_IDS);
2147
2148     if (*txt && *num)
2149         return 0;
2150
2151     if (errno == ENOMEM)
2152         PyErr_NoMemory();
2153     else
2154         PyErr_SetFromErrno(PyExc_IOError);
2155
2156     if (*txt)
2157         acl_free((acl_t)*txt);
2158     if (*num)
2159         acl_free((acl_t)*num);
2160
2161     return -1;
2162 }
2163
2164 static PyObject *bup_read_acl(PyObject *self, PyObject *args)
2165 {
2166     char *name;
2167     int isdir, rv;
2168     PyObject *ret = NULL;
2169     char *acl_txt = NULL, *acl_num = NULL;
2170
2171     if (!PyArg_ParseTuple(args, cstr_argf "i", &name, &isdir))
2172         return NULL;
2173
2174     if (!acl_extended_file(name))
2175         Py_RETURN_NONE;
2176
2177     rv = bup_read_acl_to_text(name, ACL_TYPE_ACCESS, &acl_txt, &acl_num);
2178     if (rv)
2179         goto out;
2180
2181     if (isdir) {
2182         char *def_txt = NULL, *def_num = NULL;
2183
2184         rv = bup_read_acl_to_text(name, ACL_TYPE_DEFAULT, &def_txt, &def_num);
2185         if (rv)
2186             goto out;
2187
2188         ret = Py_BuildValue("[" cstr_argf cstr_argf cstr_argf cstr_argf "]",
2189                             acl_txt, acl_num, def_txt, def_num);
2190
2191         if (def_txt)
2192             acl_free((acl_t)def_txt);
2193         if (def_num)
2194             acl_free((acl_t)def_num);
2195     } else {
2196         ret = Py_BuildValue("[" cstr_argf cstr_argf "]",
2197                             acl_txt, acl_num);
2198     }
2199
2200 out:
2201     if (acl_txt)
2202         acl_free((acl_t)acl_txt);
2203     if (acl_num)
2204         acl_free((acl_t)acl_num);
2205     if (rv == -2)
2206         Py_RETURN_NONE;
2207     return ret;
2208 }
2209
2210 static int bup_apply_acl_string(const char *name, const char *s)
2211 {
2212     acl_t acl = acl_from_text(s);
2213     int ret = 0;
2214
2215     if (!acl) {
2216         PyErr_SetFromErrno(PyExc_IOError);
2217         return -1;
2218     }
2219
2220     if (acl_set_file(name, ACL_TYPE_ACCESS, acl)) {
2221         PyErr_SetFromErrno(PyExc_IOError);
2222         ret = -1;
2223     }
2224
2225     acl_free(acl);
2226
2227     return ret;
2228 }
2229
2230 static PyObject *bup_apply_acl(PyObject *self, PyObject *args)
2231 {
2232     char *name, *acl, *def = NULL;
2233
2234     if (!PyArg_ParseTuple(args, cstr_argf cstr_argf "|" cstr_argf, &name, &acl, &def))
2235         return NULL;
2236
2237     if (bup_apply_acl_string(name, acl))
2238         return NULL;
2239
2240     if (def && bup_apply_acl_string(name, def))
2241         return NULL;
2242
2243     Py_RETURN_NONE;
2244 }
2245 #endif
2246
2247 static PyObject *bup_limited_vint_pack(PyObject *self, PyObject *args)
2248 {
2249     const char *fmt;
2250     PyObject *packargs, *result;
2251     Py_ssize_t sz, i, bufsz;
2252     char *buf, *pos, *end;
2253
2254     if (!PyArg_ParseTuple(args, "sO", &fmt, &packargs))
2255         return NULL;
2256
2257     if (!PyTuple_Check(packargs))
2258         return PyErr_Format(PyExc_Exception, "pack() arg must be tuple");
2259
2260     sz = PyTuple_GET_SIZE(packargs);
2261     if (sz != (Py_ssize_t)strlen(fmt))
2262         return PyErr_Format(PyExc_Exception,
2263                             "number of arguments (%ld) does not match format string (%ld)",
2264                             (unsigned long)sz, (unsigned long)strlen(fmt));
2265
2266     if (sz > INT_MAX / 20)
2267         return PyErr_Format(PyExc_Exception, "format is far too long");
2268
2269     // estimate no more than 20 bytes for each on average, the maximum
2270     // vint/vuint we can encode is anyway 10 bytes, so this gives us
2271     // some headroom for a few strings before we need to realloc ...
2272     bufsz = sz * 20;
2273     buf = malloc(bufsz);
2274     if (!buf)
2275         return PyErr_NoMemory();
2276
2277     pos = buf;
2278     end = buf + bufsz;
2279     for (i = 0; i < sz; i++) {
2280         PyObject *item = PyTuple_GET_ITEM(packargs, i);
2281         const char *bytes;
2282
2283         switch (fmt[i]) {
2284         case 'V': {
2285             long long val = PyLong_AsLongLong(item);
2286             if (val == -1 && PyErr_Occurred())
2287                 return PyErr_Format(PyExc_OverflowError,
2288                                     "pack arg %d invalid", (int)i);
2289             if (end - pos < 10)
2290                 goto overflow;
2291             pos += vuint_encode(val, pos);
2292             break;
2293         }
2294         case 'v': {
2295             long long val = PyLong_AsLongLong(item);
2296             if (val == -1 && PyErr_Occurred())
2297                 return PyErr_Format(PyExc_OverflowError,
2298                                     "pack arg %d invalid", (int)i);
2299             if (end - pos < 10)
2300                 goto overflow;
2301             pos += vint_encode(val, pos);
2302             break;
2303         }
2304         case 's': {
2305             bytes = PyBytes_AsString(item);
2306             if (!bytes)
2307                 goto error;
2308             if (end - pos < 10)
2309                 goto overflow;
2310             Py_ssize_t val = PyBytes_GET_SIZE(item);
2311             pos += vuint_encode(val, pos);
2312             if (end - pos < val)
2313                 goto overflow;
2314             memcpy(pos, bytes, val);
2315             pos += val;
2316             break;
2317         }
2318         default:
2319             PyErr_Format(PyExc_Exception, "unknown xpack format string item %c",
2320                          fmt[i]);
2321             goto error;
2322         }
2323     }
2324
2325     result = PyBytes_FromStringAndSize(buf, pos - buf);
2326     free(buf);
2327     return result;
2328
2329  overflow:
2330     PyErr_SetString(PyExc_OverflowError, "buffer (potentially) overflowed");
2331  error:
2332     free(buf);
2333     return NULL;
2334 }
2335
2336 static PyMethodDef helper_methods[] = {
2337     { "write_sparsely", bup_write_sparsely, METH_VARARGS,
2338       "Write buf excepting zeros at the end. Return trailing zero count." },
2339     { "selftest", selftest, METH_VARARGS,
2340         "Check that the rolling checksum rolls correctly (for unit tests)." },
2341     { "blobbits", blobbits, METH_VARARGS,
2342         "Return the number of bits in the rolling checksum." },
2343     { "splitbuf", splitbuf, METH_VARARGS,
2344         "Split a list of strings based on a rolling checksum." },
2345     { "bitmatch", bitmatch, METH_VARARGS,
2346         "Count the number of matching prefix bits between two strings." },
2347     { "firstword", firstword, METH_VARARGS,
2348         "Return an int corresponding to the first 32 bits of buf." },
2349     { "bloom_contains", bloom_contains, METH_VARARGS,
2350         "Check if a bloom filter of 2^nbits bytes contains an object" },
2351     { "bloom_add", bloom_add, METH_VARARGS,
2352         "Add an object to a bloom filter of 2^nbits bytes" },
2353     { "extract_bits", extract_bits, METH_VARARGS,
2354         "Take the first 'nbits' bits from 'buf' and return them as an int." },
2355     { "merge_into", merge_into, METH_VARARGS,
2356         "Merges a bunch of idx and midx files into a single midx." },
2357     { "write_idx", write_idx, METH_VARARGS,
2358         "Write a PackIdxV2 file from an idx list of lists of tuples" },
2359     { "write_random", write_random, METH_VARARGS,
2360         "Write random bytes to the given file descriptor" },
2361     { "random_sha", random_sha, METH_VARARGS,
2362         "Return a random 20-byte string" },
2363     { "open_noatime", open_noatime, METH_VARARGS,
2364         "open() the given filename for read with O_NOATIME if possible" },
2365     { "fadvise_done", fadvise_done, METH_VARARGS,
2366         "Inform the kernel that we're finished with earlier parts of a file" },
2367 #ifdef BUP_HAVE_FILE_ATTRS
2368     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
2369       "Return the Linux attributes for the given file." },
2370 #endif
2371 #ifdef BUP_HAVE_FILE_ATTRS
2372     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
2373       "Set the Linux attributes for the given file." },
2374 #endif
2375
2376 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
2377 #ifdef HAVE_UTIMENSAT
2378     { "bup_utimensat", bup_utimensat, METH_VARARGS,
2379       "Change path timestamps with nanosecond precision (POSIX)." },
2380 #endif
2381 #ifdef HAVE_UTIMES
2382     { "bup_utimes", bup_utimes, METH_VARARGS,
2383       "Change path timestamps with microsecond precision." },
2384 #endif
2385 #ifdef HAVE_LUTIMES
2386     { "bup_lutimes", bup_lutimes, METH_VARARGS,
2387       "Change path timestamps with microsecond precision;"
2388       " don't follow symlinks." },
2389 #endif
2390 #endif // defined BUP_USE_PYTHON_UTIME
2391
2392     { "stat", bup_stat, METH_VARARGS,
2393       "Extended version of stat." },
2394     { "lstat", bup_lstat, METH_VARARGS,
2395       "Extended version of lstat." },
2396     { "fstat", bup_fstat, METH_VARARGS,
2397       "Extended version of fstat." },
2398 #ifdef HAVE_TM_TM_GMTOFF
2399     { "localtime", bup_localtime, METH_VARARGS,
2400       "Return struct_time elements plus the timezone offset and name." },
2401 #endif
2402     { "bytescmp", bup_bytescmp, METH_VARARGS,
2403       "Return a negative value if x < y, zero if equal, positive otherwise."},
2404     { "cat_bytes", bup_cat_bytes, METH_VARARGS,
2405       "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
2406 #ifdef BUP_MINCORE_BUF_TYPE
2407     { "mincore", bup_mincore, METH_VARARGS,
2408       "For mincore(src, src_n, src_off, dest, dest_off)"
2409       " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
2410 #endif
2411     { "getpwuid", bup_getpwuid, METH_VARARGS,
2412       "Return the password database entry for the given numeric user id,"
2413       " as a tuple with all C strings as bytes(), or None if the user does"
2414       " not exist." },
2415     { "getpwnam", bup_getpwnam, METH_VARARGS,
2416       "Return the password database entry for the given user name,"
2417       " as a tuple with all C strings as bytes(), or None if the user does"
2418       " not exist." },
2419     { "getgrgid", bup_getgrgid, METH_VARARGS,
2420       "Return the group database entry for the given numeric group id,"
2421       " as a tuple with all C strings as bytes(), or None if the group does"
2422       " not exist." },
2423     { "getgrnam", bup_getgrnam, METH_VARARGS,
2424       "Return the group database entry for the given group name,"
2425       " as a tuple with all C strings as bytes(), or None if the group does"
2426       " not exist." },
2427     { "gethostname", bup_gethostname, METH_NOARGS,
2428       "Return the current hostname (as bytes)" },
2429 #ifdef BUP_HAVE_READLINE
2430     { "set_completion_entry_function", bup_set_completion_entry_function, METH_VARARGS,
2431       "Set rl_completion_entry_function.  Called as f(text, state)." },
2432     { "set_attempted_completion_function", bup_set_attempted_completion_function, METH_VARARGS,
2433       "Set rl_attempted_completion_function.  Called as f(text, start, end)." },
2434     { "parse_and_bind", bup_parse_and_bind, METH_VARARGS,
2435       "Call rl_parse_and_bind." },
2436     { "get_line_buffer", bup_get_line_buffer, METH_NOARGS,
2437       "Return rl_line_buffer." },
2438     { "get_completer_word_break_characters", bup_get_completer_word_break_characters, METH_NOARGS,
2439       "Return rl_completer_word_break_characters." },
2440     { "set_completer_word_break_characters", bup_set_completer_word_break_characters, METH_VARARGS,
2441       "Set rl_completer_word_break_characters." },
2442     { "readline", bup_readline, METH_VARARGS,
2443       "Call readline(prompt)." },
2444 #endif // defined BUP_HAVE_READLINE
2445 #ifdef ACL_SUPPORT
2446     { "read_acl", bup_read_acl, METH_VARARGS,
2447       "read_acl(name, isdir)\n\n"
2448       "Read ACLs for the given file/dirname and return the correctly encoded"
2449       " list [txt, num, def_tx, def_num] (the def_* being empty bytestrings"
2450       " unless the second argument 'isdir' is True)." },
2451     { "apply_acl", bup_apply_acl, METH_VARARGS,
2452       "apply_acl(name, acl, def=None)\n\n"
2453       "Given a file/dirname (bytes) and the ACLs to restore, do that." },
2454 #endif /* HAVE_ACLS */
2455     { "vuint_encode", bup_vuint_encode, METH_VARARGS, "encode an int to vuint" },
2456     { "vint_encode", bup_vint_encode, METH_VARARGS, "encode an int to vint" },
2457     { "limited_vint_pack", bup_limited_vint_pack, METH_VARARGS,
2458       "Try to pack vint/vuint/str, throwing OverflowError when unable." },
2459     { NULL, NULL, 0, NULL },  // sentinel
2460 };
2461
2462 static void test_integral_assignment_fits(void)
2463 {
2464     assert(sizeof(signed short) == sizeof(unsigned short));
2465     assert(sizeof(signed short) < sizeof(signed long long));
2466     assert(sizeof(signed short) < sizeof(unsigned long long));
2467     assert(sizeof(unsigned short) < sizeof(signed long long));
2468     assert(sizeof(unsigned short) < sizeof(unsigned long long));
2469     assert(sizeof(Py_ssize_t) <= sizeof(size_t));
2470     {
2471         signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
2472         unsigned short us, usmax = USHRT_MAX;
2473         signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
2474         unsigned long long ullmax = ULLONG_MAX;
2475
2476         assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
2477         assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
2478         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
2479         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
2480         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
2481         assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
2482
2483         assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
2484         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
2485         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
2486         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
2487         assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
2488     }
2489 }
2490
2491 static int setup_module(PyObject *m)
2492 {
2493     // FIXME: migrate these tests to configure, or at least don't
2494     // possibly crash the whole application.  Check against the type
2495     // we're going to use when passing to python.  Other stat types
2496     // are tested at runtime.
2497     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
2498     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
2499     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
2500     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
2501     // Just be sure (relevant when passing timestamps back to Python above).
2502     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
2503     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
2504     // At least for INTEGER_TO_PY
2505     assert(sizeof(intmax_t) <= sizeof(long long));
2506     assert(sizeof(uintmax_t) <= sizeof(unsigned long long));
2507
2508     test_integral_assignment_fits();
2509
2510     // Originally required by append_sparse_region()
2511     {
2512         off_t probe;
2513         if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
2514         {
2515             fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
2516             exit(1);
2517         }
2518     }
2519
2520     char *e;
2521     {
2522         PyObject *value;
2523         value = INTEGER_TO_PY(INT_MAX);
2524         PyObject_SetAttrString(m, "INT_MAX", value);
2525         Py_DECREF(value);
2526         value = INTEGER_TO_PY(UINT_MAX);
2527         PyObject_SetAttrString(m, "UINT_MAX", value);
2528         Py_DECREF(value);
2529     }
2530
2531 #ifndef BUP_USE_PYTHON_UTIME // just for Python 2 now
2532 #ifdef HAVE_UTIMENSAT
2533     {
2534         PyObject *value;
2535         value = INTEGER_TO_PY(AT_FDCWD);
2536         PyObject_SetAttrString(m, "AT_FDCWD", value);
2537         Py_DECREF(value);
2538         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
2539         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
2540         Py_DECREF(value);
2541         value = INTEGER_TO_PY(UTIME_NOW);
2542         PyObject_SetAttrString(m, "UTIME_NOW", value);
2543         Py_DECREF(value);
2544     }
2545 #endif
2546 #endif // defined BUP_USE_PYTHON_UTIME
2547
2548 #ifdef BUP_HAVE_MINCORE_INCORE
2549     {
2550         PyObject *value;
2551         value = INTEGER_TO_PY(MINCORE_INCORE);
2552         PyObject_SetAttrString(m, "MINCORE_INCORE", value);
2553         Py_DECREF(value);
2554     }
2555 #endif
2556
2557     e = getenv("BUP_FORCE_TTY");
2558     get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
2559     return 1;
2560 }
2561
2562
2563 #if PY_MAJOR_VERSION < 3
2564
2565 PyMODINIT_FUNC init_helpers(void)
2566 {
2567     PyObject *m = Py_InitModule("_helpers", helper_methods);
2568     if (m == NULL) {
2569         PyErr_SetString(PyExc_RuntimeError, "bup._helpers init failed");
2570         return;
2571     }
2572     if (!setup_module(m))
2573     {
2574         PyErr_SetString(PyExc_RuntimeError, "bup._helpers set up failed");
2575         Py_DECREF(m);
2576         return;
2577     }
2578 }
2579
2580 # else // PY_MAJOR_VERSION >= 3
2581
2582 static struct PyModuleDef helpers_def = {
2583     PyModuleDef_HEAD_INIT,
2584     "_helpers",
2585     NULL,
2586     sizeof(state_t),
2587     helper_methods,
2588     NULL,
2589     NULL, // helpers_traverse,
2590     NULL, // helpers_clear,
2591     NULL
2592 };
2593
2594 PyMODINIT_FUNC PyInit__helpers(void)
2595 {
2596     PyObject *module = PyModule_Create(&helpers_def);
2597     if (module == NULL)
2598         return NULL;
2599     if (!setup_module(module))
2600     {
2601         Py_DECREF(module);
2602         return NULL;
2603     }
2604     return module;
2605 }
2606
2607 #endif // PY_MAJOR_VERSION >= 3