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