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