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