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