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