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