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