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