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