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