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