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