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