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