]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
87e8b82755d581762db9d9943fc822ed4cf5fb77
[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 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
746 {
747     return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
748 }
749
750
751 struct idx {
752     unsigned char *map;
753     struct sha *cur;
754     struct sha *end;
755     uint32_t *cur_name;
756     Py_ssize_t bytes;
757     int name_base;
758 };
759
760 static void _fix_idx_order(struct idx **idxs, int *last_i)
761 {
762     struct idx *idx;
763     int low, mid, high, c = 0;
764
765     idx = idxs[*last_i];
766     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
767     {
768         idxs[*last_i] = NULL;
769         PyMem_Free(idx);
770         --*last_i;
771         return;
772     }
773     if (*last_i == 0)
774         return;
775
776     low = *last_i-1;
777     mid = *last_i;
778     high = 0;
779     while (low >= high)
780     {
781         mid = (low + high) / 2;
782         c = _cmp_sha(idx->cur, idxs[mid]->cur);
783         if (c < 0)
784             high = mid + 1;
785         else if (c > 0)
786             low = mid - 1;
787         else
788             break;
789     }
790     if (c < 0)
791         ++mid;
792     if (mid == *last_i)
793         return;
794     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
795     idxs[mid] = idx;
796 }
797
798
799 static uint32_t _get_idx_i(struct idx *idx)
800 {
801     if (idx->cur_name == NULL)
802         return idx->name_base;
803     return ntohl(*idx->cur_name) + idx->name_base;
804 }
805
806 #define MIDX4_HEADERLEN 12
807
808 static PyObject *merge_into(PyObject *self, PyObject *args)
809 {
810     PyObject *py_total, *ilist = NULL;
811     unsigned char *fmap = NULL;
812     struct sha *sha_ptr, *sha_start = NULL;
813     uint32_t *table_ptr, *name_ptr, *name_start;
814     struct idx **idxs = NULL;
815     Py_ssize_t flen = 0;
816     int bits = 0, i;
817     unsigned int total;
818     uint32_t count, prefix;
819     int num_i;
820     int last_i;
821
822     if (!PyArg_ParseTuple(args, "w#iOO",
823                           &fmap, &flen, &bits, &py_total, &ilist))
824         return NULL;
825
826     if (!bup_uint_from_py(&total, py_total, "total"))
827         return NULL;
828
829     num_i = PyList_Size(ilist);
830     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
831
832     for (i = 0; i < num_i; i++)
833     {
834         long len, sha_ofs, name_map_ofs;
835         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
836         PyObject *itup = PyList_GetItem(ilist, i);
837         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
838                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
839             return NULL;
840         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
841         idxs[i]->end = &idxs[i]->cur[len];
842         if (name_map_ofs)
843             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
844         else
845             idxs[i]->cur_name = NULL;
846     }
847     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
848     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
849     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
850
851     last_i = num_i-1;
852     count = 0;
853     prefix = 0;
854     while (last_i >= 0)
855     {
856         struct idx *idx;
857         uint32_t new_prefix;
858         if (count % 102424 == 0 && get_state(self)->istty2)
859             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
860                     count*100.0/total, count, total);
861         idx = idxs[last_i];
862         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
863         while (prefix < new_prefix)
864             table_ptr[prefix++] = htonl(count);
865         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
866         *name_ptr++ = htonl(_get_idx_i(idx));
867         ++idx->cur;
868         if (idx->cur_name != NULL)
869             ++idx->cur_name;
870         _fix_idx_order(idxs, &last_i);
871         ++count;
872     }
873     while (prefix < (1<<bits))
874         table_ptr[prefix++] = htonl(count);
875     assert(count == total);
876     assert(prefix == (1<<bits));
877     assert(sha_ptr == sha_start+count);
878     assert(name_ptr == name_start+count);
879
880     PyMem_Free(idxs);
881     return PyLong_FromUnsignedLong(count);
882 }
883
884 #define FAN_ENTRIES 256
885
886 static PyObject *write_idx(PyObject *self, PyObject *args)
887 {
888     char *filename = NULL;
889     PyObject *py_total, *idx = NULL;
890     PyObject *part;
891     unsigned char *fmap = NULL;
892     Py_ssize_t flen = 0;
893     unsigned int total = 0;
894     uint32_t count;
895     int i, j, ofs64_count;
896     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
897     uint64_t *ofs64_ptr;
898     struct sha *sha_ptr;
899
900     if (!PyArg_ParseTuple(args, "sw#OO",
901                           &filename, &fmap, &flen, &idx, &py_total))
902         return NULL;
903
904     if (!bup_uint_from_py(&total, py_total, "total"))
905         return NULL;
906
907     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
908         return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
909                              FAN_ENTRIES);
910
911     const char idx_header[] = "\377tOc\0\0\0\002";
912     memcpy (fmap, idx_header, sizeof(idx_header) - 1);
913
914     fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
915     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
916     crc_ptr = (uint32_t *)&sha_ptr[total];
917     ofs_ptr = (uint32_t *)&crc_ptr[total];
918     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
919
920     count = 0;
921     ofs64_count = 0;
922     for (i = 0; i < FAN_ENTRIES; ++i)
923     {
924         int plen;
925         part = PyList_GET_ITEM(idx, i);
926         PyList_Sort(part);
927         plen = PyList_GET_SIZE(part);
928         count += plen;
929         *fan_ptr++ = htonl(count);
930         for (j = 0; j < plen; ++j)
931         {
932             unsigned char *sha = NULL;
933             Py_ssize_t sha_len = 0;
934             PyObject *crc_py, *ofs_py;
935             unsigned int crc;
936             unsigned PY_LONG_LONG ofs_ull;
937             uint64_t ofs;
938             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
939                                   &sha, &sha_len, &crc_py, &ofs_py))
940                 return NULL;
941             if(!bup_uint_from_py(&crc, crc_py, "crc"))
942                 return NULL;
943             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
944                 return NULL;
945             assert(crc <= UINT32_MAX);
946             assert(ofs_ull <= UINT64_MAX);
947             ofs = ofs_ull;
948             if (sha_len != sizeof(struct sha))
949                 return NULL;
950             memcpy(sha_ptr++, sha, sizeof(struct sha));
951             *crc_ptr++ = htonl(crc);
952             if (ofs > 0x7fffffff)
953             {
954                 *ofs64_ptr++ = htonll(ofs);
955                 ofs = 0x80000000 | ofs64_count++;
956             }
957             *ofs_ptr++ = htonl((uint32_t)ofs);
958         }
959     }
960
961     int rc = msync(fmap, flen, MS_ASYNC);
962     if (rc != 0)
963         return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
964
965     return PyLong_FromUnsignedLong(count);
966 }
967
968
969 // I would have made this a lower-level function that just fills in a buffer
970 // with random values, and then written those values from python.  But that's
971 // about 20% slower in my tests, and since we typically generate random
972 // numbers for benchmarking other parts of bup, any slowness in generating
973 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
974 // pseudorandom bytes much except for this anyway.
975 static PyObject *write_random(PyObject *self, PyObject *args)
976 {
977     uint32_t buf[1024/4];
978     int fd = -1, seed = 0, verbose = 0;
979     ssize_t ret;
980     long long len = 0, kbytes = 0, written = 0;
981
982     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
983         return NULL;
984     
985     srandom(seed);
986     
987     for (kbytes = 0; kbytes < len/1024; kbytes++)
988     {
989         unsigned i;
990         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
991             buf[i] = random();
992         ret = write(fd, buf, sizeof(buf));
993         if (ret < 0)
994             ret = 0;
995         written += ret;
996         if (ret < (int)sizeof(buf))
997             break;
998         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
999             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1000     }
1001     
1002     // handle non-multiples of 1024
1003     if (len % 1024)
1004     {
1005         unsigned i;
1006         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1007             buf[i] = random();
1008         ret = write(fd, buf, len % 1024);
1009         if (ret < 0)
1010             ret = 0;
1011         written += ret;
1012     }
1013     
1014     if (kbytes/1024 > 0)
1015         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1016     return Py_BuildValue("L", written);
1017 }
1018
1019
1020 static PyObject *random_sha(PyObject *self, PyObject *args)
1021 {
1022     static int seeded = 0;
1023     uint32_t shabuf[20/4];
1024     int i;
1025     
1026     if (!seeded)
1027     {
1028         assert(sizeof(shabuf) == 20);
1029         srandom(time(NULL));
1030         seeded = 1;
1031     }
1032     
1033     if (!PyArg_ParseTuple(args, ""))
1034         return NULL;
1035     
1036     memset(shabuf, 0, sizeof(shabuf));
1037     for (i=0; i < 20/4; i++)
1038         shabuf[i] = random();
1039     return Py_BuildValue("s#", shabuf, 20);
1040 }
1041
1042
1043 static int _open_noatime(const char *filename, int attrs)
1044 {
1045     int attrs_noatime, fd;
1046     attrs |= O_RDONLY;
1047 #ifdef O_NOFOLLOW
1048     attrs |= O_NOFOLLOW;
1049 #endif
1050 #ifdef O_LARGEFILE
1051     attrs |= O_LARGEFILE;
1052 #endif
1053     attrs_noatime = attrs;
1054 #ifdef O_NOATIME
1055     attrs_noatime |= O_NOATIME;
1056 #endif
1057     fd = open(filename, attrs_noatime);
1058     if (fd < 0 && errno == EPERM)
1059     {
1060         // older Linux kernels would return EPERM if you used O_NOATIME
1061         // and weren't the file's owner.  This pointless restriction was
1062         // relaxed eventually, but we have to handle it anyway.
1063         // (VERY old kernels didn't recognized O_NOATIME, but they would
1064         // just harmlessly ignore it, so this branch won't trigger)
1065         fd = open(filename, attrs);
1066     }
1067     return fd;
1068 }
1069
1070
1071 static PyObject *open_noatime(PyObject *self, PyObject *args)
1072 {
1073     char *filename = NULL;
1074     int fd;
1075     if (!PyArg_ParseTuple(args, "s", &filename))
1076         return NULL;
1077     fd = _open_noatime(filename, 0);
1078     if (fd < 0)
1079         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1080     return Py_BuildValue("i", fd);
1081 }
1082
1083
1084 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1085 {
1086     int fd = -1;
1087     long long llofs, lllen = 0;
1088     if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1089         return NULL;
1090     off_t ofs, len;
1091     if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1092         return PyErr_Format(PyExc_OverflowError,
1093                             "fadvise offset overflows off_t");
1094     if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1095         return PyErr_Format(PyExc_OverflowError,
1096                             "fadvise length overflows off_t");
1097 #ifdef POSIX_FADV_DONTNEED
1098     posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1099 #endif    
1100     return Py_BuildValue("");
1101 }
1102
1103
1104 // Currently the Linux kernel and FUSE disagree over the type for
1105 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS.  The kernel actually uses int,
1106 // but FUSE chose long (matching the declaration in linux/fs.h).  So
1107 // if you use int, and then traverse a FUSE filesystem, you may
1108 // corrupt the stack.  But if you use long, then you may get invalid
1109 // results on big-endian systems.
1110 //
1111 // For now, we just use long, and then disable Linux attrs entirely
1112 // (with a warning) in helpers.py on systems that are affected.
1113
1114 #ifdef BUP_HAVE_FILE_ATTRS
1115 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1116 {
1117     int rc;
1118     unsigned long attr;
1119     char *path;
1120     int fd;
1121
1122     if (!PyArg_ParseTuple(args, "s", &path))
1123         return NULL;
1124
1125     fd = _open_noatime(path, O_NONBLOCK);
1126     if (fd == -1)
1127         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1128
1129     attr = 0;  // Handle int/long mismatch (see above)
1130     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1131     if (rc == -1)
1132     {
1133         close(fd);
1134         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1135     }
1136     close(fd);
1137     assert(attr <= UINT_MAX);  // Kernel type is actually int
1138     return PyLong_FromUnsignedLong(attr);
1139 }
1140 #endif /* def BUP_HAVE_FILE_ATTRS */
1141
1142
1143
1144 #ifdef BUP_HAVE_FILE_ATTRS
1145 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1146 {
1147     int rc;
1148     unsigned long orig_attr;
1149     unsigned int attr;
1150     char *path;
1151     PyObject *py_attr;
1152     int fd;
1153
1154     if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1155         return NULL;
1156
1157     if (!bup_uint_from_py(&attr, py_attr, "attr"))
1158         return NULL;
1159
1160     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1161     if (fd == -1)
1162         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1163
1164     // Restrict attr to modifiable flags acdeijstuADST -- see
1165     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
1166     // in pf.c flags_array[].
1167     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1168     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1169     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1170     | FS_TOPDIR_FL | FS_NOCOW_FL;
1171
1172     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1173     orig_attr = 0; // Handle int/long mismatch (see above)
1174     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1175     if (rc == -1)
1176     {
1177         close(fd);
1178         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1179     }
1180     assert(orig_attr <= UINT_MAX);  // Kernel type is actually int
1181     attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1182
1183     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1184     if (rc == -1)
1185     {
1186         close(fd);
1187         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1188     }
1189
1190     close(fd);
1191     return Py_BuildValue("O", Py_None);
1192 }
1193 #endif /* def BUP_HAVE_FILE_ATTRS */
1194
1195
1196 #ifndef HAVE_UTIMENSAT
1197 #ifndef HAVE_UTIMES
1198 #error "cannot find utimensat or utimes()"
1199 #endif
1200 #ifndef HAVE_LUTIMES
1201 #error "cannot find utimensat or lutimes()"
1202 #endif
1203 #endif
1204
1205 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1206     ({                                                     \
1207         int result = 0;                                                 \
1208         *(overflow) = 0;                                                \
1209         const long long lltmp = PyLong_AsLongLong(pylong);              \
1210         if (lltmp == -1 && PyErr_Occurred())                            \
1211         {                                                               \
1212             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
1213             {                                                           \
1214                 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1215                 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1216                 {                                                       \
1217                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
1218                     {                                                   \
1219                         PyErr_Clear();                                  \
1220                         *(overflow) = 1;                                \
1221                     }                                                   \
1222                 }                                                       \
1223                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
1224                     result = 1;                                         \
1225                 else                                                    \
1226                     *(overflow) = 1;                                    \
1227             }                                                           \
1228         }                                                               \
1229         else                                                            \
1230         {                                                               \
1231             if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
1232                 result = 1;                                             \
1233             else                                                        \
1234                 *(overflow) = 1;                                        \
1235         }                                                               \
1236         result;                                                         \
1237         })
1238
1239
1240 #ifdef HAVE_UTIMENSAT
1241
1242 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1243 {
1244     int rc;
1245     int fd, flag;
1246     char *path;
1247     PyObject *access_py, *modification_py;
1248     struct timespec ts[2];
1249
1250     if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1251                           &fd,
1252                           &path,
1253                           &access_py, &(ts[0].tv_nsec),
1254                           &modification_py, &(ts[1].tv_nsec),
1255                           &flag))
1256         return NULL;
1257
1258     int overflow;
1259     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1260     {
1261         if (overflow)
1262             PyErr_SetString(PyExc_ValueError,
1263                             "unable to convert access time seconds for utimensat");
1264         return NULL;
1265     }
1266     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1267     {
1268         if (overflow)
1269             PyErr_SetString(PyExc_ValueError,
1270                             "unable to convert modification time seconds for utimensat");
1271         return NULL;
1272     }
1273     rc = utimensat(fd, path, ts, flag);
1274     if (rc != 0)
1275         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1276
1277     return Py_BuildValue("O", Py_None);
1278 }
1279
1280 #endif /* def HAVE_UTIMENSAT */
1281
1282
1283 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1284
1285 static int bup_parse_xutimes_args(char **path,
1286                                   struct timeval tv[2],
1287                                   PyObject *args)
1288 {
1289     PyObject *access_py, *modification_py;
1290     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1291
1292     if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1293                           path,
1294                           &access_py, &access_us,
1295                           &modification_py, &modification_us))
1296         return 0;
1297
1298     int overflow;
1299     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1300     {
1301         if (overflow)
1302             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1303         return 0;
1304     }
1305     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1306     {
1307         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1308         return 0;
1309     }
1310     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1311     {
1312         if (overflow)
1313             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1314         return 0;
1315     }
1316     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1317     {
1318         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1319         return 0;
1320     }
1321     return 1;
1322 }
1323
1324 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1325
1326
1327 #ifdef HAVE_UTIMES
1328 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1329 {
1330     char *path;
1331     struct timeval tv[2];
1332     if (!bup_parse_xutimes_args(&path, tv, args))
1333         return NULL;
1334     int rc = utimes(path, tv);
1335     if (rc != 0)
1336         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1337     return Py_BuildValue("O", Py_None);
1338 }
1339 #endif /* def HAVE_UTIMES */
1340
1341
1342 #ifdef HAVE_LUTIMES
1343 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1344 {
1345     char *path;
1346     struct timeval tv[2];
1347     if (!bup_parse_xutimes_args(&path, tv, args))
1348         return NULL;
1349     int rc = lutimes(path, tv);
1350     if (rc != 0)
1351         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1352
1353     return Py_BuildValue("O", Py_None);
1354 }
1355 #endif /* def HAVE_LUTIMES */
1356
1357
1358 #ifdef HAVE_STAT_ST_ATIM
1359 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1360 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1361 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1362 #elif defined HAVE_STAT_ST_ATIMENSEC
1363 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1364 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1365 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1366 #else
1367 # define BUP_STAT_ATIME_NS(st) 0
1368 # define BUP_STAT_MTIME_NS(st) 0
1369 # define BUP_STAT_CTIME_NS(st) 0
1370 #endif
1371
1372
1373 #pragma clang diagnostic push
1374 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1375
1376 static PyObject *stat_struct_to_py(const struct stat *st,
1377                                    const char *filename,
1378                                    int fd)
1379 {
1380     // We can check the known (via POSIX) signed and unsigned types at
1381     // compile time, but not (easily) the unspecified types, so handle
1382     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1383     // long.
1384     return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1385                          INTEGER_TO_PY(st->st_mode),
1386                          (unsigned PY_LONG_LONG) st->st_ino,
1387                          INTEGER_TO_PY(st->st_dev),
1388                          INTEGER_TO_PY(st->st_nlink),
1389                          INTEGER_TO_PY(st->st_uid),
1390                          INTEGER_TO_PY(st->st_gid),
1391                          INTEGER_TO_PY(st->st_rdev),
1392                          (PY_LONG_LONG) st->st_size,
1393                          INTEGER_TO_PY(st->st_atime),
1394                          (long) BUP_STAT_ATIME_NS(st),
1395                          INTEGER_TO_PY(st->st_mtime),
1396                          (long) BUP_STAT_MTIME_NS(st),
1397                          INTEGER_TO_PY(st->st_ctime),
1398                          (long) BUP_STAT_CTIME_NS(st));
1399 }
1400
1401 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1402
1403 static PyObject *bup_stat(PyObject *self, PyObject *args)
1404 {
1405     int rc;
1406     char *filename;
1407
1408     if (!PyArg_ParseTuple(args, "s", &filename))
1409         return NULL;
1410
1411     struct stat st;
1412     rc = stat(filename, &st);
1413     if (rc != 0)
1414         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1415     return stat_struct_to_py(&st, filename, 0);
1416 }
1417
1418
1419 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1420 {
1421     int rc;
1422     char *filename;
1423
1424     if (!PyArg_ParseTuple(args, "s", &filename))
1425         return NULL;
1426
1427     struct stat st;
1428     rc = lstat(filename, &st);
1429     if (rc != 0)
1430         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1431     return stat_struct_to_py(&st, filename, 0);
1432 }
1433
1434
1435 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1436 {
1437     int rc, fd;
1438
1439     if (!PyArg_ParseTuple(args, "i", &fd))
1440         return NULL;
1441
1442     struct stat st;
1443     rc = fstat(fd, &st);
1444     if (rc != 0)
1445         return PyErr_SetFromErrno(PyExc_OSError);
1446     return stat_struct_to_py(&st, NULL, fd);
1447 }
1448
1449
1450 #ifdef HAVE_TM_TM_GMTOFF
1451 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1452 {
1453     long long lltime;
1454     time_t ttime;
1455     if (!PyArg_ParseTuple(args, "L", &lltime))
1456         return NULL;
1457     if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1458         return PyErr_Format(PyExc_OverflowError, "time value too large");
1459
1460     struct tm tm;
1461     tzset();
1462     if(localtime_r(&ttime, &tm) == NULL)
1463         return PyErr_SetFromErrno(PyExc_OSError);
1464
1465     // Match the Python struct_time values.
1466     return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1467                          1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1468                          tm.tm_hour, tm.tm_min, tm.tm_sec,
1469                          tm.tm_wday, tm.tm_yday + 1,
1470                          tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1471 }
1472 #endif /* def HAVE_TM_TM_GMTOFF */
1473
1474
1475 #ifdef BUP_MINCORE_BUF_TYPE
1476 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1477 {
1478     Py_buffer src, dest;
1479     PyObject *py_src_n, *py_src_off, *py_dest_off;
1480
1481     if (!PyArg_ParseTuple(args, buf_argf "*OOw*O",
1482                           &src, &py_src_n, &py_src_off,
1483                           &dest, &py_dest_off))
1484         return NULL;
1485
1486     PyObject *result = NULL;
1487
1488     unsigned long long src_n, src_off, dest_off;
1489     if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1490           && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1491           && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1492         goto clean_and_return;
1493
1494     unsigned long long src_region_end;
1495     if (!uadd(&src_region_end, src_off, src_n)) {
1496         result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1497         goto clean_and_return;
1498     }
1499     if (src_region_end > src.len) {
1500         result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1501         goto clean_and_return;
1502     }
1503
1504     unsigned long long dest_size;
1505     if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1506         result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1507         goto clean_and_return;
1508     }
1509     if (dest_off > dest_size) {
1510         result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1511         goto clean_and_return;
1512     }
1513
1514     size_t length;
1515     if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1516         result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1517         goto clean_and_return;
1518     }
1519     int rc = mincore((void *)(src.buf + src_off), src_n,
1520                      (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1521     if (rc != 0) {
1522         result = PyErr_SetFromErrno(PyExc_OSError);
1523         goto clean_and_return;
1524     }
1525     result = Py_BuildValue("O", Py_None);
1526
1527  clean_and_return:
1528     PyBuffer_Release(&src);
1529     PyBuffer_Release(&dest);
1530     return result;
1531 }
1532 #endif /* def BUP_MINCORE_BUF_TYPE */
1533
1534
1535 static PyMethodDef helper_methods[] = {
1536     { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1537       "Write buf excepting zeros at the end. Return trailing zero count." },
1538     { "selftest", selftest, METH_VARARGS,
1539         "Check that the rolling checksum rolls correctly (for unit tests)." },
1540     { "blobbits", blobbits, METH_VARARGS,
1541         "Return the number of bits in the rolling checksum." },
1542     { "splitbuf", splitbuf, METH_VARARGS,
1543         "Split a list of strings based on a rolling checksum." },
1544     { "bitmatch", bitmatch, METH_VARARGS,
1545         "Count the number of matching prefix bits between two strings." },
1546     { "firstword", firstword, METH_VARARGS,
1547         "Return an int corresponding to the first 32 bits of buf." },
1548     { "bloom_contains", bloom_contains, METH_VARARGS,
1549         "Check if a bloom filter of 2^nbits bytes contains an object" },
1550     { "bloom_add", bloom_add, METH_VARARGS,
1551         "Add an object to a bloom filter of 2^nbits bytes" },
1552     { "extract_bits", extract_bits, METH_VARARGS,
1553         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1554     { "merge_into", merge_into, METH_VARARGS,
1555         "Merges a bunch of idx and midx files into a single midx." },
1556     { "write_idx", write_idx, METH_VARARGS,
1557         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1558     { "write_random", write_random, METH_VARARGS,
1559         "Write random bytes to the given file descriptor" },
1560     { "random_sha", random_sha, METH_VARARGS,
1561         "Return a random 20-byte string" },
1562     { "open_noatime", open_noatime, METH_VARARGS,
1563         "open() the given filename for read with O_NOATIME if possible" },
1564     { "fadvise_done", fadvise_done, METH_VARARGS,
1565         "Inform the kernel that we're finished with earlier parts of a file" },
1566 #ifdef BUP_HAVE_FILE_ATTRS
1567     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1568       "Return the Linux attributes for the given file." },
1569 #endif
1570 #ifdef BUP_HAVE_FILE_ATTRS
1571     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1572       "Set the Linux attributes for the given file." },
1573 #endif
1574 #ifdef HAVE_UTIMENSAT
1575     { "bup_utimensat", bup_utimensat, METH_VARARGS,
1576       "Change path timestamps with nanosecond precision (POSIX)." },
1577 #endif
1578 #ifdef HAVE_UTIMES
1579     { "bup_utimes", bup_utimes, METH_VARARGS,
1580       "Change path timestamps with microsecond precision." },
1581 #endif
1582 #ifdef HAVE_LUTIMES
1583     { "bup_lutimes", bup_lutimes, METH_VARARGS,
1584       "Change path timestamps with microsecond precision;"
1585       " don't follow symlinks." },
1586 #endif
1587     { "stat", bup_stat, METH_VARARGS,
1588       "Extended version of stat." },
1589     { "lstat", bup_lstat, METH_VARARGS,
1590       "Extended version of lstat." },
1591     { "fstat", bup_fstat, METH_VARARGS,
1592       "Extended version of fstat." },
1593 #ifdef HAVE_TM_TM_GMTOFF
1594     { "localtime", bup_localtime, METH_VARARGS,
1595       "Return struct_time elements plus the timezone offset and name." },
1596 #endif
1597     { "bytescmp", bup_bytescmp, METH_VARARGS,
1598       "Return a negative value if x < y, zero if equal, positive otherwise."},
1599 #ifdef BUP_MINCORE_BUF_TYPE
1600     { "mincore", bup_mincore, METH_VARARGS,
1601       "For mincore(src, src_n, src_off, dest, dest_off)"
1602       " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1603 #endif
1604     { NULL, NULL, 0, NULL },  // sentinel
1605 };
1606
1607 static int setup_module(PyObject *m)
1608 {
1609     // FIXME: migrate these tests to configure, or at least don't
1610     // possibly crash the whole application.  Check against the type
1611     // we're going to use when passing to python.  Other stat types
1612     // are tested at runtime.
1613     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1614     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1615     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1616     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1617     // Just be sure (relevant when passing timestamps back to Python above).
1618     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1619     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1620
1621     // Originally required by append_sparse_region()
1622     {
1623         off_t probe;
1624         if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1625         {
1626             fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1627             exit(1);
1628         }
1629     }
1630
1631     char *e;
1632 #pragma clang diagnostic push
1633 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1634     {
1635         PyObject *value;
1636         value = INTEGER_TO_PY(INT_MAX);
1637         PyObject_SetAttrString(m, "INT_MAX", value);
1638         Py_DECREF(value);
1639         value = INTEGER_TO_PY(UINT_MAX);
1640         PyObject_SetAttrString(m, "UINT_MAX", value);
1641         Py_DECREF(value);
1642     }
1643 #ifdef HAVE_UTIMENSAT
1644     {
1645         PyObject *value;
1646         value = INTEGER_TO_PY(AT_FDCWD);
1647         PyObject_SetAttrString(m, "AT_FDCWD", value);
1648         Py_DECREF(value);
1649         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1650         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1651         Py_DECREF(value);
1652         value = INTEGER_TO_PY(UTIME_NOW);
1653         PyObject_SetAttrString(m, "UTIME_NOW", value);
1654         Py_DECREF(value);
1655     }
1656 #endif
1657 #ifdef BUP_HAVE_MINCORE_INCORE
1658     {
1659         PyObject *value;
1660         value = INTEGER_TO_PY(MINCORE_INCORE);
1661         PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1662         Py_DECREF(value);
1663     }
1664 #endif
1665 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1666
1667     e = getenv("BUP_FORCE_TTY");
1668     get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1669     unpythonize_argv();
1670     return 1;
1671 }
1672
1673
1674 #if PY_MAJOR_VERSION < 3
1675
1676 PyMODINIT_FUNC init_helpers(void)
1677 {
1678     PyObject *m = Py_InitModule("_helpers", helper_methods);
1679     if (m == NULL)
1680         return;
1681
1682     if (!setup_module(m))
1683     {
1684         Py_DECREF(m);
1685         return;
1686     }
1687 }
1688
1689 # else // PY_MAJOR_VERSION >= 3
1690
1691 static struct PyModuleDef helpers_def = {
1692     PyModuleDef_HEAD_INIT,
1693     "_helpers",
1694     NULL,
1695     sizeof(state_t),
1696     helper_methods,
1697     NULL,
1698     NULL, // helpers_traverse,
1699     NULL, // helpers_clear,
1700     NULL
1701 };
1702
1703 PyMODINIT_FUNC PyInit__helpers(void)
1704 {
1705     PyObject *module = PyModule_Create(&helpers_def);
1706     if (module == NULL)
1707         return NULL;
1708     if (!setup_module(module))
1709     {
1710         Py_DECREF(module);
1711         return NULL;
1712     }
1713     return module;
1714 }
1715
1716 #endif // PY_MAJOR_VERSION >= 3