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