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