]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
Switch mincore to Py_buffer for py3
[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 <assert.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <arpa/inet.h>
14 #include <stddef.h>
15 #include <stdint.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
25 #endif
26 #ifdef HAVE_SYS_STAT_H
27 #include <sys/stat.h>
28 #endif
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32
33 #ifdef HAVE_LINUX_FS_H
34 #include <linux/fs.h>
35 #endif
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
38 #endif
39
40 #ifdef HAVE_TM_TM_GMTOFF
41 #include <time.h>
42 #endif
43
44 #include "bupsplit.h"
45
46 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
47 #define BUP_HAVE_FILE_ATTRS 1
48 #endif
49
50 /*
51  * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
52  * pretend we don't have it.
53  */
54 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
55 #undef HAVE_UTIMENSAT
56 #endif
57
58 #ifndef FS_NOCOW_FL
59 // Of course, this assumes it's a bitfield value.
60 #define FS_NOCOW_FL 0
61 #endif
62
63
64 typedef unsigned char byte;
65
66
67 typedef struct {
68     int istty2;
69 } state_t;
70
71 #if PY_MAJOR_VERSION < 3
72 static state_t state;
73 #  define get_state(x) (&state)
74 #  define buf_argf "s"
75 #else
76 #  define get_state(x) ((state_t *) PyModule_GetState(x))
77 #  define buf_argf "y"
78 #endif // PY_MAJOR_VERSION >= 3
79
80
81 #ifndef htonll
82 // This function should technically be macro'd out if it's going to be used
83 // more than ocasionally.  As of this writing, it'll actually never be called
84 // in real world bup scenarios (because our packs are < MAX_INT bytes).
85 static uint64_t htonll(uint64_t value)
86 {
87     static const int endian_test = 42;
88
89     if (*(char *)&endian_test == endian_test) // LSB-MSB
90         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
91     return value; // already in network byte order MSB-LSB
92 }
93 #endif
94
95
96 #define INTEGRAL_ASSIGNMENT_FITS(dest, src)                             \
97     ({                                                                  \
98         *(dest) = (src);                                                \
99         *(dest) == (src) && (*(dest) < 1) == ((src) < 1);               \
100     })
101
102
103 // At the moment any code that calls INTGER_TO_PY() will have to
104 // disable -Wtautological-compare for clang.  See below.
105
106 #define INTEGER_TO_PY(x) \
107     (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
108
109
110
111 #if PY_MAJOR_VERSION < 3
112 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
113                                 const char *name)
114 {
115     const long tmp = PyInt_AsLong(py);
116     if (tmp == -1 && PyErr_Occurred())
117     {
118         if (PyErr_ExceptionMatches(PyExc_OverflowError))
119             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
120                          name);
121         return 0;
122     }
123     if (tmp < 0)
124     {
125         PyErr_Format(PyExc_OverflowError,
126                      "negative %s cannot be converted to unsigned long", name);
127         return 0;
128     }
129     *x = tmp;
130     return 1;
131 }
132 #endif
133
134
135 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
136 {
137 #if PY_MAJOR_VERSION < 3
138     if (PyInt_Check(py))
139         return bup_ulong_from_pyint(x, py, name);
140 #endif
141
142     if (!PyLong_Check(py))
143     {
144         PyErr_Format(PyExc_TypeError, "expected integer %s", name);
145         return 0;
146     }
147
148     const unsigned long tmp = PyLong_AsUnsignedLong(py);
149     if (PyErr_Occurred())
150     {
151         if (PyErr_ExceptionMatches(PyExc_OverflowError))
152             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
153                          name);
154         return 0;
155     }
156     *x = tmp;
157     return 1;
158 }
159
160
161 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
162 {
163     unsigned long tmp;
164     if (!bup_ulong_from_py(&tmp, py, name))
165         return 0;
166
167     if (tmp > UINT_MAX)
168     {
169         PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
170         return 0;
171     }
172     *x = tmp;
173     return 1;
174 }
175
176 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
177                               const char *name)
178 {
179 #if PY_MAJOR_VERSION < 3
180     if (PyInt_Check(py))
181     {
182         unsigned long tmp;
183         if (bup_ulong_from_pyint(&tmp, py, name))
184         {
185             *x = tmp;
186             return 1;
187         }
188         return 0;
189     }
190 #endif
191
192     if (!PyLong_Check(py))
193     {
194         PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
195         return 0;
196     }
197
198     const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
199     if (tmp == (unsigned long long) -1 && PyErr_Occurred())
200     {
201         if (PyErr_ExceptionMatches(PyExc_OverflowError))
202             PyErr_Format(PyExc_OverflowError,
203                          "%s too big for unsigned long long", name);
204         return 0;
205     }
206     *x = tmp;
207     return 1;
208 }
209
210
211 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
212 {
213     PyObject *py_s1, *py_s2;  // This is really a PyBytes/PyString
214     if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
215         return NULL;
216     char *s1, *s2;
217     Py_ssize_t s1_len, s2_len;
218     if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
219         return NULL;
220     if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
221         return NULL;
222     const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
223     const int cmp = memcmp(s1, s2, n);
224     if (cmp != 0)
225         return PyLong_FromLong(cmp);
226     if (s1_len == s2_len)
227         return PyLong_FromLong(0);;
228     return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
229 }
230
231
232 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
233 #if __WIN32__ || __CYGWIN__
234
235 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
236 static void unpythonize_argv(void) { }
237
238 #else // not __WIN32__
239
240 // For some reason this isn't declared in Python.h
241 extern void Py_GetArgcArgv(int *argc, char ***argv);
242
243 static void unpythonize_argv(void)
244 {
245     int argc, i;
246     char **argv, *arge;
247     
248     Py_GetArgcArgv(&argc, &argv);
249     
250     for (i = 0; i < argc-1; i++)
251     {
252         if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
253         {
254             // The argv block doesn't work the way we expected; it's unsafe
255             // to mess with it.
256             return;
257         }
258     }
259     
260     arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
261     
262     if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
263     {
264         char *p;
265         size_t len, diff;
266         p = strrchr(argv[1], '/');
267         if (p)
268         {
269             p++;
270             diff = p - argv[0];
271             len = arge - p;
272             memmove(argv[0], p, len);
273             memset(arge - diff, 0, diff);
274             for (i = 0; i < argc; i++)
275                 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
276         }
277     }
278 }
279
280 #endif // not __WIN32__ or __CYGWIN__
281
282
283 static int write_all(int fd, const void *buf, const size_t count)
284 {
285     size_t written = 0;
286     while (written < count)
287     {
288         const ssize_t rc = write(fd, buf + written, count - written);
289         if (rc == -1)
290             return -1;
291         written += rc;
292     }
293     return 0;
294 }
295
296
297 static int uadd(unsigned long long *dest,
298                 const unsigned long long x,
299                 const unsigned long long y)
300 {
301     const unsigned long long result = x + y;
302     if (result < x || result < y)
303         return 0;
304     *dest = result;
305     return 1;
306 }
307
308
309 static PyObject *append_sparse_region(const int fd, unsigned long long n)
310 {
311     while (n)
312     {
313         off_t new_off;
314         if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
315             new_off = INT_MAX;
316         const off_t off = lseek(fd, new_off, SEEK_CUR);
317         if (off == (off_t) -1)
318             return PyErr_SetFromErrno(PyExc_IOError);
319         n -= new_off;
320     }
321     return NULL;
322 }
323
324
325 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
326                                      const int fd,
327                                      unsigned long long prev_pending,
328                                      const unsigned long long count)
329 {
330     // Add count additional sparse zeros to prev_pending and store the
331     // result in new_pending, or if the total won't fit in
332     // new_pending, write some of the zeros to fd sparsely, and store
333     // the remaining sum in new_pending.
334     if (!uadd(new_pending, prev_pending, count))
335     {
336         PyObject *err = append_sparse_region(fd, prev_pending);
337         if (err != NULL)
338             return err;
339         *new_pending = count;
340     }
341     return NULL;
342 }
343
344
345 static byte* find_not_zero(const byte * const start, const byte * const end)
346 {
347     // Return a pointer to first non-zero byte between start and end,
348     // or end if there isn't one.
349     assert(start <= end);
350     const unsigned char *cur = start;
351     while (cur < end && *cur == 0)
352         cur++;
353     return (byte *) cur;
354 }
355
356
357 static byte* find_trailing_zeros(const byte * const start,
358                                  const byte * const end)
359 {
360     // Return a pointer to the start of any trailing run of zeros, or
361     // end if there isn't one.
362     assert(start <= end);
363     if (start == end)
364         return (byte *) end;
365     const byte * cur = end;
366     while (cur > start && *--cur == 0) {}
367     if (*cur == 0)
368         return (byte *) cur;
369     else
370         return (byte *) (cur + 1);
371 }
372
373
374 static byte *find_non_sparse_end(const byte * const start,
375                                  const byte * const end,
376                                  const unsigned long long min_len)
377 {
378     // Return the first pointer to a min_len sparse block in [start,
379     // end) if there is one, otherwise a pointer to the start of any
380     // trailing run of zeros.  If there are no trailing zeros, return
381     // end.
382     if (start == end)
383         return (byte *) end;
384     assert(start < end);
385     assert(min_len);
386     // Probe in min_len jumps, searching backward from the jump
387     // destination for a non-zero byte.  If such a byte is found, move
388     // just past it and try again.
389     const byte *candidate = start;
390     // End of any run of zeros, starting at candidate, that we've already seen
391     const byte *end_of_known_zeros = candidate;
392     while (end - candidate >= min_len) // Handle all min_len candidate blocks
393     {
394         const byte * const probe_end = candidate + min_len;
395         const byte * const trailing_zeros =
396             find_trailing_zeros(end_of_known_zeros, probe_end);
397         if (trailing_zeros == probe_end)
398             end_of_known_zeros = candidate = probe_end;
399         else if (trailing_zeros == end_of_known_zeros)
400         {
401             assert(candidate >= start);
402             assert(candidate <= end);
403             assert(*candidate == 0);
404             return (byte *) candidate;
405         }
406         else
407         {
408             candidate = trailing_zeros;
409             end_of_known_zeros = probe_end;
410         }
411     }
412
413     if (candidate == end)
414         return (byte *) end;
415
416     // No min_len sparse run found, search backward from end
417     const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
418                                                             end);
419
420     if (trailing_zeros == end_of_known_zeros)
421     {
422         assert(candidate >= start);
423         assert(candidate < end);
424         assert(*candidate == 0);
425         assert(end - candidate < min_len);
426         return (byte *) candidate;
427     }
428
429     if (trailing_zeros == end)
430     {
431         assert(*(end - 1) != 0);
432         return (byte *) end;
433     }
434
435     assert(end - trailing_zeros < min_len);
436     assert(trailing_zeros >= start);
437     assert(trailing_zeros < end);
438     assert(*trailing_zeros == 0);
439     return (byte *) trailing_zeros;
440 }
441
442
443 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
444 {
445     int fd;
446     unsigned char *buf = NULL;
447     Py_ssize_t sbuf_len;
448     PyObject *py_min_sparse_len, *py_prev_sparse_len;
449     if (!PyArg_ParseTuple(args, "it#OO",
450                           &fd, &buf, &sbuf_len,
451                           &py_min_sparse_len, &py_prev_sparse_len))
452         return NULL;
453     unsigned long long min_sparse_len, prev_sparse_len, buf_len;
454     if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
455         return NULL;
456     if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
457         return NULL;
458     if (sbuf_len < 0)
459         return PyErr_Format(PyExc_ValueError, "negative bufer length");
460     if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
461         return PyErr_Format(PyExc_OverflowError, "buffer length too large");
462
463     const byte * block = buf; // Start of pending block
464     const byte * const end = buf + buf_len;
465     unsigned long long zeros = prev_sparse_len;
466     while (1)
467     {
468         assert(block <= end);
469         if (block == end)
470             return PyLong_FromUnsignedLongLong(zeros);
471
472         if (*block != 0)
473         {
474             // Look for the end of block, i.e. the next sparse run of
475             // at least min_sparse_len zeros, or the end of the
476             // buffer.
477             const byte * const probe = find_non_sparse_end(block + 1, end,
478                                                            min_sparse_len);
479             // Either at end of block, or end of non-sparse; write pending data
480             PyObject *err = append_sparse_region(fd, zeros);
481             if (err != NULL)
482                 return err;
483             int rc = write_all(fd, block, probe - block);
484             if (rc)
485                 return PyErr_SetFromErrno(PyExc_IOError);
486
487             if (end - probe < min_sparse_len)
488                 zeros = end - probe;
489             else
490                 zeros = min_sparse_len;
491             block = probe + zeros;
492         }
493         else // *block == 0
494         {
495             // Should be in the first loop iteration, a sparse run of
496             // zeros, or nearly at the end of the block (within
497             // min_sparse_len).
498             const byte * const zeros_end = find_not_zero(block, end);
499             PyObject *err = record_sparse_zeros(&zeros, fd,
500                                                 zeros, zeros_end - block);
501             if (err != NULL)
502                 return err;
503             assert(block <= zeros_end);
504             block = zeros_end;
505         }
506     }
507 }
508
509
510 static PyObject *selftest(PyObject *self, PyObject *args)
511 {
512     if (!PyArg_ParseTuple(args, ""))
513         return NULL;
514     
515     return Py_BuildValue("i", !bupsplit_selftest());
516 }
517
518
519 static PyObject *blobbits(PyObject *self, PyObject *args)
520 {
521     if (!PyArg_ParseTuple(args, ""))
522         return NULL;
523     return Py_BuildValue("i", BUP_BLOBBITS);
524 }
525
526
527 static PyObject *splitbuf(PyObject *self, PyObject *args)
528 {
529     unsigned char *buf = NULL;
530     Py_ssize_t len = 0;
531     int out = 0, bits = -1;
532
533     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
534         return NULL;
535     assert(len <= INT_MAX);
536     out = bupsplit_find_ofs(buf, len, &bits);
537     if (out) assert(bits >= BUP_BLOBBITS);
538     return Py_BuildValue("ii", out, bits);
539 }
540
541
542 static PyObject *bitmatch(PyObject *self, PyObject *args)
543 {
544     unsigned char *buf1 = NULL, *buf2 = NULL;
545     Py_ssize_t len1 = 0, len2 = 0;
546     Py_ssize_t byte;
547     int bit;
548
549     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
550         return NULL;
551     
552     bit = 0;
553     for (byte = 0; byte < len1 && byte < len2; byte++)
554     {
555         int b1 = buf1[byte], b2 = buf2[byte];
556         if (b1 != b2)
557         {
558             for (bit = 0; bit < 8; bit++)
559                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
560                     break;
561             break;
562         }
563     }
564     
565     assert(byte <= (INT_MAX >> 3));
566     return Py_BuildValue("i", byte*8 + bit);
567 }
568
569
570 static PyObject *firstword(PyObject *self, PyObject *args)
571 {
572     unsigned char *buf = NULL;
573     Py_ssize_t len = 0;
574     uint32_t v;
575
576     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
577         return NULL;
578     
579     if (len < 4)
580         return NULL;
581     
582     v = ntohl(*(uint32_t *)buf);
583     return PyLong_FromUnsignedLong(v);
584 }
585
586
587 #define BLOOM2_HEADERLEN 16
588
589 static void to_bloom_address_bitmask4(const unsigned char *buf,
590         const int nbits, uint64_t *v, unsigned char *bitmask)
591 {
592     int bit;
593     uint32_t high;
594     uint64_t raw, mask;
595
596     memcpy(&high, buf, 4);
597     mask = (1<<nbits) - 1;
598     raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
599     bit = (raw >> (37-nbits)) & 0x7;
600     *v = (raw >> (40-nbits)) & mask;
601     *bitmask = 1 << bit;
602 }
603
604 static void to_bloom_address_bitmask5(const unsigned char *buf,
605         const int nbits, uint32_t *v, unsigned char *bitmask)
606 {
607     int bit;
608     uint32_t high;
609     uint32_t raw, mask;
610
611     memcpy(&high, buf, 4);
612     mask = (1<<nbits) - 1;
613     raw = ntohl(high);
614     bit = (raw >> (29-nbits)) & 0x7;
615     *v = (raw >> (32-nbits)) & mask;
616     *bitmask = 1 << bit;
617 }
618
619 #define BLOOM_SET_BIT(name, address, otype) \
620 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
621 {\
622     unsigned char bitmask;\
623     otype v;\
624     address(buf, nbits, &v, &bitmask);\
625     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
626 }
627 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
628 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
629
630
631 #define BLOOM_GET_BIT(name, address, otype) \
632 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
633 {\
634     unsigned char bitmask;\
635     otype v;\
636     address(buf, nbits, &v, &bitmask);\
637     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
638 }
639 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
640 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
641
642
643 static PyObject *bloom_add(PyObject *self, PyObject *args)
644 {
645     unsigned char *sha = NULL, *bloom = NULL;
646     unsigned char *end;
647     Py_ssize_t len = 0, blen = 0;
648     int nbits = 0, k = 0;
649
650     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
651         return NULL;
652
653     if (blen < 16+(1<<nbits) || len % 20 != 0)
654         return NULL;
655
656     if (k == 5)
657     {
658         if (nbits > 29)
659             return NULL;
660         for (end = sha + len; sha < end; sha += 20/k)
661             bloom_set_bit5(bloom, sha, nbits);
662     }
663     else if (k == 4)
664     {
665         if (nbits > 37)
666             return NULL;
667         for (end = sha + len; sha < end; sha += 20/k)
668             bloom_set_bit4(bloom, sha, nbits);
669     }
670     else
671         return NULL;
672
673
674     return Py_BuildValue("n", len/20);
675 }
676
677 static PyObject *bloom_contains(PyObject *self, PyObject *args)
678 {
679     unsigned char *sha = NULL, *bloom = NULL;
680     Py_ssize_t len = 0, blen = 0;
681     int nbits = 0, k = 0;
682     unsigned char *end;
683     int steps;
684
685     if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
686         return NULL;
687
688     if (len != 20)
689         return NULL;
690
691     if (k == 5)
692     {
693         if (nbits > 29)
694             return NULL;
695         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
696             if (!bloom_get_bit5(bloom, sha, nbits))
697                 return Py_BuildValue("Oi", Py_None, steps);
698     }
699     else if (k == 4)
700     {
701         if (nbits > 37)
702             return NULL;
703         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
704             if (!bloom_get_bit4(bloom, sha, nbits))
705                 return Py_BuildValue("Oi", Py_None, steps);
706     }
707     else
708         return NULL;
709
710     return Py_BuildValue("ii", 1, k);
711 }
712
713
714 static uint32_t _extract_bits(unsigned char *buf, int nbits)
715 {
716     uint32_t v, mask;
717
718     mask = (1<<nbits) - 1;
719     v = ntohl(*(uint32_t *)buf);
720     v = (v >> (32-nbits)) & mask;
721     return v;
722 }
723
724
725 static PyObject *extract_bits(PyObject *self, PyObject *args)
726 {
727     unsigned char *buf = NULL;
728     Py_ssize_t len = 0;
729     int nbits = 0;
730
731     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
732         return NULL;
733     
734     if (len < 4)
735         return NULL;
736     
737     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
738 }
739
740
741 struct sha {
742     unsigned char bytes[20];
743 };
744
745
746 struct idx {
747     unsigned char *map;
748     struct sha *cur;
749     struct sha *end;
750     uint32_t *cur_name;
751     Py_ssize_t bytes;
752     int name_base;
753 };
754
755
756 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
757 {
758     int i;
759     for (i = 0; i < sizeof(struct sha); i++)
760         if (sha1->bytes[i] != sha2->bytes[i])
761             return sha1->bytes[i] - sha2->bytes[i];
762     return 0;
763 }
764
765
766 static void _fix_idx_order(struct idx **idxs, int *last_i)
767 {
768     struct idx *idx;
769     int low, mid, high, c = 0;
770
771     idx = idxs[*last_i];
772     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
773     {
774         idxs[*last_i] = NULL;
775         PyMem_Free(idx);
776         --*last_i;
777         return;
778     }
779     if (*last_i == 0)
780         return;
781
782     low = *last_i-1;
783     mid = *last_i;
784     high = 0;
785     while (low >= high)
786     {
787         mid = (low + high) / 2;
788         c = _cmp_sha(idx->cur, idxs[mid]->cur);
789         if (c < 0)
790             high = mid + 1;
791         else if (c > 0)
792             low = mid - 1;
793         else
794             break;
795     }
796     if (c < 0)
797         ++mid;
798     if (mid == *last_i)
799         return;
800     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
801     idxs[mid] = idx;
802 }
803
804
805 static uint32_t _get_idx_i(struct idx *idx)
806 {
807     if (idx->cur_name == NULL)
808         return idx->name_base;
809     return ntohl(*idx->cur_name) + idx->name_base;
810 }
811
812 #define MIDX4_HEADERLEN 12
813
814 static PyObject *merge_into(PyObject *self, PyObject *args)
815 {
816     PyObject *py_total, *ilist = NULL;
817     unsigned char *fmap = NULL;
818     struct sha *sha_ptr, *sha_start = NULL;
819     uint32_t *table_ptr, *name_ptr, *name_start;
820     struct idx **idxs = NULL;
821     Py_ssize_t flen = 0;
822     int bits = 0, i;
823     unsigned int total;
824     uint32_t count, prefix;
825     int num_i;
826     int last_i;
827
828     if (!PyArg_ParseTuple(args, "w#iOO",
829                           &fmap, &flen, &bits, &py_total, &ilist))
830         return NULL;
831
832     if (!bup_uint_from_py(&total, py_total, "total"))
833         return NULL;
834
835     num_i = PyList_Size(ilist);
836     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
837
838     for (i = 0; i < num_i; i++)
839     {
840         long len, sha_ofs, name_map_ofs;
841         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
842         PyObject *itup = PyList_GetItem(ilist, i);
843         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
844                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
845             return NULL;
846         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
847         idxs[i]->end = &idxs[i]->cur[len];
848         if (name_map_ofs)
849             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
850         else
851             idxs[i]->cur_name = NULL;
852     }
853     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
854     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
855     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
856
857     last_i = num_i-1;
858     count = 0;
859     prefix = 0;
860     while (last_i >= 0)
861     {
862         struct idx *idx;
863         uint32_t new_prefix;
864         if (count % 102424 == 0 && get_state(self)->istty2)
865             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
866                     count*100.0/total, count, total);
867         idx = idxs[last_i];
868         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
869         while (prefix < new_prefix)
870             table_ptr[prefix++] = htonl(count);
871         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
872         *name_ptr++ = htonl(_get_idx_i(idx));
873         ++idx->cur;
874         if (idx->cur_name != NULL)
875             ++idx->cur_name;
876         _fix_idx_order(idxs, &last_i);
877         ++count;
878     }
879     while (prefix < (1<<bits))
880         table_ptr[prefix++] = htonl(count);
881     assert(count == total);
882     assert(prefix == (1<<bits));
883     assert(sha_ptr == sha_start+count);
884     assert(name_ptr == name_start+count);
885
886     PyMem_Free(idxs);
887     return PyLong_FromUnsignedLong(count);
888 }
889
890 #define FAN_ENTRIES 256
891
892 static PyObject *write_idx(PyObject *self, PyObject *args)
893 {
894     char *filename = NULL;
895     PyObject *py_total, *idx = NULL;
896     PyObject *part;
897     unsigned char *fmap = NULL;
898     Py_ssize_t flen = 0;
899     unsigned int total = 0;
900     uint32_t count;
901     int i, j, ofs64_count;
902     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
903     uint64_t *ofs64_ptr;
904     struct sha *sha_ptr;
905
906     if (!PyArg_ParseTuple(args, "sw#OO",
907                           &filename, &fmap, &flen, &idx, &py_total))
908         return NULL;
909
910     if (!bup_uint_from_py(&total, py_total, "total"))
911         return NULL;
912
913     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
914         return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
915                              FAN_ENTRIES);
916
917     const char idx_header[] = "\377tOc\0\0\0\002";
918     memcpy (fmap, idx_header, sizeof(idx_header) - 1);
919
920     fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
921     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
922     crc_ptr = (uint32_t *)&sha_ptr[total];
923     ofs_ptr = (uint32_t *)&crc_ptr[total];
924     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
925
926     count = 0;
927     ofs64_count = 0;
928     for (i = 0; i < FAN_ENTRIES; ++i)
929     {
930         int plen;
931         part = PyList_GET_ITEM(idx, i);
932         PyList_Sort(part);
933         plen = PyList_GET_SIZE(part);
934         count += plen;
935         *fan_ptr++ = htonl(count);
936         for (j = 0; j < plen; ++j)
937         {
938             unsigned char *sha = NULL;
939             Py_ssize_t sha_len = 0;
940             PyObject *crc_py, *ofs_py;
941             unsigned int crc;
942             unsigned PY_LONG_LONG ofs_ull;
943             uint64_t ofs;
944             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
945                                   &sha, &sha_len, &crc_py, &ofs_py))
946                 return NULL;
947             if(!bup_uint_from_py(&crc, crc_py, "crc"))
948                 return NULL;
949             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
950                 return NULL;
951             assert(crc <= UINT32_MAX);
952             assert(ofs_ull <= UINT64_MAX);
953             ofs = ofs_ull;
954             if (sha_len != sizeof(struct sha))
955                 return NULL;
956             memcpy(sha_ptr++, sha, sizeof(struct sha));
957             *crc_ptr++ = htonl(crc);
958             if (ofs > 0x7fffffff)
959             {
960                 *ofs64_ptr++ = htonll(ofs);
961                 ofs = 0x80000000 | ofs64_count++;
962             }
963             *ofs_ptr++ = htonl((uint32_t)ofs);
964         }
965     }
966
967     int rc = msync(fmap, flen, MS_ASYNC);
968     if (rc != 0)
969         return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
970
971     return PyLong_FromUnsignedLong(count);
972 }
973
974
975 // I would have made this a lower-level function that just fills in a buffer
976 // with random values, and then written those values from python.  But that's
977 // about 20% slower in my tests, and since we typically generate random
978 // numbers for benchmarking other parts of bup, any slowness in generating
979 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
980 // pseudorandom bytes much except for this anyway.
981 static PyObject *write_random(PyObject *self, PyObject *args)
982 {
983     uint32_t buf[1024/4];
984     int fd = -1, seed = 0, verbose = 0;
985     ssize_t ret;
986     long long len = 0, kbytes = 0, written = 0;
987
988     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
989         return NULL;
990     
991     srandom(seed);
992     
993     for (kbytes = 0; kbytes < len/1024; kbytes++)
994     {
995         unsigned i;
996         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
997             buf[i] = random();
998         ret = write(fd, buf, sizeof(buf));
999         if (ret < 0)
1000             ret = 0;
1001         written += ret;
1002         if (ret < (int)sizeof(buf))
1003             break;
1004         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1005             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1006     }
1007     
1008     // handle non-multiples of 1024
1009     if (len % 1024)
1010     {
1011         unsigned i;
1012         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1013             buf[i] = random();
1014         ret = write(fd, buf, len % 1024);
1015         if (ret < 0)
1016             ret = 0;
1017         written += ret;
1018     }
1019     
1020     if (kbytes/1024 > 0)
1021         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1022     return Py_BuildValue("L", written);
1023 }
1024
1025
1026 static PyObject *random_sha(PyObject *self, PyObject *args)
1027 {
1028     static int seeded = 0;
1029     uint32_t shabuf[20/4];
1030     int i;
1031     
1032     if (!seeded)
1033     {
1034         assert(sizeof(shabuf) == 20);
1035         srandom(time(NULL));
1036         seeded = 1;
1037     }
1038     
1039     if (!PyArg_ParseTuple(args, ""))
1040         return NULL;
1041     
1042     memset(shabuf, 0, sizeof(shabuf));
1043     for (i=0; i < 20/4; i++)
1044         shabuf[i] = random();
1045     return Py_BuildValue("s#", shabuf, 20);
1046 }
1047
1048
1049 static int _open_noatime(const char *filename, int attrs)
1050 {
1051     int attrs_noatime, fd;
1052     attrs |= O_RDONLY;
1053 #ifdef O_NOFOLLOW
1054     attrs |= O_NOFOLLOW;
1055 #endif
1056 #ifdef O_LARGEFILE
1057     attrs |= O_LARGEFILE;
1058 #endif
1059     attrs_noatime = attrs;
1060 #ifdef O_NOATIME
1061     attrs_noatime |= O_NOATIME;
1062 #endif
1063     fd = open(filename, attrs_noatime);
1064     if (fd < 0 && errno == EPERM)
1065     {
1066         // older Linux kernels would return EPERM if you used O_NOATIME
1067         // and weren't the file's owner.  This pointless restriction was
1068         // relaxed eventually, but we have to handle it anyway.
1069         // (VERY old kernels didn't recognized O_NOATIME, but they would
1070         // just harmlessly ignore it, so this branch won't trigger)
1071         fd = open(filename, attrs);
1072     }
1073     return fd;
1074 }
1075
1076
1077 static PyObject *open_noatime(PyObject *self, PyObject *args)
1078 {
1079     char *filename = NULL;
1080     int fd;
1081     if (!PyArg_ParseTuple(args, "s", &filename))
1082         return NULL;
1083     fd = _open_noatime(filename, 0);
1084     if (fd < 0)
1085         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1086     return Py_BuildValue("i", fd);
1087 }
1088
1089
1090 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1091 {
1092     int fd = -1;
1093     long long llofs, lllen = 0;
1094     if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1095         return NULL;
1096     off_t ofs, len;
1097     if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1098         return PyErr_Format(PyExc_OverflowError,
1099                             "fadvise offset overflows off_t");
1100     if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1101         return PyErr_Format(PyExc_OverflowError,
1102                             "fadvise length overflows off_t");
1103 #ifdef POSIX_FADV_DONTNEED
1104     posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1105 #endif    
1106     return Py_BuildValue("");
1107 }
1108
1109
1110 // Currently the Linux kernel and FUSE disagree over the type for
1111 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS.  The kernel actually uses int,
1112 // but FUSE chose long (matching the declaration in linux/fs.h).  So
1113 // if you use int, and then traverse a FUSE filesystem, you may
1114 // corrupt the stack.  But if you use long, then you may get invalid
1115 // results on big-endian systems.
1116 //
1117 // For now, we just use long, and then disable Linux attrs entirely
1118 // (with a warning) in helpers.py on systems that are affected.
1119
1120 #ifdef BUP_HAVE_FILE_ATTRS
1121 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1122 {
1123     int rc;
1124     unsigned long attr;
1125     char *path;
1126     int fd;
1127
1128     if (!PyArg_ParseTuple(args, "s", &path))
1129         return NULL;
1130
1131     fd = _open_noatime(path, O_NONBLOCK);
1132     if (fd == -1)
1133         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1134
1135     attr = 0;  // Handle int/long mismatch (see above)
1136     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1137     if (rc == -1)
1138     {
1139         close(fd);
1140         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1141     }
1142     close(fd);
1143     assert(attr <= UINT_MAX);  // Kernel type is actually int
1144     return PyLong_FromUnsignedLong(attr);
1145 }
1146 #endif /* def BUP_HAVE_FILE_ATTRS */
1147
1148
1149
1150 #ifdef BUP_HAVE_FILE_ATTRS
1151 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1152 {
1153     int rc;
1154     unsigned long orig_attr;
1155     unsigned int attr;
1156     char *path;
1157     PyObject *py_attr;
1158     int fd;
1159
1160     if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1161         return NULL;
1162
1163     if (!bup_uint_from_py(&attr, py_attr, "attr"))
1164         return NULL;
1165
1166     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1167     if (fd == -1)
1168         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1169
1170     // Restrict attr to modifiable flags acdeijstuADST -- see
1171     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
1172     // in pf.c flags_array[].
1173     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1174     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1175     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1176     | FS_TOPDIR_FL | FS_NOCOW_FL;
1177
1178     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1179     orig_attr = 0; // Handle int/long mismatch (see above)
1180     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1181     if (rc == -1)
1182     {
1183         close(fd);
1184         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1185     }
1186     assert(orig_attr <= UINT_MAX);  // Kernel type is actually int
1187     attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1188
1189     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1190     if (rc == -1)
1191     {
1192         close(fd);
1193         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1194     }
1195
1196     close(fd);
1197     return Py_BuildValue("O", Py_None);
1198 }
1199 #endif /* def BUP_HAVE_FILE_ATTRS */
1200
1201
1202 #ifndef HAVE_UTIMENSAT
1203 #ifndef HAVE_UTIMES
1204 #error "cannot find utimensat or utimes()"
1205 #endif
1206 #ifndef HAVE_LUTIMES
1207 #error "cannot find utimensat or lutimes()"
1208 #endif
1209 #endif
1210
1211 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1212     ({                                                     \
1213         int result = 0;                                                 \
1214         *(overflow) = 0;                                                \
1215         const long long lltmp = PyLong_AsLongLong(pylong);              \
1216         if (lltmp == -1 && PyErr_Occurred())                            \
1217         {                                                               \
1218             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
1219             {                                                           \
1220                 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1221                 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1222                 {                                                       \
1223                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
1224                     {                                                   \
1225                         PyErr_Clear();                                  \
1226                         *(overflow) = 1;                                \
1227                     }                                                   \
1228                 }                                                       \
1229                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
1230                     result = 1;                                         \
1231                 else                                                    \
1232                     *(overflow) = 1;                                    \
1233             }                                                           \
1234         }                                                               \
1235         else                                                            \
1236         {                                                               \
1237             if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
1238                 result = 1;                                             \
1239             else                                                        \
1240                 *(overflow) = 1;                                        \
1241         }                                                               \
1242         result;                                                         \
1243         })
1244
1245
1246 #ifdef HAVE_UTIMENSAT
1247
1248 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1249 {
1250     int rc;
1251     int fd, flag;
1252     char *path;
1253     PyObject *access_py, *modification_py;
1254     struct timespec ts[2];
1255
1256     if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1257                           &fd,
1258                           &path,
1259                           &access_py, &(ts[0].tv_nsec),
1260                           &modification_py, &(ts[1].tv_nsec),
1261                           &flag))
1262         return NULL;
1263
1264     int overflow;
1265     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1266     {
1267         if (overflow)
1268             PyErr_SetString(PyExc_ValueError,
1269                             "unable to convert access time seconds for utimensat");
1270         return NULL;
1271     }
1272     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1273     {
1274         if (overflow)
1275             PyErr_SetString(PyExc_ValueError,
1276                             "unable to convert modification time seconds for utimensat");
1277         return NULL;
1278     }
1279     rc = utimensat(fd, path, ts, flag);
1280     if (rc != 0)
1281         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1282
1283     return Py_BuildValue("O", Py_None);
1284 }
1285
1286 #endif /* def HAVE_UTIMENSAT */
1287
1288
1289 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1290
1291 static int bup_parse_xutimes_args(char **path,
1292                                   struct timeval tv[2],
1293                                   PyObject *args)
1294 {
1295     PyObject *access_py, *modification_py;
1296     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1297
1298     if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1299                           path,
1300                           &access_py, &access_us,
1301                           &modification_py, &modification_us))
1302         return 0;
1303
1304     int overflow;
1305     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1306     {
1307         if (overflow)
1308             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1309         return 0;
1310     }
1311     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1312     {
1313         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1314         return 0;
1315     }
1316     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1317     {
1318         if (overflow)
1319             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1320         return 0;
1321     }
1322     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1323     {
1324         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1325         return 0;
1326     }
1327     return 1;
1328 }
1329
1330 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1331
1332
1333 #ifdef HAVE_UTIMES
1334 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1335 {
1336     char *path;
1337     struct timeval tv[2];
1338     if (!bup_parse_xutimes_args(&path, tv, args))
1339         return NULL;
1340     int rc = utimes(path, tv);
1341     if (rc != 0)
1342         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1343     return Py_BuildValue("O", Py_None);
1344 }
1345 #endif /* def HAVE_UTIMES */
1346
1347
1348 #ifdef HAVE_LUTIMES
1349 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1350 {
1351     char *path;
1352     struct timeval tv[2];
1353     if (!bup_parse_xutimes_args(&path, tv, args))
1354         return NULL;
1355     int rc = lutimes(path, tv);
1356     if (rc != 0)
1357         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1358
1359     return Py_BuildValue("O", Py_None);
1360 }
1361 #endif /* def HAVE_LUTIMES */
1362
1363
1364 #ifdef HAVE_STAT_ST_ATIM
1365 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1366 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1367 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1368 #elif defined HAVE_STAT_ST_ATIMENSEC
1369 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1370 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1371 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1372 #else
1373 # define BUP_STAT_ATIME_NS(st) 0
1374 # define BUP_STAT_MTIME_NS(st) 0
1375 # define BUP_STAT_CTIME_NS(st) 0
1376 #endif
1377
1378
1379 #pragma clang diagnostic push
1380 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1381
1382 static PyObject *stat_struct_to_py(const struct stat *st,
1383                                    const char *filename,
1384                                    int fd)
1385 {
1386     // We can check the known (via POSIX) signed and unsigned types at
1387     // compile time, but not (easily) the unspecified types, so handle
1388     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1389     // long.
1390     return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1391                          INTEGER_TO_PY(st->st_mode),
1392                          (unsigned PY_LONG_LONG) st->st_ino,
1393                          INTEGER_TO_PY(st->st_dev),
1394                          INTEGER_TO_PY(st->st_nlink),
1395                          INTEGER_TO_PY(st->st_uid),
1396                          INTEGER_TO_PY(st->st_gid),
1397                          INTEGER_TO_PY(st->st_rdev),
1398                          (PY_LONG_LONG) st->st_size,
1399                          INTEGER_TO_PY(st->st_atime),
1400                          (long) BUP_STAT_ATIME_NS(st),
1401                          INTEGER_TO_PY(st->st_mtime),
1402                          (long) BUP_STAT_MTIME_NS(st),
1403                          INTEGER_TO_PY(st->st_ctime),
1404                          (long) BUP_STAT_CTIME_NS(st));
1405 }
1406
1407 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1408
1409 static PyObject *bup_stat(PyObject *self, PyObject *args)
1410 {
1411     int rc;
1412     char *filename;
1413
1414     if (!PyArg_ParseTuple(args, "s", &filename))
1415         return NULL;
1416
1417     struct stat st;
1418     rc = stat(filename, &st);
1419     if (rc != 0)
1420         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1421     return stat_struct_to_py(&st, filename, 0);
1422 }
1423
1424
1425 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1426 {
1427     int rc;
1428     char *filename;
1429
1430     if (!PyArg_ParseTuple(args, "s", &filename))
1431         return NULL;
1432
1433     struct stat st;
1434     rc = lstat(filename, &st);
1435     if (rc != 0)
1436         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1437     return stat_struct_to_py(&st, filename, 0);
1438 }
1439
1440
1441 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1442 {
1443     int rc, fd;
1444
1445     if (!PyArg_ParseTuple(args, "i", &fd))
1446         return NULL;
1447
1448     struct stat st;
1449     rc = fstat(fd, &st);
1450     if (rc != 0)
1451         return PyErr_SetFromErrno(PyExc_OSError);
1452     return stat_struct_to_py(&st, NULL, fd);
1453 }
1454
1455
1456 #ifdef HAVE_TM_TM_GMTOFF
1457 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1458 {
1459     long long lltime;
1460     time_t ttime;
1461     if (!PyArg_ParseTuple(args, "L", &lltime))
1462         return NULL;
1463     if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1464         return PyErr_Format(PyExc_OverflowError, "time value too large");
1465
1466     struct tm tm;
1467     tzset();
1468     if(localtime_r(&ttime, &tm) == NULL)
1469         return PyErr_SetFromErrno(PyExc_OSError);
1470
1471     // Match the Python struct_time values.
1472     return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1473                          1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1474                          tm.tm_hour, tm.tm_min, tm.tm_sec,
1475                          tm.tm_wday, tm.tm_yday + 1,
1476                          tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1477 }
1478 #endif /* def HAVE_TM_TM_GMTOFF */
1479
1480
1481 #ifdef BUP_MINCORE_BUF_TYPE
1482 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1483 {
1484     Py_buffer src, dest;
1485     PyObject *py_src_n, *py_src_off, *py_dest_off;
1486
1487     if (!PyArg_ParseTuple(args, buf_argf "*OOw*O",
1488                           &src, &py_src_n, &py_src_off,
1489                           &dest, &py_dest_off))
1490         return NULL;
1491
1492     PyObject *result = NULL;
1493
1494     unsigned long long src_n, src_off, dest_off;
1495     if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1496           && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1497           && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1498         goto clean_and_return;
1499
1500     unsigned long long src_region_end;
1501     if (!uadd(&src_region_end, src_off, src_n)) {
1502         result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1503         goto clean_and_return;
1504     }
1505     if (src_region_end > src.len) {
1506         result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1507         goto clean_and_return;
1508     }
1509
1510     unsigned long long dest_size;
1511     if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1512         result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1513         goto clean_and_return;
1514     }
1515     if (dest_off > dest_size) {
1516         result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1517         goto clean_and_return;
1518     }
1519
1520     size_t length;
1521     if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1522         result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1523         goto clean_and_return;
1524     }
1525     int rc = mincore((void *)(src.buf + src_off), src_n,
1526                      (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1527     if (rc != 0) {
1528         result = PyErr_SetFromErrno(PyExc_OSError);
1529         goto clean_and_return;
1530     }
1531     result = Py_BuildValue("O", Py_None);
1532
1533  clean_and_return:
1534     PyBuffer_Release(&src);
1535     PyBuffer_Release(&dest);
1536     return result;
1537 }
1538 #endif /* def BUP_MINCORE_BUF_TYPE */
1539
1540
1541 static PyMethodDef helper_methods[] = {
1542     { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1543       "Write buf excepting zeros at the end. Return trailing zero count." },
1544     { "selftest", selftest, METH_VARARGS,
1545         "Check that the rolling checksum rolls correctly (for unit tests)." },
1546     { "blobbits", blobbits, METH_VARARGS,
1547         "Return the number of bits in the rolling checksum." },
1548     { "splitbuf", splitbuf, METH_VARARGS,
1549         "Split a list of strings based on a rolling checksum." },
1550     { "bitmatch", bitmatch, METH_VARARGS,
1551         "Count the number of matching prefix bits between two strings." },
1552     { "firstword", firstword, METH_VARARGS,
1553         "Return an int corresponding to the first 32 bits of buf." },
1554     { "bloom_contains", bloom_contains, METH_VARARGS,
1555         "Check if a bloom filter of 2^nbits bytes contains an object" },
1556     { "bloom_add", bloom_add, METH_VARARGS,
1557         "Add an object to a bloom filter of 2^nbits bytes" },
1558     { "extract_bits", extract_bits, METH_VARARGS,
1559         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1560     { "merge_into", merge_into, METH_VARARGS,
1561         "Merges a bunch of idx and midx files into a single midx." },
1562     { "write_idx", write_idx, METH_VARARGS,
1563         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1564     { "write_random", write_random, METH_VARARGS,
1565         "Write random bytes to the given file descriptor" },
1566     { "random_sha", random_sha, METH_VARARGS,
1567         "Return a random 20-byte string" },
1568     { "open_noatime", open_noatime, METH_VARARGS,
1569         "open() the given filename for read with O_NOATIME if possible" },
1570     { "fadvise_done", fadvise_done, METH_VARARGS,
1571         "Inform the kernel that we're finished with earlier parts of a file" },
1572 #ifdef BUP_HAVE_FILE_ATTRS
1573     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1574       "Return the Linux attributes for the given file." },
1575 #endif
1576 #ifdef BUP_HAVE_FILE_ATTRS
1577     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1578       "Set the Linux attributes for the given file." },
1579 #endif
1580 #ifdef HAVE_UTIMENSAT
1581     { "bup_utimensat", bup_utimensat, METH_VARARGS,
1582       "Change path timestamps with nanosecond precision (POSIX)." },
1583 #endif
1584 #ifdef HAVE_UTIMES
1585     { "bup_utimes", bup_utimes, METH_VARARGS,
1586       "Change path timestamps with microsecond precision." },
1587 #endif
1588 #ifdef HAVE_LUTIMES
1589     { "bup_lutimes", bup_lutimes, METH_VARARGS,
1590       "Change path timestamps with microsecond precision;"
1591       " don't follow symlinks." },
1592 #endif
1593     { "stat", bup_stat, METH_VARARGS,
1594       "Extended version of stat." },
1595     { "lstat", bup_lstat, METH_VARARGS,
1596       "Extended version of lstat." },
1597     { "fstat", bup_fstat, METH_VARARGS,
1598       "Extended version of fstat." },
1599 #ifdef HAVE_TM_TM_GMTOFF
1600     { "localtime", bup_localtime, METH_VARARGS,
1601       "Return struct_time elements plus the timezone offset and name." },
1602 #endif
1603     { "bytescmp", bup_bytescmp, METH_VARARGS,
1604       "Return a negative value if x < y, zero if equal, positive otherwise."},
1605 #ifdef BUP_MINCORE_BUF_TYPE
1606     { "mincore", bup_mincore, METH_VARARGS,
1607       "For mincore(src, src_n, src_off, dest, dest_off)"
1608       " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1609 #endif
1610     { NULL, NULL, 0, NULL },  // sentinel
1611 };
1612
1613 static int setup_module(PyObject *m)
1614 {
1615     // FIXME: migrate these tests to configure, or at least don't
1616     // possibly crash the whole application.  Check against the type
1617     // we're going to use when passing to python.  Other stat types
1618     // are tested at runtime.
1619     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1620     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1621     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1622     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1623     // Just be sure (relevant when passing timestamps back to Python above).
1624     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1625     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1626
1627     // Originally required by append_sparse_region()
1628     {
1629         off_t probe;
1630         if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1631         {
1632             fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1633             exit(1);
1634         }
1635     }
1636
1637     char *e;
1638 #pragma clang diagnostic push
1639 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1640     {
1641         PyObject *value;
1642         value = INTEGER_TO_PY(INT_MAX);
1643         PyObject_SetAttrString(m, "INT_MAX", value);
1644         Py_DECREF(value);
1645         value = INTEGER_TO_PY(UINT_MAX);
1646         PyObject_SetAttrString(m, "UINT_MAX", value);
1647         Py_DECREF(value);
1648     }
1649 #ifdef HAVE_UTIMENSAT
1650     {
1651         PyObject *value;
1652         value = INTEGER_TO_PY(AT_FDCWD);
1653         PyObject_SetAttrString(m, "AT_FDCWD", value);
1654         Py_DECREF(value);
1655         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1656         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1657         Py_DECREF(value);
1658         value = INTEGER_TO_PY(UTIME_NOW);
1659         PyObject_SetAttrString(m, "UTIME_NOW", value);
1660         Py_DECREF(value);
1661     }
1662 #endif
1663 #ifdef BUP_HAVE_MINCORE_INCORE
1664     {
1665         PyObject *value;
1666         value = INTEGER_TO_PY(MINCORE_INCORE);
1667         PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1668         Py_DECREF(value);
1669     }
1670 #endif
1671 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1672
1673     e = getenv("BUP_FORCE_TTY");
1674     get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1675     unpythonize_argv();
1676     return 1;
1677 }
1678
1679
1680 #if PY_MAJOR_VERSION < 3
1681
1682 PyMODINIT_FUNC init_helpers(void)
1683 {
1684     PyObject *m = Py_InitModule("_helpers", helper_methods);
1685     if (m == NULL)
1686         return;
1687
1688     if (!setup_module(m))
1689     {
1690         Py_DECREF(m);
1691         return;
1692     }
1693 }
1694
1695 # else // PY_MAJOR_VERSION >= 3
1696
1697 static struct PyModuleDef helpers_def = {
1698     PyModuleDef_HEAD_INIT,
1699     "_helpers",
1700     NULL,
1701     sizeof(state_t),
1702     helper_methods,
1703     NULL,
1704     NULL, // helpers_traverse,
1705     NULL, // helpers_clear,
1706     NULL
1707 };
1708
1709 PyMODINIT_FUNC PyInit__helpers(void)
1710 {
1711     PyObject *module = PyModule_Create(&helpers_def);
1712     if (module == NULL)
1713         return NULL;
1714     if (!setup_module(module))
1715     {
1716         Py_DECREF(module);
1717         return NULL;
1718     }
1719     return module;
1720 }
1721
1722 #endif // PY_MAJOR_VERSION >= 3