]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
Take additional precautions with the Python/C conversions in _helpers.c.
[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 typedef struct {
174     uint32_t high;
175     unsigned char low;
176 } bits40_t;
177
178 static void to_bloom_address_bitmask4(const bits40_t *buf,
179         const int nbits, uint64_t *v, unsigned char *bitmask)
180 {
181     int bit;
182     uint64_t raw, mask;
183
184     mask = (1<<nbits) - 1;
185     raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
186     bit = (raw >> (37-nbits)) & 0x7;
187     *v = (raw >> (40-nbits)) & mask;
188     *bitmask = 1 << bit;
189 }
190
191 static void to_bloom_address_bitmask5(const uint32_t *buf,
192         const int nbits, uint32_t *v, unsigned char *bitmask)
193 {
194     int bit;
195     uint32_t raw, mask;
196
197     mask = (1<<nbits) - 1;
198     raw = ntohl(*buf);
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, itype, otype) \
205 static void name(unsigned char *bloom, const void *buf, const int nbits)\
206 {\
207     unsigned char bitmask;\
208     otype v;\
209     address((itype *)buf, nbits, &v, &bitmask);\
210     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
211 }
212 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
213 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
214
215
216 #define BLOOM_GET_BIT(name, address, itype, otype) \
217 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
218 {\
219     unsigned char bitmask;\
220     otype v;\
221     address((itype *)buf, nbits, &v, &bitmask);\
222     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
223 }
224 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
225 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, 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 PACK_IDX_V2_HEADERLEN 8
484 #define FAN_ENTRIES 256
485
486 static PyObject *write_idx(PyObject *self, PyObject *args)
487 {
488     PyObject *pf = NULL, *idx = NULL;
489     PyObject *part;
490     FILE *f;
491     unsigned char *fmap = NULL;
492     Py_ssize_t flen = 0;
493     unsigned int total = 0;
494     uint32_t count;
495     int i, j, ofs64_count;
496     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
497     struct sha *sha_ptr;
498
499     if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
500         return NULL;
501
502     fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
503     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
504     crc_ptr = (uint32_t *)&sha_ptr[total];
505     ofs_ptr = (uint32_t *)&crc_ptr[total];
506     f = PyFile_AsFile(pf);
507
508     count = 0;
509     ofs64_count = 0;
510     for (i = 0; i < FAN_ENTRIES; ++i)
511     {
512         int plen;
513         part = PyList_GET_ITEM(idx, i);
514         PyList_Sort(part);
515         plen = PyList_GET_SIZE(part);
516         count += plen;
517         *fan_ptr++ = htonl(count);
518         for (j = 0; j < plen; ++j)
519         {
520             unsigned char *sha = NULL;
521             Py_ssize_t sha_len = 0;
522             unsigned int crc = 0;
523             unsigned PY_LONG_LONG ofs_py = 0;
524             uint64_t ofs;
525             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
526                                   &sha, &sha_len, &crc, &ofs_py))
527                 return NULL;
528             assert(crc <= UINT32_MAX);
529             assert(ofs_py <= UINT64_MAX);
530             ofs = ofs_py;
531             if (sha_len != sizeof(struct sha))
532                 return NULL;
533             memcpy(sha_ptr++, sha, sizeof(struct sha));
534             *crc_ptr++ = htonl(crc);
535             if (ofs > 0x7fffffff)
536             {
537                 const uint64_t nofs = htonll(ofs);
538                 if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
539                     return PyErr_SetFromErrno(PyExc_OSError);
540                 ofs = 0x80000000 | ofs64_count++;
541             }
542             *ofs_ptr++ = htonl((uint32_t)ofs);
543         }
544     }
545     return PyLong_FromUnsignedLong(count);
546 }
547
548
549 // I would have made this a lower-level function that just fills in a buffer
550 // with random values, and then written those values from python.  But that's
551 // about 20% slower in my tests, and since we typically generate random
552 // numbers for benchmarking other parts of bup, any slowness in generating
553 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
554 // pseudorandom bytes much except for this anyway.
555 static PyObject *write_random(PyObject *self, PyObject *args)
556 {
557     uint32_t buf[1024/4];
558     int fd = -1, seed = 0, verbose = 0;
559     ssize_t ret;
560     long long len = 0, kbytes = 0, written = 0;
561
562     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
563         return NULL;
564     
565     srandom(seed);
566     
567     for (kbytes = 0; kbytes < len/1024; kbytes++)
568     {
569         unsigned i;
570         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
571             buf[i] = random();
572         ret = write(fd, buf, sizeof(buf));
573         if (ret < 0)
574             ret = 0;
575         written += ret;
576         if (ret < (int)sizeof(buf))
577             break;
578         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
579             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
580     }
581     
582     // handle non-multiples of 1024
583     if (len % 1024)
584     {
585         unsigned i;
586         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
587             buf[i] = random();
588         ret = write(fd, buf, len % 1024);
589         if (ret < 0)
590             ret = 0;
591         written += ret;
592     }
593     
594     if (kbytes/1024 > 0)
595         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
596     return Py_BuildValue("L", written);
597 }
598
599
600 static PyObject *random_sha(PyObject *self, PyObject *args)
601 {
602     static int seeded = 0;
603     uint32_t shabuf[20/4];
604     int i;
605     
606     if (!seeded)
607     {
608         assert(sizeof(shabuf) == 20);
609         srandom(time(NULL));
610         seeded = 1;
611     }
612     
613     if (!PyArg_ParseTuple(args, ""))
614         return NULL;
615     
616     memset(shabuf, 0, sizeof(shabuf));
617     for (i=0; i < 20/4; i++)
618         shabuf[i] = random();
619     return Py_BuildValue("s#", shabuf, 20);
620 }
621
622
623 static int _open_noatime(const char *filename, int attrs)
624 {
625     int attrs_noatime, fd;
626     attrs |= O_RDONLY;
627 #ifdef O_NOFOLLOW
628     attrs |= O_NOFOLLOW;
629 #endif
630 #ifdef O_LARGEFILE
631     attrs |= O_LARGEFILE;
632 #endif
633     attrs_noatime = attrs;
634 #ifdef O_NOATIME
635     attrs_noatime |= O_NOATIME;
636 #endif
637     fd = open(filename, attrs_noatime);
638     if (fd < 0 && errno == EPERM)
639     {
640         // older Linux kernels would return EPERM if you used O_NOATIME
641         // and weren't the file's owner.  This pointless restriction was
642         // relaxed eventually, but we have to handle it anyway.
643         // (VERY old kernels didn't recognized O_NOATIME, but they would
644         // just harmlessly ignore it, so this branch won't trigger)
645         fd = open(filename, attrs);
646     }
647     return fd;
648 }
649
650
651 static PyObject *open_noatime(PyObject *self, PyObject *args)
652 {
653     char *filename = NULL;
654     int fd;
655     if (!PyArg_ParseTuple(args, "s", &filename))
656         return NULL;
657     fd = _open_noatime(filename, 0);
658     if (fd < 0)
659         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
660     return Py_BuildValue("i", fd);
661 }
662
663
664 static PyObject *fadvise_done(PyObject *self, PyObject *args)
665 {
666     int fd = -1;
667     long long ofs = 0;
668     if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
669         return NULL;
670 #ifdef POSIX_FADV_DONTNEED
671     posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
672 #endif    
673     return Py_BuildValue("");
674 }
675
676
677 #ifdef BUP_HAVE_FILE_ATTRS
678 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
679 {
680     int rc;
681     unsigned long attr;
682     char *path;
683     int fd;
684
685     if (!PyArg_ParseTuple(args, "s", &path))
686         return NULL;
687
688     fd = _open_noatime(path, O_NONBLOCK);
689     if (fd == -1)
690         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
691
692     attr = 0;
693     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
694     if (rc == -1)
695     {
696         close(fd);
697         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
698     }
699
700     close(fd);
701     return Py_BuildValue("k", attr);
702 }
703 #endif /* def BUP_HAVE_FILE_ATTRS */
704
705
706 #ifdef BUP_HAVE_FILE_ATTRS
707 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
708 {
709     int rc;
710     unsigned long orig_attr, attr;
711     char *path;
712     int fd;
713
714     if (!PyArg_ParseTuple(args, "sk", &path, &attr))
715         return NULL;
716
717     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
718     if (fd == -1)
719         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
720
721     // Restrict attr to modifiable flags acdeijstuADST -- see
722     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
723     // in pf.c flags_array[].
724     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
725     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
726     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
727     | FS_TOPDIR_FL | FS_NOCOW_FL;
728
729     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
730     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
731     if (rc == -1)
732     {
733         close(fd);
734         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
735     }
736     attr |= (orig_attr & FS_EXTENT_FL);
737
738     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
739     if (rc == -1)
740     {
741         close(fd);
742         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
743     }
744
745     close(fd);
746     return Py_BuildValue("O", Py_None);
747 }
748 #endif /* def BUP_HAVE_FILE_ATTRS */
749
750
751 #if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES) || defined(HAVE_LUTIMES)
752
753 static int bup_parse_xutime_args(char **path,
754                                  long *access,
755                                  long *access_ns,
756                                  long *modification,
757                                  long *modification_ns,
758                                  PyObject *self, PyObject *args)
759 {
760     if (!PyArg_ParseTuple(args, "s((ll)(ll))",
761                           path,
762                           access, access_ns,
763                           modification, modification_ns))
764         return 0;
765
766     if (isnan(*access))
767     {
768         PyErr_SetString(PyExc_ValueError, "access time is NaN");
769         return 0;
770     }
771     else if (isinf(*access))
772     {
773         PyErr_SetString(PyExc_ValueError, "access time is infinite");
774         return 0;
775     }
776     else if (isnan(*modification))
777     {
778         PyErr_SetString(PyExc_ValueError, "modification time is NaN");
779         return 0;
780     }
781     else if (isinf(*modification))
782     {
783         PyErr_SetString(PyExc_ValueError, "modification time is infinite");
784         return 0;
785     }
786
787     if (isnan(*access_ns))
788     {
789         PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
790         return 0;
791     }
792     else if (isinf(*access_ns))
793     {
794         PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
795         return 0;
796     }
797     else if (isnan(*modification_ns))
798     {
799         PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
800         return 0;
801     }
802     else if (isinf(*modification_ns))
803     {
804         PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
805         return 0;
806     }
807
808     return 1;
809 }
810
811 #endif /* defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES)
812           || defined(HAVE_LUTIMES) */
813
814
815 #ifdef HAVE_UTIMENSAT
816
817 static PyObject *bup_xutime_ns(PyObject *self, PyObject *args,
818                                int follow_symlinks)
819 {
820     int rc;
821     char *path;
822     long access, access_ns, modification, modification_ns;
823     struct timespec ts[2];
824
825     if (!bup_parse_xutime_args(&path, &access, &access_ns,
826                                &modification, &modification_ns,
827                                self, args))
828        return NULL;
829
830     ts[0].tv_sec = access;
831     ts[0].tv_nsec = access_ns;
832     ts[1].tv_sec = modification;
833     ts[1].tv_nsec = modification_ns;
834     rc = utimensat(AT_FDCWD, path, ts,
835                    follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
836     if (rc != 0)
837         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
838
839     return Py_BuildValue("O", Py_None);
840 }
841
842
843 #define BUP_HAVE_BUP_UTIME_NS 1
844 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
845 {
846     return bup_xutime_ns(self, args, 1);
847 }
848
849
850 #define BUP_HAVE_BUP_LUTIME_NS 1
851 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
852 {
853     return bup_xutime_ns(self, args, 0);
854 }
855
856
857 #else /* not defined(HAVE_UTIMENSAT) */
858
859
860 #ifdef HAVE_UTIMES
861 #define BUP_HAVE_BUP_UTIME_NS 1
862 static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
863 {
864     int rc;
865     char *path;
866     long access, access_ns, modification, modification_ns;
867     struct timeval tv[2];
868
869     if (!bup_parse_xutime_args(&path, &access, &access_ns,
870                                &modification, &modification_ns,
871                                self, args))
872        return NULL;
873
874     tv[0].tv_sec = access;
875     tv[0].tv_usec = access_ns / 1000;
876     tv[1].tv_sec = modification;
877     tv[1].tv_usec = modification_ns / 1000;
878     rc = utimes(path, tv);
879     if (rc != 0)
880         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
881
882     return Py_BuildValue("O", Py_None);
883 }
884 #endif /* def HAVE_UTIMES */
885
886
887 #ifdef HAVE_LUTIMES
888 #define BUP_HAVE_BUP_LUTIME_NS 1
889 static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
890 {
891     int rc;
892     char *path;
893     long access, access_ns, modification, modification_ns;
894     struct timeval tv[2];
895
896     if (!bup_parse_xutime_args(&path, &access, &access_ns,
897                                &modification, &modification_ns,
898                                self, args))
899        return NULL;
900
901     tv[0].tv_sec = access;
902     tv[0].tv_usec = access_ns / 1000;
903     tv[1].tv_sec = modification;
904     tv[1].tv_usec = modification_ns / 1000;
905     rc = lutimes(path, tv);
906     if (rc != 0)
907         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
908
909     return Py_BuildValue("O", Py_None);
910 }
911 #endif /* def HAVE_LUTIMES */
912
913
914 #endif /* not defined(HAVE_UTIMENSAT) */
915
916
917 #ifdef HAVE_STAT_ST_ATIM
918 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
919 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
920 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
921 #elif defined HAVE_STAT_ST_ATIMENSEC
922 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
923 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
924 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
925 #else
926 # define BUP_STAT_ATIME_NS(st) 0
927 # define BUP_STAT_MTIME_NS(st) 0
928 # define BUP_STAT_CTIME_NS(st) 0
929 #endif
930
931
932 static void set_invalid_timespec_msg(const char *field,
933                                      const long long sec,
934                                      const long nsec,
935                                      const char *filename,
936                                      int fd)
937 {
938     if (filename != NULL)
939         PyErr_Format(PyExc_ValueError,
940                      "invalid %s timespec (%lld %ld) for file \"%s\"",
941                      field, sec, nsec, filename);
942     else
943         PyErr_Format(PyExc_ValueError,
944                      "invalid %s timespec (%lld %ld) for file descriptor %d",
945                      field, sec, nsec, fd);
946 }
947
948
949 static int normalize_timespec_values(const char *name,
950                                      long long *sec,
951                                      long *nsec,
952                                      const char *filename,
953                                      int fd)
954 {
955     if (*nsec < -999999999 || *nsec > 999999999)
956     {
957         set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
958         return 0;
959     }
960     if (*nsec < 0)
961     {
962         if (*sec == LONG_MIN)
963         {
964             set_invalid_timespec_msg(name, *sec, *nsec, filename, fd);
965             return 0;
966         }
967         *nsec += 1000000000;
968         *sec -= 1;
969     }
970     return 1;
971 }
972
973
974 static PyObject *stat_struct_to_py(const struct stat *st,
975                                    const char *filename,
976                                    int fd)
977 {
978     long long atime = st->st_atime;
979     long long mtime = st->st_mtime;
980     long long ctime = st->st_ctime;
981     long atime_ns = BUP_STAT_ATIME_NS(st);
982     long mtime_ns = BUP_STAT_MTIME_NS(st);
983     long ctime_ns = BUP_STAT_CTIME_NS(st);
984
985     if (!normalize_timespec_values("atime", &atime, &atime_ns, filename, fd))
986         return NULL;
987     if (!normalize_timespec_values("mtime", &mtime, &mtime_ns, filename, fd))
988         return NULL;
989     if (!normalize_timespec_values("ctime", &ctime, &ctime_ns, filename, fd))
990         return NULL;
991
992     return Py_BuildValue("kkkkkkkk(Ll)(Ll)(Ll)",
993                          (unsigned long) st->st_mode,
994                          (unsigned long) st->st_ino,
995                          (unsigned long) st->st_dev,
996                          (unsigned long) st->st_nlink,
997                          (unsigned long) st->st_uid,
998                          (unsigned long) st->st_gid,
999                          (unsigned long) st->st_rdev,
1000                          (unsigned long) st->st_size,
1001                          (long long) atime,
1002                          (long) atime_ns,
1003                          (long long) mtime,
1004                          (long) mtime_ns,
1005                          (long long) ctime,
1006                          (long) ctime_ns);
1007 }
1008
1009
1010 static PyObject *bup_stat(PyObject *self, PyObject *args)
1011 {
1012     int rc;
1013     char *filename;
1014
1015     if (!PyArg_ParseTuple(args, "s", &filename))
1016         return NULL;
1017
1018     struct stat st;
1019     rc = stat(filename, &st);
1020     if (rc != 0)
1021         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1022     return stat_struct_to_py(&st, filename, 0);
1023 }
1024
1025
1026 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1027 {
1028     int rc;
1029     char *filename;
1030
1031     if (!PyArg_ParseTuple(args, "s", &filename))
1032         return NULL;
1033
1034     struct stat st;
1035     rc = lstat(filename, &st);
1036     if (rc != 0)
1037         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1038     return stat_struct_to_py(&st, filename, 0);
1039 }
1040
1041
1042 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1043 {
1044     int rc, fd;
1045
1046     if (!PyArg_ParseTuple(args, "i", &fd))
1047         return NULL;
1048
1049     struct stat st;
1050     rc = fstat(fd, &st);
1051     if (rc != 0)
1052         return PyErr_SetFromErrno(PyExc_OSError);
1053     return stat_struct_to_py(&st, NULL, fd);
1054 }
1055
1056
1057 static PyMethodDef helper_methods[] = {
1058     { "selftest", selftest, METH_VARARGS,
1059         "Check that the rolling checksum rolls correctly (for unit tests)." },
1060     { "blobbits", blobbits, METH_VARARGS,
1061         "Return the number of bits in the rolling checksum." },
1062     { "splitbuf", splitbuf, METH_VARARGS,
1063         "Split a list of strings based on a rolling checksum." },
1064     { "bitmatch", bitmatch, METH_VARARGS,
1065         "Count the number of matching prefix bits between two strings." },
1066     { "firstword", firstword, METH_VARARGS,
1067         "Return an int corresponding to the first 32 bits of buf." },
1068     { "bloom_contains", bloom_contains, METH_VARARGS,
1069         "Check if a bloom filter of 2^nbits bytes contains an object" },
1070     { "bloom_add", bloom_add, METH_VARARGS,
1071         "Add an object to a bloom filter of 2^nbits bytes" },
1072     { "extract_bits", extract_bits, METH_VARARGS,
1073         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1074     { "merge_into", merge_into, METH_VARARGS,
1075         "Merges a bunch of idx and midx files into a single midx." },
1076     { "write_idx", write_idx, METH_VARARGS,
1077         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1078     { "write_random", write_random, METH_VARARGS,
1079         "Write random bytes to the given file descriptor" },
1080     { "random_sha", random_sha, METH_VARARGS,
1081         "Return a random 20-byte string" },
1082     { "open_noatime", open_noatime, METH_VARARGS,
1083         "open() the given filename for read with O_NOATIME if possible" },
1084     { "fadvise_done", fadvise_done, METH_VARARGS,
1085         "Inform the kernel that we're finished with earlier parts of a file" },
1086 #ifdef BUP_HAVE_FILE_ATTRS
1087     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1088       "Return the Linux attributes for the given file." },
1089 #endif
1090 #ifdef BUP_HAVE_FILE_ATTRS
1091     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1092       "Set the Linux attributes for the given file." },
1093 #endif
1094 #ifdef BUP_HAVE_BUP_UTIME_NS
1095     { "bup_utime_ns", bup_utime_ns, METH_VARARGS,
1096       "Change path timestamps with up to nanosecond precision." },
1097 #endif
1098 #ifdef BUP_HAVE_BUP_LUTIME_NS
1099     { "bup_lutime_ns", bup_lutime_ns, METH_VARARGS,
1100       "Change path timestamps with up to nanosecond precision;"
1101       " don't follow symlinks." },
1102 #endif
1103     { "stat", bup_stat, METH_VARARGS,
1104       "Extended version of stat." },
1105     { "lstat", bup_lstat, METH_VARARGS,
1106       "Extended version of lstat." },
1107     { "fstat", bup_fstat, METH_VARARGS,
1108       "Extended version of fstat." },
1109     { NULL, NULL, 0, NULL },  // sentinel
1110 };
1111
1112
1113 PyMODINIT_FUNC init_helpers(void)
1114 {
1115     char *e;
1116     PyObject *m = Py_InitModule("_helpers", helper_methods);
1117     if (m == NULL)
1118         return;
1119     e = getenv("BUP_FORCE_TTY");
1120     istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1121     unpythonize_argv();
1122 }