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