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