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