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