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