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