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