]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
Use FS_IOC_GETFLAGS/FS_IOC_SETFLAGS directly as the preprocessor guards.
[bup.git] / lib / bup / _helpers.c
1 #define _LARGEFILE64_SOURCE 1
2 #undef NDEBUG
3 #include "../../config/config.h"
4 #include "bupsplit.h"
5 #include <Python.h>
6 #include <assert.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <arpa/inet.h>
10 #include <stdint.h>
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14 #include <stdlib.h>
15 #include <stdio.h>
16
17 #ifdef HAVE_LINUX_FS_H
18 #include <linux/fs.h>
19 #endif
20 #ifdef HAVE_SYS_IOCTL_H
21 #include <sys/ioctl.h>
22 #endif
23
24 static int istty2 = 0;
25
26 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
27 #if __WIN32__ || __CYGWIN__
28
29 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
30 static void unpythonize_argv(void) { }
31
32 #else // not __WIN32__
33
34 // For some reason this isn't declared in Python.h
35 extern void Py_GetArgcArgv(int *argc, char ***argv);
36
37 static void unpythonize_argv(void)
38 {
39     int argc, i;
40     char **argv, *arge;
41     
42     Py_GetArgcArgv(&argc, &argv);
43     
44     for (i = 0; i < argc-1; i++)
45     {
46         if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
47         {
48             // The argv block doesn't work the way we expected; it's unsafe
49             // to mess with it.
50             return;
51         }
52     }
53     
54     arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
55     
56     if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
57     {
58         char *p;
59         size_t len, diff;
60         p = strrchr(argv[1], '/');
61         if (p)
62         {
63             p++;
64             diff = p - argv[0];
65             len = arge - p;
66             memmove(argv[0], p, len);
67             memset(arge - diff, 0, diff);
68             for (i = 0; i < argc; i++)
69                 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
70         }
71     }
72 }
73
74 #endif // not __WIN32__ or __CYGWIN__
75
76
77 static PyObject *selftest(PyObject *self, PyObject *args)
78 {
79     if (!PyArg_ParseTuple(args, ""))
80         return NULL;
81     
82     return Py_BuildValue("i", !bupsplit_selftest());
83 }
84
85
86 static PyObject *blobbits(PyObject *self, PyObject *args)
87 {
88     if (!PyArg_ParseTuple(args, ""))
89         return NULL;
90     return Py_BuildValue("i", BUP_BLOBBITS);
91 }
92
93
94 static PyObject *splitbuf(PyObject *self, PyObject *args)
95 {
96     unsigned char *buf = NULL;
97     int len = 0, out = 0, bits = -1;
98
99     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
100         return NULL;
101     out = bupsplit_find_ofs(buf, len, &bits);
102     if (out) assert(bits >= BUP_BLOBBITS);
103     return Py_BuildValue("ii", out, bits);
104 }
105
106
107 static PyObject *bitmatch(PyObject *self, PyObject *args)
108 {
109     unsigned char *buf1 = NULL, *buf2 = NULL;
110     int len1 = 0, len2 = 0;
111     int byte, bit;
112
113     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
114         return NULL;
115     
116     bit = 0;
117     for (byte = 0; byte < len1 && byte < len2; byte++)
118     {
119         int b1 = buf1[byte], b2 = buf2[byte];
120         if (b1 != b2)
121         {
122             for (bit = 0; bit < 8; bit++)
123                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
124                     break;
125             break;
126         }
127     }
128     
129     return Py_BuildValue("i", byte*8 + bit);
130 }
131
132
133 static PyObject *firstword(PyObject *self, PyObject *args)
134 {
135     unsigned char *buf = NULL;
136     int len = 0;
137     uint32_t v;
138
139     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
140         return NULL;
141     
142     if (len < 4)
143         return NULL;
144     
145     v = ntohl(*(uint32_t *)buf);
146     return PyLong_FromUnsignedLong(v);
147 }
148
149
150 #define BLOOM2_HEADERLEN 16
151
152 typedef struct {
153     uint32_t high;
154     unsigned char low;
155 } bits40_t;
156
157 static void to_bloom_address_bitmask4(const bits40_t *buf,
158         const int nbits, uint64_t *v, unsigned char *bitmask)
159 {
160     int bit;
161     uint64_t raw, mask;
162
163     mask = (1<<nbits) - 1;
164     raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
165     bit = (raw >> (37-nbits)) & 0x7;
166     *v = (raw >> (40-nbits)) & mask;
167     *bitmask = 1 << bit;
168 }
169
170 static void to_bloom_address_bitmask5(const uint32_t *buf,
171         const int nbits, uint32_t *v, unsigned char *bitmask)
172 {
173     int bit;
174     uint32_t raw, mask;
175
176     mask = (1<<nbits) - 1;
177     raw = ntohl(*buf);
178     bit = (raw >> (29-nbits)) & 0x7;
179     *v = (raw >> (32-nbits)) & mask;
180     *bitmask = 1 << bit;
181 }
182
183 #define BLOOM_SET_BIT(name, address, itype, otype) \
184 static void name(unsigned char *bloom, const void *buf, const int nbits)\
185 {\
186     unsigned char bitmask;\
187     otype v;\
188     address((itype *)buf, nbits, &v, &bitmask);\
189     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
190 }
191 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
192 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
193
194
195 #define BLOOM_GET_BIT(name, address, itype, otype) \
196 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
197 {\
198     unsigned char bitmask;\
199     otype v;\
200     address((itype *)buf, nbits, &v, &bitmask);\
201     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
202 }
203 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
204 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
205
206
207 static PyObject *bloom_add(PyObject *self, PyObject *args)
208 {
209     unsigned char *sha = NULL, *bloom = NULL;
210     unsigned char *end;
211     int len = 0, blen = 0, nbits = 0, k = 0;
212
213     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
214         return NULL;
215
216     if (blen < 16+(1<<nbits) || len % 20 != 0)
217         return NULL;
218
219     if (k == 5)
220     {
221         if (nbits > 29)
222             return NULL;
223         for (end = sha + len; sha < end; sha += 20/k)
224             bloom_set_bit5(bloom, sha, nbits);
225     }
226     else if (k == 4)
227     {
228         if (nbits > 37)
229             return NULL;
230         for (end = sha + len; sha < end; sha += 20/k)
231             bloom_set_bit4(bloom, sha, nbits);
232     }
233     else
234         return NULL;
235
236
237     return Py_BuildValue("i", len/20);
238 }
239
240 static PyObject *bloom_contains(PyObject *self, PyObject *args)
241 {
242     unsigned char *sha = NULL, *bloom = NULL;
243     int len = 0, blen = 0, nbits = 0, k = 0;
244     unsigned char *end;
245     int steps;
246
247     if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
248         return NULL;
249
250     if (len != 20)
251         return NULL;
252
253     if (k == 5)
254     {
255         if (nbits > 29)
256             return NULL;
257         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
258             if (!bloom_get_bit5(bloom, sha, nbits))
259                 return Py_BuildValue("Oi", Py_None, steps);
260     }
261     else if (k == 4)
262     {
263         if (nbits > 37)
264             return NULL;
265         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
266             if (!bloom_get_bit4(bloom, sha, nbits))
267                 return Py_BuildValue("Oi", Py_None, steps);
268     }
269     else
270         return NULL;
271
272     return Py_BuildValue("ii", 1, k);
273 }
274
275
276 static uint32_t _extract_bits(unsigned char *buf, int nbits)
277 {
278     uint32_t v, mask;
279
280     mask = (1<<nbits) - 1;
281     v = ntohl(*(uint32_t *)buf);
282     v = (v >> (32-nbits)) & mask;
283     return v;
284 }
285 static PyObject *extract_bits(PyObject *self, PyObject *args)
286 {
287     unsigned char *buf = NULL;
288     int len = 0, nbits = 0;
289
290     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
291         return NULL;
292     
293     if (len < 4)
294         return NULL;
295     
296     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
297 }
298
299
300 struct sha {
301     unsigned char bytes[20];
302 };
303 struct idx {
304     unsigned char *map;
305     struct sha *cur;
306     struct sha *end;
307     uint32_t *cur_name;
308     long bytes;
309     int name_base;
310 };
311
312
313 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
314 {
315     int i;
316     for (i = 0; i < sizeof(struct sha); i++)
317         if (sha1->bytes[i] != sha2->bytes[i])
318             return sha1->bytes[i] - sha2->bytes[i];
319     return 0;
320 }
321
322
323 static void _fix_idx_order(struct idx **idxs, int *last_i)
324 {
325     struct idx *idx;
326     int low, mid, high, c = 0;
327
328     idx = idxs[*last_i];
329     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
330     {
331         idxs[*last_i] = NULL;
332         PyMem_Free(idx);
333         --*last_i;
334         return;
335     }
336     if (*last_i == 0)
337         return;
338
339     low = *last_i-1;
340     mid = *last_i;
341     high = 0;
342     while (low >= high)
343     {
344         mid = (low + high) / 2;
345         c = _cmp_sha(idx->cur, idxs[mid]->cur);
346         if (c < 0)
347             high = mid + 1;
348         else if (c > 0)
349             low = mid - 1;
350         else
351             break;
352     }
353     if (c < 0)
354         ++mid;
355     if (mid == *last_i)
356         return;
357     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
358     idxs[mid] = idx;
359 }
360
361
362 static uint32_t _get_idx_i(struct idx *idx)
363 {
364     if (idx->cur_name == NULL)
365         return idx->name_base;
366     return ntohl(*idx->cur_name) + idx->name_base;
367 }
368
369 #define MIDX4_HEADERLEN 12
370
371 static PyObject *merge_into(PyObject *self, PyObject *args)
372 {
373     PyObject *ilist = NULL;
374     unsigned char *fmap = NULL;
375     struct sha *sha_ptr, *sha_start = NULL;
376     uint32_t *table_ptr, *name_ptr, *name_start;
377     struct idx **idxs = NULL;
378     int flen = 0, bits = 0, i;
379     uint32_t total, count, prefix;
380     int num_i;
381     int last_i;
382
383     if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
384         return NULL;
385
386     num_i = PyList_Size(ilist);
387     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
388
389     for (i = 0; i < num_i; i++)
390     {
391         long len, sha_ofs, name_map_ofs;
392         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
393         PyObject *itup = PyList_GetItem(ilist, i);
394         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
395                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
396             return NULL;
397         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
398         idxs[i]->end = &idxs[i]->cur[len];
399         if (name_map_ofs)
400             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
401         else
402             idxs[i]->cur_name = NULL;
403     }
404     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
405     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
406     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
407
408     last_i = num_i-1;
409     count = 0;
410     prefix = 0;
411     while (last_i >= 0)
412     {
413         struct idx *idx;
414         uint32_t new_prefix;
415         if (count % 102424 == 0 && istty2)
416             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
417                     count*100.0/total, count, total);
418         idx = idxs[last_i];
419         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
420         while (prefix < new_prefix)
421             table_ptr[prefix++] = htonl(count);
422         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
423         *name_ptr++ = htonl(_get_idx_i(idx));
424         ++idx->cur;
425         if (idx->cur_name != NULL)
426             ++idx->cur_name;
427         _fix_idx_order(idxs, &last_i);
428         ++count;
429     }
430     while (prefix < (1<<bits))
431         table_ptr[prefix++] = htonl(count);
432     assert(count == total);
433     assert(prefix == (1<<bits));
434     assert(sha_ptr == sha_start+count);
435     assert(name_ptr == name_start+count);
436
437     PyMem_Free(idxs);
438     return PyLong_FromUnsignedLong(count);
439 }
440
441 // This function should technically be macro'd out if it's going to be used
442 // more than ocasionally.  As of this writing, it'll actually never be called
443 // in real world bup scenarios (because our packs are < MAX_INT bytes).
444 static uint64_t htonll(uint64_t value)
445 {
446     static const int endian_test = 42;
447
448     if (*(char *)&endian_test == endian_test) // LSB-MSB
449         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
450     return value; // already in network byte order MSB-LSB
451 }
452
453 #define PACK_IDX_V2_HEADERLEN 8
454 #define FAN_ENTRIES 256
455
456 static PyObject *write_idx(PyObject *self, PyObject *args)
457 {
458     PyObject *pf = NULL, *idx = NULL;
459     PyObject *part;
460     FILE *f;
461     unsigned char *fmap = NULL;
462     int flen = 0;
463     uint32_t total = 0;
464     uint32_t count;
465     int i, j, ofs64_count;
466     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
467     struct sha *sha_ptr;
468
469     if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
470         return NULL;
471
472     fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
473     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
474     crc_ptr = (uint32_t *)&sha_ptr[total];
475     ofs_ptr = (uint32_t *)&crc_ptr[total];
476     f = PyFile_AsFile(pf);
477
478     count = 0;
479     ofs64_count = 0;
480     for (i = 0; i < FAN_ENTRIES; ++i)
481     {
482         int plen;
483         part = PyList_GET_ITEM(idx, i);
484         PyList_Sort(part);
485         plen = PyList_GET_SIZE(part);
486         count += plen;
487         *fan_ptr++ = htonl(count);
488         for (j = 0; j < plen; ++j)
489         {
490             unsigned char *sha = NULL;
491             int sha_len = 0;
492             uint32_t crc = 0;
493             uint64_t ofs = 0;
494             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
495                                   &sha, &sha_len, &crc, &ofs))
496                 return NULL;
497             if (sha_len != sizeof(struct sha))
498                 return NULL;
499             memcpy(sha_ptr++, sha, sizeof(struct sha));
500             *crc_ptr++ = htonl(crc);
501             if (ofs > 0x7fffffff)
502             {
503                 uint64_t nofs = htonll(ofs);
504                 if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
505                     return PyErr_SetFromErrno(PyExc_OSError);
506                 ofs = 0x80000000 | ofs64_count++;
507             }
508             *ofs_ptr++ = htonl((uint32_t)ofs);
509         }
510     }
511     return PyLong_FromUnsignedLong(count);
512 }
513
514
515 // I would have made this a lower-level function that just fills in a buffer
516 // with random values, and then written those values from python.  But that's
517 // about 20% slower in my tests, and since we typically generate random
518 // numbers for benchmarking other parts of bup, any slowness in generating
519 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
520 // pseudorandom bytes much except for this anyway.
521 static PyObject *write_random(PyObject *self, PyObject *args)
522 {
523     uint32_t buf[1024/4];
524     int fd = -1, seed = 0, verbose = 0;
525     ssize_t ret;
526     long long len = 0, kbytes = 0, written = 0;
527
528     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
529         return NULL;
530     
531     srandom(seed);
532     
533     for (kbytes = 0; kbytes < len/1024; kbytes++)
534     {
535         unsigned i;
536         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
537             buf[i] = random();
538         ret = write(fd, buf, sizeof(buf));
539         if (ret < 0)
540             ret = 0;
541         written += ret;
542         if (ret < (int)sizeof(buf))
543             break;
544         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
545             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
546     }
547     
548     // handle non-multiples of 1024
549     if (len % 1024)
550     {
551         unsigned i;
552         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
553             buf[i] = random();
554         ret = write(fd, buf, len % 1024);
555         if (ret < 0)
556             ret = 0;
557         written += ret;
558     }
559     
560     if (kbytes/1024 > 0)
561         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
562     return Py_BuildValue("L", written);
563 }
564
565
566 static PyObject *random_sha(PyObject *self, PyObject *args)
567 {
568     static int seeded = 0;
569     uint32_t shabuf[20/4];
570     int i;
571     
572     if (!seeded)
573     {
574         assert(sizeof(shabuf) == 20);
575         srandom(time(NULL));
576         seeded = 1;
577     }
578     
579     if (!PyArg_ParseTuple(args, ""))
580         return NULL;
581     
582     memset(shabuf, 0, sizeof(shabuf));
583     for (i=0; i < 20/4; i++)
584         shabuf[i] = random();
585     return Py_BuildValue("s#", shabuf, 20);
586 }
587
588
589 static PyObject *open_noatime(PyObject *self, PyObject *args)
590 {
591     char *filename = NULL;
592     int attrs, attrs_noatime, fd;
593     if (!PyArg_ParseTuple(args, "s", &filename))
594         return NULL;
595     attrs = O_RDONLY;
596 #ifdef O_NOFOLLOW
597     attrs |= O_NOFOLLOW;
598 #endif
599 #ifdef O_LARGEFILE
600     attrs |= O_LARGEFILE;
601 #endif
602     attrs_noatime = attrs;
603 #ifdef O_NOATIME
604     attrs_noatime |= O_NOATIME;
605 #endif
606     fd = open(filename, attrs_noatime);
607     if (fd < 0 && errno == EPERM)
608     {
609         // older Linux kernels would return EPERM if you used O_NOATIME
610         // and weren't the file's owner.  This pointless restriction was
611         // relaxed eventually, but we have to handle it anyway.
612         // (VERY old kernels didn't recognized O_NOATIME, but they would
613         // just harmlessly ignore it, so this branch won't trigger)
614         fd = open(filename, attrs);
615     }
616     if (fd < 0)
617         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
618     return Py_BuildValue("i", fd);
619 }
620
621
622 static PyObject *fadvise_done(PyObject *self, PyObject *args)
623 {
624     int fd = -1;
625     long long ofs = 0;
626     if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
627         return NULL;
628 #ifdef POSIX_FADV_DONTNEED
629     posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
630 #endif    
631     return Py_BuildValue("");
632 }
633
634
635 #ifdef FS_IOC_GETFLAGS
636 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
637 {
638     int rc;
639     unsigned long attr;
640     char *path;
641     int fd;
642
643     if (!PyArg_ParseTuple(args, "s", &path))
644         return NULL;
645
646     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
647     if (fd == -1)
648         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
649
650     attr = 0;
651     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
652     if (rc == -1)
653     {
654         close(fd);
655         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
656     }
657
658     close(fd);
659     return Py_BuildValue("k", attr);
660 }
661 #endif /* def FS_IOC_GETFLAGS */
662
663
664 #ifdef FS_IOC_SETFLAGS
665 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
666 {
667     int rc;
668     unsigned long attr;
669     char *path;
670     int fd;
671
672     if (!PyArg_ParseTuple(args, "sk", &path, &attr))
673         return NULL;
674
675     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
676     if (fd == -1)
677         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
678
679     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
680     if (rc == -1)
681     {
682         close(fd);
683         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
684     }
685
686     close(fd);
687     return Py_BuildValue("O", Py_None);
688 }
689 #endif /* def FS_IOC_SETFLAGS */
690
691
692 #ifdef HAVE_UTIMENSAT
693 #if defined(_ATFILE_SOURCE) \
694   || _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
695 #define HAVE_BUP_UTIMENSAT 1
696
697 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
698 {
699     int rc, dirfd, flags;
700     char *path;
701     long access, access_ns, modification, modification_ns;
702     struct timespec ts[2];
703
704     if (!PyArg_ParseTuple(args, "is((ll)(ll))i",
705                           &dirfd,
706                           &path,
707                           &access, &access_ns,
708                           &modification, &modification_ns,
709                           &flags))
710         return NULL;
711
712     if (isnan(access))
713     {
714         PyErr_SetString(PyExc_ValueError, "access time is NaN");
715         return NULL;
716     }
717     else if (isinf(access))
718     {
719         PyErr_SetString(PyExc_ValueError, "access time is infinite");
720         return NULL;
721     }
722     else if (isnan(modification))
723     {
724         PyErr_SetString(PyExc_ValueError, "modification time is NaN");
725         return NULL;
726     }
727     else if (isinf(modification))
728     {
729         PyErr_SetString(PyExc_ValueError, "modification time is infinite");
730         return NULL;
731     }
732
733     if (isnan(access_ns))
734     {
735         PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
736         return NULL;
737     }
738     else if (isinf(access_ns))
739     {
740         PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
741         return NULL;
742     }
743     else if (isnan(modification_ns))
744     {
745         PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
746         return NULL;
747     }
748     else if (isinf(modification_ns))
749     {
750         PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
751         return NULL;
752     }
753
754     ts[0].tv_sec = access;
755     ts[0].tv_nsec = access_ns;
756     ts[1].tv_sec = modification;
757     ts[1].tv_nsec = modification_ns;
758
759     rc = utimensat(dirfd, path, ts, flags);
760     if (rc != 0)
761         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
762
763     return Py_BuildValue("O", Py_None);
764 }
765
766 #endif /* defined(_ATFILE_SOURCE)
767           || _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L */
768 #endif /* HAVE_UTIMENSAT */
769
770 static PyObject *stat_struct_to_py(const struct stat *st)
771 {
772     /* Enforce the current timespec nanosecond range expectations. */
773     if (st->st_atim.tv_nsec < 0 || st->st_atim.tv_nsec > 999999999)
774     {
775         PyErr_SetString(PyExc_ValueError, "invalid atime timespec nanoseconds");
776         return NULL;
777     }
778     if (st->st_mtim.tv_nsec < 0 || st->st_mtim.tv_nsec > 999999999)
779     {
780         PyErr_SetString(PyExc_ValueError, "invalid mtime timespec nanoseconds");
781         return NULL;
782     }
783     if (st->st_ctim.tv_nsec < 0 || st->st_ctim.tv_nsec > 999999999)
784     {
785         PyErr_SetString(PyExc_ValueError, "invalid ctime timespec nanoseconds");
786         return NULL;
787     }
788
789     return Py_BuildValue("kkkkkkkk(Ll)(Ll)(Ll)",
790                          (unsigned long) st->st_mode,
791                          (unsigned long) st->st_ino,
792                          (unsigned long) st->st_dev,
793                          (unsigned long) st->st_nlink,
794                          (unsigned long) st->st_uid,
795                          (unsigned long) st->st_gid,
796                          (unsigned long) st->st_rdev,
797                          (unsigned long) st->st_size,
798                          (long long) st->st_atime,
799                          (long) st->st_atim.tv_nsec,
800                          (long long) st->st_mtime,
801                          (long) st->st_mtim.tv_nsec,
802                          (long long) st->st_ctime,
803                          (long) st->st_ctim.tv_nsec);
804 }
805
806
807 static PyObject *bup_stat(PyObject *self, PyObject *args)
808 {
809     int rc;
810     char *filename;
811
812     if (!PyArg_ParseTuple(args, "s", &filename))
813         return NULL;
814
815     struct stat st;
816     rc = stat(filename, &st);
817     if (rc != 0)
818         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
819     return stat_struct_to_py(&st);
820 }
821
822
823 static PyObject *bup_lstat(PyObject *self, PyObject *args)
824 {
825     int rc;
826     char *filename;
827
828     if (!PyArg_ParseTuple(args, "s", &filename))
829         return NULL;
830
831     struct stat st;
832     rc = lstat(filename, &st);
833     if (rc != 0)
834         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
835     return stat_struct_to_py(&st);
836 }
837
838
839 static PyObject *bup_fstat(PyObject *self, PyObject *args)
840 {
841     int rc, fd;
842
843     if (!PyArg_ParseTuple(args, "i", &fd))
844         return NULL;
845
846     struct stat st;
847     rc = fstat(fd, &st);
848     if (rc != 0)
849         return PyErr_SetFromErrno(PyExc_OSError);
850     return stat_struct_to_py(&st);
851 }
852
853
854 static PyMethodDef helper_methods[] = {
855     { "selftest", selftest, METH_VARARGS,
856         "Check that the rolling checksum rolls correctly (for unit tests)." },
857     { "blobbits", blobbits, METH_VARARGS,
858         "Return the number of bits in the rolling checksum." },
859     { "splitbuf", splitbuf, METH_VARARGS,
860         "Split a list of strings based on a rolling checksum." },
861     { "bitmatch", bitmatch, METH_VARARGS,
862         "Count the number of matching prefix bits between two strings." },
863     { "firstword", firstword, METH_VARARGS,
864         "Return an int corresponding to the first 32 bits of buf." },
865     { "bloom_contains", bloom_contains, METH_VARARGS,
866         "Check if a bloom filter of 2^nbits bytes contains an object" },
867     { "bloom_add", bloom_add, METH_VARARGS,
868         "Add an object to a bloom filter of 2^nbits bytes" },
869     { "extract_bits", extract_bits, METH_VARARGS,
870         "Take the first 'nbits' bits from 'buf' and return them as an int." },
871     { "merge_into", merge_into, METH_VARARGS,
872         "Merges a bunch of idx and midx files into a single midx." },
873     { "write_idx", write_idx, METH_VARARGS,
874         "Write a PackIdxV2 file from an idx list of lists of tuples" },
875     { "write_random", write_random, METH_VARARGS,
876         "Write random bytes to the given file descriptor" },
877     { "random_sha", random_sha, METH_VARARGS,
878         "Return a random 20-byte string" },
879     { "open_noatime", open_noatime, METH_VARARGS,
880         "open() the given filename for read with O_NOATIME if possible" },
881     { "fadvise_done", fadvise_done, METH_VARARGS,
882         "Inform the kernel that we're finished with earlier parts of a file" },
883 #ifdef FS_IOC_GETFLAGS
884     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
885       "Return the Linux attributes for the given file." },
886 #endif
887 #ifdef FS_IOC_SETFLAGS
888     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
889       "Set the Linux attributes for the given file." },
890 #endif
891 #ifdef HAVE_BUP_UTIMENSAT
892     { "utimensat", bup_utimensat, METH_VARARGS,
893       "Change file timestamps with nanosecond precision." },
894 #endif
895     { "stat", bup_stat, METH_VARARGS,
896       "Extended version of stat." },
897     { "lstat", bup_lstat, METH_VARARGS,
898       "Extended version of lstat." },
899     { "fstat", bup_fstat, METH_VARARGS,
900       "Extended version of fstat." },
901     { NULL, NULL, 0, NULL },  // sentinel
902 };
903
904
905 PyMODINIT_FUNC init_helpers(void)
906 {
907     char *e;
908     PyObject *m = Py_InitModule("_helpers", helper_methods);
909     if (m == NULL)
910         return;
911 #ifdef HAVE_BUP_UTIMENSAT
912     PyModule_AddObject(m, "AT_FDCWD", Py_BuildValue("i", AT_FDCWD));
913     PyModule_AddObject(m, "AT_SYMLINK_NOFOLLOW",
914                        Py_BuildValue("i", AT_SYMLINK_NOFOLLOW));
915 #endif
916     e = getenv("BUP_FORCE_TTY");
917     istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
918     unpythonize_argv();
919 }