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