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 <arpa/inet.h>
11 #include <assert.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <grp.h>
15 #include <pwd.h>
16 #include <stddef.h>
17 #include <stdint.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
21
22 #ifdef HAVE_SYS_MMAN_H
23 #include <sys/mman.h>
24 #endif
25 #ifdef HAVE_SYS_TYPES_H
26 #include <sys/types.h>
27 #endif
28 #ifdef HAVE_SYS_STAT_H
29 #include <sys/stat.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37
38 #ifdef HAVE_LINUX_FS_H
39 #include <linux/fs.h>
40 #endif
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44
45 #ifdef HAVE_TM_TM_GMTOFF
46 #include <time.h>
47 #endif
48
49 #if defined(BUP_RL_EXPECTED_XOPEN_SOURCE) \
50 && (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < BUP_RL_EXPECTED_XOPEN_SOURCE)
51 # warning "_XOPEN_SOURCE version is incorrect for readline"
52 #endif
53
54 #ifdef BUP_HAVE_READLINE
55 # pragma GCC diagnostic push
56 # pragma GCC diagnostic ignored "-Wstrict-prototypes"
57 # ifdef BUP_READLINE_INCLUDES_IN_SUBDIR
58 # include <readline/readline.h>
59 # include <readline/history.h>
60 # else
61 # include <readline.h>
62 # include <history.h>
63 # endif
64 # pragma GCC diagnostic pop
65 #endif
66
67 #include "bupsplit.h"
68
69 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
70 #define BUP_HAVE_FILE_ATTRS 1
71 #endif
72
73 /*
74 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
75 * pretend we don't have it.
76 */
77 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
78 #undef HAVE_UTIMENSAT
79 #endif
80
81 #ifndef FS_NOCOW_FL
82 // Of course, this assumes it's a bitfield value.
83 #define FS_NOCOW_FL 0
84 #endif
85
86
87 typedef unsigned char byte;
88
89
90 typedef struct {
91 int istty2;
92 } state_t;
93
94 // cstr_argf: for byte vectors without null characters (e.g. paths)
95 // rbuf_argf: for read-only byte vectors
96 // wbuf_argf: for mutable byte vectors
97
98 #if PY_MAJOR_VERSION < 3
99 static state_t state;
100 # define get_state(x) (&state)
101 # define cstr_argf "s"
102 # define rbuf_argf "s#"
103 # define wbuf_argf "s*"
104 #else
105 # define get_state(x) ((state_t *) PyModule_GetState(x))
106 # define cstr_argf "y"
107 # define rbuf_argf "y#"
108 # define wbuf_argf "y*"
109 #endif // PY_MAJOR_VERSION >= 3
110
111
checked_calloc(size_t n,size_t size)112 static void *checked_calloc(size_t n, size_t size)
113 {
114 void *result = calloc(n, size);
115 if (!result)
116 PyErr_NoMemory();
117 return result;
118 }
119
120 #ifndef BUP_HAVE_BUILTIN_MUL_OVERFLOW
121
122 #define checked_malloc checked_calloc
123
124 #else // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
125
checked_malloc(size_t n,size_t size)126 static void *checked_malloc(size_t n, size_t size)
127 {
128 size_t total;
129 if (__builtin_mul_overflow(n, size, &total))
130 {
131 PyErr_Format(PyExc_OverflowError,
132 "request to allocate %zu items of size %zu is too large",
133 n, size);
134 return NULL;
135 }
136 void *result = malloc(total);
137 if (!result)
138 return PyErr_NoMemory();
139 return result;
140 }
141
142 #endif // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
143
144
145 #ifndef htonll
146 // This function should technically be macro'd out if it's going to be used
147 // more than ocasionally. As of this writing, it'll actually never be called
148 // in real world bup scenarios (because our packs are < MAX_INT bytes).
htonll(uint64_t value)149 static uint64_t htonll(uint64_t value)
150 {
151 static const int endian_test = 42;
152
153 if (*(char *)&endian_test == endian_test) // LSB-MSB
154 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
155 return value; // already in network byte order MSB-LSB
156 }
157 #endif
158
159
160 // Disabling sign-compare here should be fine since we're explicitly
161 // checking for a sign mismatch, i.e. if the signs don't match, then
162 // it doesn't matter what the value comparison says.
163 // FIXME: ... so should we reverse the order?
164 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
165 ({ \
166 _Pragma("GCC diagnostic push"); \
167 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
168 _Pragma("clang diagnostic push"); \
169 _Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\""); \
170 *(dest) = (src); \
171 int result = *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
172 _Pragma("clang diagnostic pop"); \
173 _Pragma("GCC diagnostic pop"); \
174 result; \
175 })
176
177
178 // At the moment any code that calls INTEGER_TO_PY() will have to
179 // disable -Wtautological-compare for clang. See below.
180
181 #define INTEGER_TO_PY(x) \
182 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
183
184
185
186 #if PY_MAJOR_VERSION < 3
bup_ulong_from_pyint(unsigned long * x,PyObject * py,const char * name)187 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
188 const char *name)
189 {
190 const long tmp = PyInt_AsLong(py);
191 if (tmp == -1 && PyErr_Occurred())
192 {
193 if (PyErr_ExceptionMatches(PyExc_OverflowError))
194 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
195 name);
196 return 0;
197 }
198 if (tmp < 0)
199 {
200 PyErr_Format(PyExc_OverflowError,
201 "negative %s cannot be converted to unsigned long", name);
202 return 0;
203 }
204 *x = tmp;
205 return 1;
206 }
207 #endif
208
209
bup_ulong_from_py(unsigned long * x,PyObject * py,const char * name)210 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
211 {
212 #if PY_MAJOR_VERSION < 3
213 if (PyInt_Check(py))
214 return bup_ulong_from_pyint(x, py, name);
215 #endif
216
217 if (!PyLong_Check(py))
218 {
219 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
220 return 0;
221 }
222
223 const unsigned long tmp = PyLong_AsUnsignedLong(py);
224 if (PyErr_Occurred())
225 {
226 if (PyErr_ExceptionMatches(PyExc_OverflowError))
227 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
228 name);
229 return 0;
230 }
231 *x = tmp;
232 return 1;
233 }
234
235
bup_uint_from_py(unsigned int * x,PyObject * py,const char * name)236 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
237 {
238 unsigned long tmp;
239 if (!bup_ulong_from_py(&tmp, py, name))
240 return 0;
241
242 if (tmp > UINT_MAX)
243 {
244 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
245 return 0;
246 }
247 *x = (unsigned int) tmp;
248 return 1;
249 }
250
bup_ullong_from_py(unsigned PY_LONG_LONG * x,PyObject * py,const char * name)251 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
252 const char *name)
253 {
254 #if PY_MAJOR_VERSION < 3
255 if (PyInt_Check(py))
256 {
257 unsigned long tmp;
258 if (bup_ulong_from_pyint(&tmp, py, name))
259 {
260 *x = tmp;
261 return 1;
262 }
263 return 0;
264 }
265 #endif
266
267 if (!PyLong_Check(py))
268 {
269 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
270 return 0;
271 }
272
273 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
274 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
275 {
276 if (PyErr_ExceptionMatches(PyExc_OverflowError))
277 PyErr_Format(PyExc_OverflowError,
278 "%s too big for unsigned long long", name);
279 return 0;
280 }
281 *x = tmp;
282 return 1;
283 }
284
285
bup_bytescmp(PyObject * self,PyObject * args)286 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
287 {
288 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
289 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
290 return NULL;
291 char *s1, *s2;
292 Py_ssize_t s1_len, s2_len;
293 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
294 return NULL;
295 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
296 return NULL;
297 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
298 const int cmp = memcmp(s1, s2, n);
299 if (cmp != 0)
300 return PyLong_FromLong(cmp);
301 if (s1_len == s2_len)
302 return PyLong_FromLong(0);;
303 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
304 }
305
306
bup_cat_bytes(PyObject * self,PyObject * args)307 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
308 {
309 unsigned char *bufx = NULL, *bufy = NULL;
310 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
311 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
312 if (!PyArg_ParseTuple(args,
313 rbuf_argf "nn"
314 rbuf_argf "nn",
315 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
316 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
317 return NULL;
318 if (bufx_ofs < 0)
319 return PyErr_Format(PyExc_ValueError, "negative x offset");
320 if (bufx_n < 0)
321 return PyErr_Format(PyExc_ValueError, "negative x extent");
322 if (bufx_ofs > bufx_len)
323 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
324 if (bufx_n > bufx_len - bufx_ofs)
325 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
326
327 if (bufy_ofs < 0)
328 return PyErr_Format(PyExc_ValueError, "negative y offset");
329 if (bufy_n < 0)
330 return PyErr_Format(PyExc_ValueError, "negative y extent");
331 if (bufy_ofs > bufy_len)
332 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
333 if (bufy_n > bufy_len - bufy_ofs)
334 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
335
336 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
337 return PyErr_Format(PyExc_OverflowError, "result length too long");
338
339 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
340 if (!result)
341 return PyErr_NoMemory();
342 char *buf = PyBytes_AS_STRING(result);
343 memcpy(buf, bufx + bufx_ofs, bufx_n);
344 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
345 return result;
346 }
347
348
349
350 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
351 #if __WIN32__ || __CYGWIN__
352
353 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
unpythonize_argv(void)354 static void unpythonize_argv(void) { }
355
356 #else // not __WIN32__
357
358 // For some reason this isn't declared in Python.h
359 extern void Py_GetArgcArgv(int *argc, char ***argv);
360
unpythonize_argv(void)361 static void unpythonize_argv(void)
362 {
363 int argc, i;
364 char **argv, *arge;
365
366 Py_GetArgcArgv(&argc, &argv);
367
368 for (i = 0; i < argc-1; i++)
369 {
370 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
371 {
372 // The argv block doesn't work the way we expected; it's unsafe
373 // to mess with it.
374 return;
375 }
376 }
377
378 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
379
380 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
381 {
382 char *p;
383 size_t len, diff;
384 p = strrchr(argv[1], '/');
385 if (p)
386 {
387 p++;
388 diff = p - argv[0];
389 len = arge - p;
390 memmove(argv[0], p, len);
391 memset(arge - diff, 0, diff);
392 for (i = 0; i < argc; i++)
393 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
394 }
395 }
396 }
397
398 #endif // not __WIN32__ or __CYGWIN__
399
400
write_all(int fd,const void * buf,const size_t count)401 static int write_all(int fd, const void *buf, const size_t count)
402 {
403 size_t written = 0;
404 while (written < count)
405 {
406 const ssize_t rc = write(fd, buf + written, count - written);
407 if (rc == -1)
408 return -1;
409 written += rc;
410 }
411 return 0;
412 }
413
414
uadd(unsigned long long * dest,const unsigned long long x,const unsigned long long y)415 static int uadd(unsigned long long *dest,
416 const unsigned long long x,
417 const unsigned long long y)
418 {
419 const unsigned long long result = x + y;
420 if (result < x || result < y)
421 return 0;
422 *dest = result;
423 return 1;
424 }
425
426
append_sparse_region(const int fd,unsigned long long n)427 static PyObject *append_sparse_region(const int fd, unsigned long long n)
428 {
429 while (n)
430 {
431 off_t new_off;
432 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
433 new_off = INT_MAX;
434 const off_t off = lseek(fd, new_off, SEEK_CUR);
435 if (off == (off_t) -1)
436 return PyErr_SetFromErrno(PyExc_IOError);
437 n -= new_off;
438 }
439 return NULL;
440 }
441
442
record_sparse_zeros(unsigned long long * new_pending,const int fd,unsigned long long prev_pending,const unsigned long long count)443 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
444 const int fd,
445 unsigned long long prev_pending,
446 const unsigned long long count)
447 {
448 // Add count additional sparse zeros to prev_pending and store the
449 // result in new_pending, or if the total won't fit in
450 // new_pending, write some of the zeros to fd sparsely, and store
451 // the remaining sum in new_pending.
452 if (!uadd(new_pending, prev_pending, count))
453 {
454 PyObject *err = append_sparse_region(fd, prev_pending);
455 if (err != NULL)
456 return err;
457 *new_pending = count;
458 }
459 return NULL;
460 }
461
462
find_not_zero(const byte * const start,const byte * const end)463 static byte* find_not_zero(const byte * const start, const byte * const end)
464 {
465 // Return a pointer to first non-zero byte between start and end,
466 // or end if there isn't one.
467 assert(start <= end);
468 const unsigned char *cur = start;
469 while (cur < end && *cur == 0)
470 cur++;
471 return (byte *) cur;
472 }
473
474
find_trailing_zeros(const byte * const start,const byte * const end)475 static byte* find_trailing_zeros(const byte * const start,
476 const byte * const end)
477 {
478 // Return a pointer to the start of any trailing run of zeros, or
479 // end if there isn't one.
480 assert(start <= end);
481 if (start == end)
482 return (byte *) end;
483 const byte * cur = end;
484 while (cur > start && *--cur == 0) {}
485 if (*cur == 0)
486 return (byte *) cur;
487 else
488 return (byte *) (cur + 1);
489 }
490
491
find_non_sparse_end(const byte * const start,const byte * const end,const ptrdiff_t min_len)492 static byte *find_non_sparse_end(const byte * const start,
493 const byte * const end,
494 const ptrdiff_t min_len)
495 {
496 // Return the first pointer to a min_len sparse block in [start,
497 // end) if there is one, otherwise a pointer to the start of any
498 // trailing run of zeros. If there are no trailing zeros, return
499 // end.
500 if (start == end)
501 return (byte *) end;
502 assert(start < end);
503 assert(min_len);
504 // Probe in min_len jumps, searching backward from the jump
505 // destination for a non-zero byte. If such a byte is found, move
506 // just past it and try again.
507 const byte *candidate = start;
508 // End of any run of zeros, starting at candidate, that we've already seen
509 const byte *end_of_known_zeros = candidate;
510 while (end - candidate >= min_len) // Handle all min_len candidate blocks
511 {
512 const byte * const probe_end = candidate + min_len;
513 const byte * const trailing_zeros =
514 find_trailing_zeros(end_of_known_zeros, probe_end);
515 if (trailing_zeros == probe_end)
516 end_of_known_zeros = candidate = probe_end;
517 else if (trailing_zeros == end_of_known_zeros)
518 {
519 assert(candidate >= start);
520 assert(candidate <= end);
521 assert(*candidate == 0);
522 return (byte *) candidate;
523 }
524 else
525 {
526 candidate = trailing_zeros;
527 end_of_known_zeros = probe_end;
528 }
529 }
530
531 if (candidate == end)
532 return (byte *) end;
533
534 // No min_len sparse run found, search backward from end
535 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
536 end);
537
538 if (trailing_zeros == end_of_known_zeros)
539 {
540 assert(candidate >= start);
541 assert(candidate < end);
542 assert(*candidate == 0);
543 assert(end - candidate < min_len);
544 return (byte *) candidate;
545 }
546
547 if (trailing_zeros == end)
548 {
549 assert(*(end - 1) != 0);
550 return (byte *) end;
551 }
552
553 assert(end - trailing_zeros < min_len);
554 assert(trailing_zeros >= start);
555 assert(trailing_zeros < end);
556 assert(*trailing_zeros == 0);
557 return (byte *) trailing_zeros;
558 }
559
560
bup_write_sparsely(PyObject * self,PyObject * args)561 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
562 {
563 int fd;
564 unsigned char *buf = NULL;
565 Py_ssize_t sbuf_len;
566 PyObject *py_min_sparse_len, *py_prev_sparse_len;
567 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
568 &fd, &buf, &sbuf_len,
569 &py_min_sparse_len, &py_prev_sparse_len))
570 return NULL;
571 ptrdiff_t min_sparse_len;
572 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
573 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
574 return NULL;
575 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
576 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
577 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
578 return NULL;
579 if (sbuf_len < 0)
580 return PyErr_Format(PyExc_ValueError, "negative bufer length");
581 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
582 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
583
584 const byte * block = buf; // Start of pending block
585 const byte * const end = buf + buf_len;
586 unsigned long long zeros = prev_sparse_len;
587 while (1)
588 {
589 assert(block <= end);
590 if (block == end)
591 return PyLong_FromUnsignedLongLong(zeros);
592
593 if (*block != 0)
594 {
595 // Look for the end of block, i.e. the next sparse run of
596 // at least min_sparse_len zeros, or the end of the
597 // buffer.
598 const byte * const probe = find_non_sparse_end(block + 1, end,
599 min_sparse_len);
600 // Either at end of block, or end of non-sparse; write pending data
601 PyObject *err = append_sparse_region(fd, zeros);
602 if (err != NULL)
603 return err;
604 int rc = write_all(fd, block, probe - block);
605 if (rc)
606 return PyErr_SetFromErrno(PyExc_IOError);
607
608 if (end - probe < min_sparse_len)
609 zeros = end - probe;
610 else
611 zeros = min_sparse_len;
612 block = probe + zeros;
613 }
614 else // *block == 0
615 {
616 // Should be in the first loop iteration, a sparse run of
617 // zeros, or nearly at the end of the block (within
618 // min_sparse_len).
619 const byte * const zeros_end = find_not_zero(block, end);
620 PyObject *err = record_sparse_zeros(&zeros, fd,
621 zeros, zeros_end - block);
622 if (err != NULL)
623 return err;
624 assert(block <= zeros_end);
625 block = zeros_end;
626 }
627 }
628 }
629
630
selftest(PyObject * self,PyObject * args)631 static PyObject *selftest(PyObject *self, PyObject *args)
632 {
633 if (!PyArg_ParseTuple(args, ""))
634 return NULL;
635
636 return Py_BuildValue("i", !bupsplit_selftest());
637 }
638
639
blobbits(PyObject * self,PyObject * args)640 static PyObject *blobbits(PyObject *self, PyObject *args)
641 {
642 if (!PyArg_ParseTuple(args, ""))
643 return NULL;
644 return Py_BuildValue("i", BUP_BLOBBITS);
645 }
646
647
splitbuf(PyObject * self,PyObject * args)648 static PyObject *splitbuf(PyObject *self, PyObject *args)
649 {
650 // We stick to buffers in python 2 because they appear to be
651 // substantially smaller than memoryviews, and because
652 // zlib.compress() in python 2 can't accept a memoryview
653 // (cf. hashsplit.py).
654 int out = 0, bits = -1;
655 if (PY_MAJOR_VERSION > 2)
656 {
657 Py_buffer buf;
658 if (!PyArg_ParseTuple(args, "y*", &buf))
659 return NULL;
660 assert(buf.len <= INT_MAX);
661 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
662 PyBuffer_Release(&buf);
663 }
664 else
665 {
666 unsigned char *buf = NULL;
667 Py_ssize_t len = 0;
668 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
669 return NULL;
670 assert(len <= INT_MAX);
671 out = bupsplit_find_ofs(buf, (int) len, &bits);
672 }
673 if (out) assert(bits >= BUP_BLOBBITS);
674 return Py_BuildValue("ii", out, bits);
675 }
676
677
bitmatch(PyObject * self,PyObject * args)678 static PyObject *bitmatch(PyObject *self, PyObject *args)
679 {
680 unsigned char *buf1 = NULL, *buf2 = NULL;
681 Py_ssize_t len1 = 0, len2 = 0;
682 Py_ssize_t byte;
683 int bit;
684
685 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
686 return NULL;
687
688 bit = 0;
689 for (byte = 0; byte < len1 && byte < len2; byte++)
690 {
691 int b1 = buf1[byte], b2 = buf2[byte];
692 if (b1 != b2)
693 {
694 for (bit = 0; bit < 8; bit++)
695 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
696 break;
697 break;
698 }
699 }
700
701 assert(byte <= (INT_MAX >> 3));
702 return Py_BuildValue("i", byte*8 + bit);
703 }
704
705
firstword(PyObject * self,PyObject * args)706 static PyObject *firstword(PyObject *self, PyObject *args)
707 {
708 unsigned char *buf = NULL;
709 Py_ssize_t len = 0;
710 uint32_t v;
711
712 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
713 return NULL;
714
715 if (len < 4)
716 return NULL;
717
718 v = ntohl(*(uint32_t *)buf);
719 return PyLong_FromUnsignedLong(v);
720 }
721
722
723 #define BLOOM2_HEADERLEN 16
724
to_bloom_address_bitmask4(const unsigned char * buf,const int nbits,uint64_t * v,unsigned char * bitmask)725 static void to_bloom_address_bitmask4(const unsigned char *buf,
726 const int nbits, uint64_t *v, unsigned char *bitmask)
727 {
728 int bit;
729 uint32_t high;
730 uint64_t raw, mask;
731
732 memcpy(&high, buf, 4);
733 mask = (1<<nbits) - 1;
734 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
735 bit = (raw >> (37-nbits)) & 0x7;
736 *v = (raw >> (40-nbits)) & mask;
737 *bitmask = 1 << bit;
738 }
739
to_bloom_address_bitmask5(const unsigned char * buf,const int nbits,uint32_t * v,unsigned char * bitmask)740 static void to_bloom_address_bitmask5(const unsigned char *buf,
741 const int nbits, uint32_t *v, unsigned char *bitmask)
742 {
743 int bit;
744 uint32_t high;
745 uint32_t raw, mask;
746
747 memcpy(&high, buf, 4);
748 mask = (1<<nbits) - 1;
749 raw = ntohl(high);
750 bit = (raw >> (29-nbits)) & 0x7;
751 *v = (raw >> (32-nbits)) & mask;
752 *bitmask = 1 << bit;
753 }
754
755 #define BLOOM_SET_BIT(name, address, otype) \
756 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
757 {\
758 unsigned char bitmask;\
759 otype v;\
760 address(buf, nbits, &v, &bitmask);\
761 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
762 }
BLOOM_SET_BIT(bloom_set_bit4,to_bloom_address_bitmask4,uint64_t)763 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
764 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
765
766
767 #define BLOOM_GET_BIT(name, address, otype) \
768 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
769 {\
770 unsigned char bitmask;\
771 otype v;\
772 address(buf, nbits, &v, &bitmask);\
773 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
774 }
775 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
776 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
777
778
779 static PyObject *bloom_add(PyObject *self, PyObject *args)
780 {
781 Py_buffer bloom, sha;
782 int nbits = 0, k = 0;
783 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
784 &bloom, &sha, &nbits, &k))
785 return NULL;
786
787 PyObject *result = NULL;
788
789 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
790 goto clean_and_return;
791
792 if (k == 5)
793 {
794 if (nbits > 29)
795 goto clean_and_return;
796 unsigned char *cur = sha.buf;
797 unsigned char *end;
798 for (end = cur + sha.len; cur < end; cur += 20/k)
799 bloom_set_bit5(bloom.buf, cur, nbits);
800 }
801 else if (k == 4)
802 {
803 if (nbits > 37)
804 goto clean_and_return;
805 unsigned char *cur = sha.buf;
806 unsigned char *end = cur + sha.len;
807 for (; cur < end; cur += 20/k)
808 bloom_set_bit4(bloom.buf, cur, nbits);
809 }
810 else
811 goto clean_and_return;
812
813 result = Py_BuildValue("n", sha.len / 20);
814
815 clean_and_return:
816 PyBuffer_Release(&bloom);
817 PyBuffer_Release(&sha);
818 return result;
819 }
820
bloom_contains(PyObject * self,PyObject * args)821 static PyObject *bloom_contains(PyObject *self, PyObject *args)
822 {
823 Py_buffer bloom;
824 unsigned char *sha = NULL;
825 Py_ssize_t len = 0;
826 int nbits = 0, k = 0;
827 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
828 &bloom, &sha, &len, &nbits, &k))
829 return NULL;
830
831 PyObject *result = NULL;
832
833 if (len != 20)
834 goto clean_and_return;
835
836 if (k == 5)
837 {
838 if (nbits > 29)
839 goto clean_and_return;
840 int steps;
841 unsigned char *end;
842 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
843 if (!bloom_get_bit5(bloom.buf, sha, nbits))
844 {
845 result = Py_BuildValue("Oi", Py_None, steps);
846 goto clean_and_return;
847 }
848 }
849 else if (k == 4)
850 {
851 if (nbits > 37)
852 goto clean_and_return;
853 int steps;
854 unsigned char *end;
855 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
856 if (!bloom_get_bit4(bloom.buf, sha, nbits))
857 {
858 result = Py_BuildValue("Oi", Py_None, steps);
859 goto clean_and_return;
860 }
861 }
862 else
863 goto clean_and_return;
864
865 result = Py_BuildValue("ii", 1, k);
866
867 clean_and_return:
868 PyBuffer_Release(&bloom);
869 return result;
870 }
871
872
_extract_bits(unsigned char * buf,int nbits)873 static uint32_t _extract_bits(unsigned char *buf, int nbits)
874 {
875 uint32_t v, mask;
876
877 mask = (1<<nbits) - 1;
878 v = ntohl(*(uint32_t *)buf);
879 v = (v >> (32-nbits)) & mask;
880 return v;
881 }
882
883
extract_bits(PyObject * self,PyObject * args)884 static PyObject *extract_bits(PyObject *self, PyObject *args)
885 {
886 unsigned char *buf = NULL;
887 Py_ssize_t len = 0;
888 int nbits = 0;
889
890 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
891 return NULL;
892
893 if (len < 4)
894 return NULL;
895
896 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
897 }
898
899
900 struct sha {
901 unsigned char bytes[20];
902 };
903
_cmp_sha(const struct sha * sha1,const struct sha * sha2)904 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
905 {
906 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
907 }
908
909
910 struct idx {
911 unsigned char *map;
912 struct sha *cur;
913 struct sha *end;
914 uint32_t *cur_name;
915 Py_ssize_t bytes;
916 int name_base;
917 };
918
_fix_idx_order(struct idx ** idxs,Py_ssize_t * last_i)919 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
920 {
921 struct idx *idx;
922 Py_ssize_t low, mid, high;
923 int c = 0;
924
925 idx = idxs[*last_i];
926 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
927 {
928 idxs[*last_i] = NULL;
929 PyMem_Free(idx);
930 --*last_i;
931 return;
932 }
933 if (*last_i == 0)
934 return;
935
936 low = *last_i-1;
937 mid = *last_i;
938 high = 0;
939 while (low >= high)
940 {
941 mid = (low + high) / 2;
942 c = _cmp_sha(idx->cur, idxs[mid]->cur);
943 if (c < 0)
944 high = mid + 1;
945 else if (c > 0)
946 low = mid - 1;
947 else
948 break;
949 }
950 if (c < 0)
951 ++mid;
952 if (mid == *last_i)
953 return;
954 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
955 idxs[mid] = idx;
956 }
957
958
_get_idx_i(struct idx * idx)959 static uint32_t _get_idx_i(struct idx *idx)
960 {
961 if (idx->cur_name == NULL)
962 return idx->name_base;
963 return ntohl(*idx->cur_name) + idx->name_base;
964 }
965
966 #define MIDX4_HEADERLEN 12
967
merge_into(PyObject * self,PyObject * args)968 static PyObject *merge_into(PyObject *self, PyObject *args)
969 {
970 struct sha *sha_ptr, *sha_start = NULL;
971 uint32_t *table_ptr, *name_ptr, *name_start;
972 int i;
973 unsigned int total;
974 uint32_t count, prefix;
975
976
977 Py_buffer fmap;
978 int bits;;
979 PyObject *py_total, *ilist = NULL;
980 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
981 &fmap, &bits, &py_total, &ilist))
982 return NULL;
983
984 PyObject *result = NULL;
985 struct idx **idxs = NULL;
986 Py_ssize_t num_i = 0;
987 int *idx_buf_init = NULL;
988 Py_buffer *idx_buf = NULL;
989
990 if (!bup_uint_from_py(&total, py_total, "total"))
991 goto clean_and_return;
992
993 num_i = PyList_Size(ilist);
994
995 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
996 goto clean_and_return;
997 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
998 goto clean_and_return;
999 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
1000 goto clean_and_return;
1001
1002 for (i = 0; i < num_i; i++)
1003 {
1004 long len, sha_ofs, name_map_ofs;
1005 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
1006 goto clean_and_return;
1007 PyObject *itup = PyList_GetItem(ilist, i);
1008 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
1009 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
1010 &idxs[i]->name_base))
1011 return NULL;
1012 idx_buf_init[i] = 1;
1013 idxs[i]->map = idx_buf[i].buf;
1014 idxs[i]->bytes = idx_buf[i].len;
1015 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
1016 idxs[i]->end = &idxs[i]->cur[len];
1017 if (name_map_ofs)
1018 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
1019 else
1020 idxs[i]->cur_name = NULL;
1021 }
1022 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
1023 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
1024 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
1025
1026 Py_ssize_t last_i = num_i - 1;
1027 count = 0;
1028 prefix = 0;
1029 while (last_i >= 0)
1030 {
1031 struct idx *idx;
1032 uint32_t new_prefix;
1033 if (count % 102424 == 0 && get_state(self)->istty2)
1034 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
1035 count*100.0/total, count, total);
1036 idx = idxs[last_i];
1037 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
1038 while (prefix < new_prefix)
1039 table_ptr[prefix++] = htonl(count);
1040 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
1041 *name_ptr++ = htonl(_get_idx_i(idx));
1042 ++idx->cur;
1043 if (idx->cur_name != NULL)
1044 ++idx->cur_name;
1045 _fix_idx_order(idxs, &last_i);
1046 ++count;
1047 }
1048 while (prefix < ((uint32_t) 1 << bits))
1049 table_ptr[prefix++] = htonl(count);
1050 assert(count == total);
1051 assert(prefix == ((uint32_t) 1 << bits));
1052 assert(sha_ptr == sha_start+count);
1053 assert(name_ptr == name_start+count);
1054
1055 result = PyLong_FromUnsignedLong(count);
1056
1057 clean_and_return:
1058 if (idx_buf_init)
1059 {
1060 for (i = 0; i < num_i; i++)
1061 if (idx_buf_init[i])
1062 PyBuffer_Release(&(idx_buf[i]));
1063 free(idx_buf_init);
1064 free(idx_buf);
1065 }
1066 if (idxs)
1067 {
1068 for (i = 0; i < num_i; i++)
1069 free(idxs[i]);
1070 free(idxs);
1071 }
1072 PyBuffer_Release(&fmap);
1073 return result;
1074 }
1075
1076 #define FAN_ENTRIES 256
1077
write_idx(PyObject * self,PyObject * args)1078 static PyObject *write_idx(PyObject *self, PyObject *args)
1079 {
1080 char *filename = NULL;
1081 PyObject *py_total, *idx = NULL;
1082 PyObject *part;
1083 unsigned int total = 0;
1084 uint32_t count;
1085 int i, j, ofs64_count;
1086 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1087 uint64_t *ofs64_ptr;
1088 struct sha *sha_ptr;
1089
1090 Py_buffer fmap;
1091 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1092 &filename, &fmap, &idx, &py_total))
1093 return NULL;
1094
1095 PyObject *result = NULL;
1096
1097 if (!bup_uint_from_py(&total, py_total, "total"))
1098 goto clean_and_return;
1099
1100 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1101 {
1102 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1103 FAN_ENTRIES);
1104 goto clean_and_return;
1105 }
1106
1107 const char idx_header[] = "\377tOc\0\0\0\002";
1108 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1109
1110 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1111 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1112 crc_ptr = (uint32_t *)&sha_ptr[total];
1113 ofs_ptr = (uint32_t *)&crc_ptr[total];
1114 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1115
1116 count = 0;
1117 ofs64_count = 0;
1118 for (i = 0; i < FAN_ENTRIES; ++i)
1119 {
1120 Py_ssize_t plen;
1121 part = PyList_GET_ITEM(idx, i);
1122 PyList_Sort(part);
1123 plen = PyList_GET_SIZE(part);
1124 if (plen > UINT32_MAX || UINT32_MAX - count < plen) {
1125 PyErr_Format(PyExc_OverflowError, "too many objects in index part");
1126 goto clean_and_return;
1127 }
1128 count += (uint32_t) plen;
1129 *fan_ptr++ = htonl(count);
1130 for (j = 0; j < plen; ++j)
1131 {
1132 unsigned char *sha = NULL;
1133 Py_ssize_t sha_len = 0;
1134 PyObject *crc_py, *ofs_py;
1135 unsigned int crc;
1136 unsigned PY_LONG_LONG ofs_ull;
1137 uint64_t ofs;
1138 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1139 &sha, &sha_len, &crc_py, &ofs_py))
1140 goto clean_and_return;
1141 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1142 goto clean_and_return;
1143 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1144 goto clean_and_return;
1145 assert(crc <= UINT32_MAX);
1146 assert(ofs_ull <= UINT64_MAX);
1147 ofs = ofs_ull;
1148 if (sha_len != sizeof(struct sha))
1149 goto clean_and_return;
1150 memcpy(sha_ptr++, sha, sizeof(struct sha));
1151 *crc_ptr++ = htonl(crc);
1152 if (ofs > 0x7fffffff)
1153 {
1154 *ofs64_ptr++ = htonll(ofs);
1155 ofs = 0x80000000 | ofs64_count++;
1156 }
1157 *ofs_ptr++ = htonl((uint32_t)ofs);
1158 }
1159 }
1160
1161 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1162 if (rc != 0)
1163 {
1164 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1165 goto clean_and_return;
1166 }
1167
1168 result = PyLong_FromUnsignedLong(count);
1169
1170 clean_and_return:
1171 PyBuffer_Release(&fmap);
1172 return result;
1173 }
1174
1175
1176 // I would have made this a lower-level function that just fills in a buffer
1177 // with random values, and then written those values from python. But that's
1178 // about 20% slower in my tests, and since we typically generate random
1179 // numbers for benchmarking other parts of bup, any slowness in generating
1180 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1181 // pseudorandom bytes much except for this anyway.
write_random(PyObject * self,PyObject * args)1182 static PyObject *write_random(PyObject *self, PyObject *args)
1183 {
1184 uint32_t buf[1024/4];
1185 int fd = -1, seed = 0, verbose = 0;
1186 ssize_t ret;
1187 long long len = 0, kbytes = 0, written = 0;
1188
1189 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1190 return NULL;
1191
1192 srandom(seed);
1193
1194 for (kbytes = 0; kbytes < len/1024; kbytes++)
1195 {
1196 unsigned i;
1197 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1198 buf[i] = (uint32_t) random();
1199 ret = write(fd, buf, sizeof(buf));
1200 if (ret < 0)
1201 ret = 0;
1202 written += ret;
1203 if (ret < (int)sizeof(buf))
1204 break;
1205 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1206 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1207 }
1208
1209 // handle non-multiples of 1024
1210 if (len % 1024)
1211 {
1212 unsigned i;
1213 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1214 buf[i] = (uint32_t) random();
1215 ret = write(fd, buf, len % 1024);
1216 if (ret < 0)
1217 ret = 0;
1218 written += ret;
1219 }
1220
1221 if (kbytes/1024 > 0)
1222 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1223 return Py_BuildValue("L", written);
1224 }
1225
1226
random_sha(PyObject * self,PyObject * args)1227 static PyObject *random_sha(PyObject *self, PyObject *args)
1228 {
1229 static int seeded = 0;
1230 uint32_t shabuf[20/4];
1231 int i;
1232
1233 if (!seeded)
1234 {
1235 assert(sizeof(shabuf) == 20);
1236 srandom((unsigned int) time(NULL));
1237 seeded = 1;
1238 }
1239
1240 if (!PyArg_ParseTuple(args, ""))
1241 return NULL;
1242
1243 memset(shabuf, 0, sizeof(shabuf));
1244 for (i=0; i < 20/4; i++)
1245 shabuf[i] = (uint32_t) random();
1246 return Py_BuildValue(rbuf_argf, shabuf, 20);
1247 }
1248
1249
_open_noatime(const char * filename,int attrs)1250 static int _open_noatime(const char *filename, int attrs)
1251 {
1252 int attrs_noatime, fd;
1253 attrs |= O_RDONLY;
1254 #ifdef O_NOFOLLOW
1255 attrs |= O_NOFOLLOW;
1256 #endif
1257 #ifdef O_LARGEFILE
1258 attrs |= O_LARGEFILE;
1259 #endif
1260 attrs_noatime = attrs;
1261 #ifdef O_NOATIME
1262 attrs_noatime |= O_NOATIME;
1263 #endif
1264 fd = open(filename, attrs_noatime);
1265 if (fd < 0 && errno == EPERM)
1266 {
1267 // older Linux kernels would return EPERM if you used O_NOATIME
1268 // and weren't the file's owner. This pointless restriction was
1269 // relaxed eventually, but we have to handle it anyway.
1270 // (VERY old kernels didn't recognized O_NOATIME, but they would
1271 // just harmlessly ignore it, so this branch won't trigger)
1272 fd = open(filename, attrs);
1273 }
1274 return fd;
1275 }
1276
1277
open_noatime(PyObject * self,PyObject * args)1278 static PyObject *open_noatime(PyObject *self, PyObject *args)
1279 {
1280 char *filename = NULL;
1281 int fd;
1282 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1283 return NULL;
1284 fd = _open_noatime(filename, 0);
1285 if (fd < 0)
1286 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1287 return Py_BuildValue("i", fd);
1288 }
1289
1290
fadvise_done(PyObject * self,PyObject * args)1291 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1292 {
1293 int fd = -1;
1294 long long llofs, lllen = 0;
1295 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1296 return NULL;
1297 off_t ofs, len;
1298 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1299 return PyErr_Format(PyExc_OverflowError,
1300 "fadvise offset overflows off_t");
1301 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1302 return PyErr_Format(PyExc_OverflowError,
1303 "fadvise length overflows off_t");
1304 #ifdef POSIX_FADV_DONTNEED
1305 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1306 #endif
1307 return Py_BuildValue("");
1308 }
1309
1310
1311 // Currently the Linux kernel and FUSE disagree over the type for
1312 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1313 // but FUSE chose long (matching the declaration in linux/fs.h). So
1314 // if you use int, and then traverse a FUSE filesystem, you may
1315 // corrupt the stack. But if you use long, then you may get invalid
1316 // results on big-endian systems.
1317 //
1318 // For now, we just use long, and then disable Linux attrs entirely
1319 // (with a warning) in helpers.py on systems that are affected.
1320
1321 #ifdef BUP_HAVE_FILE_ATTRS
bup_get_linux_file_attr(PyObject * self,PyObject * args)1322 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1323 {
1324 int rc;
1325 unsigned long attr;
1326 char *path;
1327 int fd;
1328
1329 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1330 return NULL;
1331
1332 fd = _open_noatime(path, O_NONBLOCK);
1333 if (fd == -1)
1334 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1335
1336 attr = 0; // Handle int/long mismatch (see above)
1337 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1338 if (rc == -1)
1339 {
1340 close(fd);
1341 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1342 }
1343 close(fd);
1344 assert(attr <= UINT_MAX); // Kernel type is actually int
1345 return PyLong_FromUnsignedLong(attr);
1346 }
1347 #endif /* def BUP_HAVE_FILE_ATTRS */
1348
1349
1350
1351 #ifdef BUP_HAVE_FILE_ATTRS
bup_set_linux_file_attr(PyObject * self,PyObject * args)1352 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1353 {
1354 int rc;
1355 unsigned long orig_attr;
1356 unsigned int attr;
1357 char *path;
1358 PyObject *py_attr;
1359 int fd;
1360
1361 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1362 return NULL;
1363
1364 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1365 return NULL;
1366
1367 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1368 if (fd == -1)
1369 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1370
1371 // Restrict attr to modifiable flags acdeijstuADST -- see
1372 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1373 // in pf.c flags_array[].
1374 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1375 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1376 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1377 | FS_TOPDIR_FL | FS_NOCOW_FL;
1378
1379 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1380 orig_attr = 0; // Handle int/long mismatch (see above)
1381 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1382 if (rc == -1)
1383 {
1384 close(fd);
1385 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1386 }
1387 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1388 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1389
1390 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1391 if (rc == -1)
1392 {
1393 close(fd);
1394 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1395 }
1396
1397 close(fd);
1398 return Py_BuildValue("O", Py_None);
1399 }
1400 #endif /* def BUP_HAVE_FILE_ATTRS */
1401
1402
1403 #ifndef HAVE_UTIMENSAT
1404 #ifndef HAVE_UTIMES
1405 #error "cannot find utimensat or utimes()"
1406 #endif
1407 #ifndef HAVE_LUTIMES
1408 #error "cannot find utimensat or lutimes()"
1409 #endif
1410 #endif
1411
1412 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1413 ({ \
1414 int result = 0; \
1415 *(overflow) = 0; \
1416 const long long lltmp = PyLong_AsLongLong(pylong); \
1417 if (lltmp == -1 && PyErr_Occurred()) \
1418 { \
1419 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1420 { \
1421 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1422 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1423 { \
1424 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1425 { \
1426 PyErr_Clear(); \
1427 *(overflow) = 1; \
1428 } \
1429 } \
1430 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1431 result = 1; \
1432 else \
1433 *(overflow) = 1; \
1434 } \
1435 } \
1436 else \
1437 { \
1438 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1439 result = 1; \
1440 else \
1441 *(overflow) = 1; \
1442 } \
1443 result; \
1444 })
1445
1446
1447 #ifdef HAVE_UTIMENSAT
1448
bup_utimensat(PyObject * self,PyObject * args)1449 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1450 {
1451 int rc;
1452 int fd, flag;
1453 char *path;
1454 PyObject *access_py, *modification_py;
1455 struct timespec ts[2];
1456
1457 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1458 &fd,
1459 &path,
1460 &access_py, &(ts[0].tv_nsec),
1461 &modification_py, &(ts[1].tv_nsec),
1462 &flag))
1463 return NULL;
1464
1465 int overflow;
1466 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1467 {
1468 if (overflow)
1469 PyErr_SetString(PyExc_ValueError,
1470 "unable to convert access time seconds for utimensat");
1471 return NULL;
1472 }
1473 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1474 {
1475 if (overflow)
1476 PyErr_SetString(PyExc_ValueError,
1477 "unable to convert modification time seconds for utimensat");
1478 return NULL;
1479 }
1480 rc = utimensat(fd, path, ts, flag);
1481 if (rc != 0)
1482 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1483
1484 return Py_BuildValue("O", Py_None);
1485 }
1486
1487 #endif /* def HAVE_UTIMENSAT */
1488
1489
1490 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1491
bup_parse_xutimes_args(char ** path,struct timeval tv[2],PyObject * args)1492 static int bup_parse_xutimes_args(char **path,
1493 struct timeval tv[2],
1494 PyObject *args)
1495 {
1496 PyObject *access_py, *modification_py;
1497 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1498
1499 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1500 path,
1501 &access_py, &access_us,
1502 &modification_py, &modification_us))
1503 return 0;
1504
1505 int overflow;
1506 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1507 {
1508 if (overflow)
1509 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1510 return 0;
1511 }
1512 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1513 {
1514 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1515 return 0;
1516 }
1517 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1518 {
1519 if (overflow)
1520 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1521 return 0;
1522 }
1523 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1524 {
1525 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1526 return 0;
1527 }
1528 return 1;
1529 }
1530
1531 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1532
1533
1534 #ifdef HAVE_UTIMES
bup_utimes(PyObject * self,PyObject * args)1535 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1536 {
1537 char *path;
1538 struct timeval tv[2];
1539 if (!bup_parse_xutimes_args(&path, tv, args))
1540 return NULL;
1541 int rc = utimes(path, tv);
1542 if (rc != 0)
1543 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1544 return Py_BuildValue("O", Py_None);
1545 }
1546 #endif /* def HAVE_UTIMES */
1547
1548
1549 #ifdef HAVE_LUTIMES
bup_lutimes(PyObject * self,PyObject * args)1550 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1551 {
1552 char *path;
1553 struct timeval tv[2];
1554 if (!bup_parse_xutimes_args(&path, tv, args))
1555 return NULL;
1556 int rc = lutimes(path, tv);
1557 if (rc != 0)
1558 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1559
1560 return Py_BuildValue("O", Py_None);
1561 }
1562 #endif /* def HAVE_LUTIMES */
1563
1564
1565 #ifdef HAVE_STAT_ST_ATIM
1566 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1567 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1568 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1569 #elif defined HAVE_STAT_ST_ATIMENSEC
1570 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1571 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1572 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1573 #else
1574 # define BUP_STAT_ATIME_NS(st) 0
1575 # define BUP_STAT_MTIME_NS(st) 0
1576 # define BUP_STAT_CTIME_NS(st) 0
1577 #endif
1578
1579
1580 #pragma clang diagnostic push
1581 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1582
stat_struct_to_py(const struct stat * st,const char * filename,int fd)1583 static PyObject *stat_struct_to_py(const struct stat *st,
1584 const char *filename,
1585 int fd)
1586 {
1587 // We can check the known (via POSIX) signed and unsigned types at
1588 // compile time, but not (easily) the unspecified types, so handle
1589 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1590 // long.
1591 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1592 INTEGER_TO_PY(st->st_mode),
1593 (unsigned PY_LONG_LONG) st->st_ino,
1594 INTEGER_TO_PY(st->st_dev),
1595 INTEGER_TO_PY(st->st_nlink),
1596 INTEGER_TO_PY(st->st_uid),
1597 INTEGER_TO_PY(st->st_gid),
1598 INTEGER_TO_PY(st->st_rdev),
1599 (PY_LONG_LONG) st->st_size,
1600 INTEGER_TO_PY(st->st_atime),
1601 (long) BUP_STAT_ATIME_NS(st),
1602 INTEGER_TO_PY(st->st_mtime),
1603 (long) BUP_STAT_MTIME_NS(st),
1604 INTEGER_TO_PY(st->st_ctime),
1605 (long) BUP_STAT_CTIME_NS(st));
1606 }
1607
1608 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1609
bup_stat(PyObject * self,PyObject * args)1610 static PyObject *bup_stat(PyObject *self, PyObject *args)
1611 {
1612 int rc;
1613 char *filename;
1614
1615 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1616 return NULL;
1617
1618 struct stat st;
1619 rc = stat(filename, &st);
1620 if (rc != 0)
1621 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1622 return stat_struct_to_py(&st, filename, 0);
1623 }
1624
1625
bup_lstat(PyObject * self,PyObject * args)1626 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1627 {
1628 int rc;
1629 char *filename;
1630
1631 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1632 return NULL;
1633
1634 struct stat st;
1635 rc = lstat(filename, &st);
1636 if (rc != 0)
1637 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1638 return stat_struct_to_py(&st, filename, 0);
1639 }
1640
1641
bup_fstat(PyObject * self,PyObject * args)1642 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1643 {
1644 int rc, fd;
1645
1646 if (!PyArg_ParseTuple(args, "i", &fd))
1647 return NULL;
1648
1649 struct stat st;
1650 rc = fstat(fd, &st);
1651 if (rc != 0)
1652 return PyErr_SetFromErrno(PyExc_OSError);
1653 return stat_struct_to_py(&st, NULL, fd);
1654 }
1655
1656
1657 #ifdef HAVE_TM_TM_GMTOFF
bup_localtime(PyObject * self,PyObject * args)1658 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1659 {
1660 long long lltime;
1661 time_t ttime;
1662 if (!PyArg_ParseTuple(args, "L", &lltime))
1663 return NULL;
1664 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1665 return PyErr_Format(PyExc_OverflowError, "time value too large");
1666
1667 struct tm tm;
1668 tzset();
1669 if(localtime_r(&ttime, &tm) == NULL)
1670 return PyErr_SetFromErrno(PyExc_OSError);
1671
1672 // Match the Python struct_time values.
1673 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1674 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1675 tm.tm_hour, tm.tm_min, tm.tm_sec,
1676 tm.tm_wday, tm.tm_yday + 1,
1677 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1678 }
1679 #endif /* def HAVE_TM_TM_GMTOFF */
1680
1681
1682 #ifdef BUP_MINCORE_BUF_TYPE
bup_mincore(PyObject * self,PyObject * args)1683 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1684 {
1685 Py_buffer src, dest;
1686 PyObject *py_src_n, *py_src_off, *py_dest_off;
1687
1688 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1689 &src, &py_src_n, &py_src_off,
1690 &dest, &py_dest_off))
1691 return NULL;
1692
1693 PyObject *result = NULL;
1694
1695 unsigned long long src_n, src_off, dest_off;
1696 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1697 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1698 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1699 goto clean_and_return;
1700
1701 unsigned long long src_region_end;
1702 if (!uadd(&src_region_end, src_off, src_n)) {
1703 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1704 goto clean_and_return;
1705 }
1706 assert(src.len >= 0);
1707 if (src_region_end > (unsigned long long) src.len) {
1708 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1709 goto clean_and_return;
1710 }
1711
1712 unsigned long long dest_size;
1713 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1714 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1715 goto clean_and_return;
1716 }
1717 if (dest_off > dest_size) {
1718 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1719 goto clean_and_return;
1720 }
1721
1722 size_t length;
1723 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1724 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1725 goto clean_and_return;
1726 }
1727 int rc = mincore((void *)(src.buf + src_off), length,
1728 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1729 if (rc != 0) {
1730 result = PyErr_SetFromErrno(PyExc_OSError);
1731 goto clean_and_return;
1732 }
1733 result = Py_BuildValue("O", Py_None);
1734
1735 clean_and_return:
1736 PyBuffer_Release(&src);
1737 PyBuffer_Release(&dest);
1738 return result;
1739 }
1740 #endif /* def BUP_MINCORE_BUF_TYPE */
1741
1742
tuple_from_cstrs(char ** cstrs)1743 static PyObject *tuple_from_cstrs(char **cstrs)
1744 {
1745 // Assumes list is null terminated
1746 size_t n = 0;
1747 while(cstrs[n] != NULL)
1748 n++;
1749
1750 Py_ssize_t sn;
1751 if (!INTEGRAL_ASSIGNMENT_FITS(&sn, n))
1752 return PyErr_Format(PyExc_OverflowError, "string array too large");
1753
1754 PyObject *result = PyTuple_New(sn);
1755 Py_ssize_t i = 0;
1756 for (i = 0; i < sn; i++)
1757 {
1758 PyObject *gname = Py_BuildValue(cstr_argf, cstrs[i]);
1759 if (gname == NULL)
1760 {
1761 Py_DECREF(result);
1762 return NULL;
1763 }
1764 PyTuple_SET_ITEM(result, i, gname);
1765 }
1766 return result;
1767 }
1768
appropriate_errno_ex(void)1769 static PyObject *appropriate_errno_ex(void)
1770 {
1771 switch (errno) {
1772 case ENOMEM:
1773 return PyErr_NoMemory();
1774 case EIO:
1775 case EMFILE:
1776 case ENFILE:
1777 // In 3.3 IOError was merged into OSError.
1778 return PyErr_SetFromErrno(PyExc_IOError);
1779 default:
1780 return PyErr_SetFromErrno(PyExc_OSError);
1781 }
1782 }
1783
1784
pwd_struct_to_py(const struct passwd * pwd)1785 static PyObject *pwd_struct_to_py(const struct passwd *pwd)
1786 {
1787 // We can check the known (via POSIX) signed and unsigned types at
1788 // compile time, but not (easily) the unspecified types, so handle
1789 // those via INTEGER_TO_PY().
1790 if (pwd == NULL)
1791 Py_RETURN_NONE;
1792 return Py_BuildValue(cstr_argf cstr_argf "OO"
1793 cstr_argf cstr_argf cstr_argf,
1794 pwd->pw_name,
1795 pwd->pw_passwd,
1796 INTEGER_TO_PY(pwd->pw_uid),
1797 INTEGER_TO_PY(pwd->pw_gid),
1798 pwd->pw_gecos,
1799 pwd->pw_dir,
1800 pwd->pw_shell);
1801 }
1802
bup_getpwuid(PyObject * self,PyObject * args)1803 static PyObject *bup_getpwuid(PyObject *self, PyObject *args)
1804 {
1805 unsigned long long py_uid;
1806 if (!PyArg_ParseTuple(args, "K", &py_uid))
1807 return NULL;
1808 uid_t uid;
1809 if (!INTEGRAL_ASSIGNMENT_FITS(&uid, py_uid))
1810 return PyErr_Format(PyExc_OverflowError, "uid too large for uid_t");
1811
1812 errno = 0;
1813 struct passwd *pwd = getpwuid(uid);
1814 if (!pwd && errno)
1815 return appropriate_errno_ex();
1816 return pwd_struct_to_py(pwd);
1817 }
1818
bup_getpwnam(PyObject * self,PyObject * args)1819 static PyObject *bup_getpwnam(PyObject *self, PyObject *args)
1820 {
1821 PyObject *py_name;
1822 if (!PyArg_ParseTuple(args, "S", &py_name))
1823 return NULL;
1824
1825 char *name = PyBytes_AS_STRING(py_name);
1826 errno = 0;
1827 struct passwd *pwd = getpwnam(name);
1828 if (!pwd && errno)
1829 return appropriate_errno_ex();
1830 return pwd_struct_to_py(pwd);
1831 }
1832
grp_struct_to_py(const struct group * grp)1833 static PyObject *grp_struct_to_py(const struct group *grp)
1834 {
1835 // We can check the known (via POSIX) signed and unsigned types at
1836 // compile time, but not (easily) the unspecified types, so handle
1837 // those via INTEGER_TO_PY().
1838 if (grp == NULL)
1839 Py_RETURN_NONE;
1840
1841 PyObject *members = tuple_from_cstrs(grp->gr_mem);
1842 if (members == NULL)
1843 return NULL;
1844 return Py_BuildValue(cstr_argf cstr_argf "OO",
1845 grp->gr_name,
1846 grp->gr_passwd,
1847 INTEGER_TO_PY(grp->gr_gid),
1848 members);
1849 }
1850
bup_getgrgid(PyObject * self,PyObject * args)1851 static PyObject *bup_getgrgid(PyObject *self, PyObject *args)
1852 {
1853 unsigned long long py_gid;
1854 if (!PyArg_ParseTuple(args, "K", &py_gid))
1855 return NULL;
1856 gid_t gid;
1857 if (!INTEGRAL_ASSIGNMENT_FITS(&gid, py_gid))
1858 return PyErr_Format(PyExc_OverflowError, "gid too large for gid_t");
1859
1860 errno = 0;
1861 struct group *grp = getgrgid(gid);
1862 if (!grp && errno)
1863 return appropriate_errno_ex();
1864 return grp_struct_to_py(grp);
1865 }
1866
bup_getgrnam(PyObject * self,PyObject * args)1867 static PyObject *bup_getgrnam(PyObject *self, PyObject *args)
1868 {
1869 PyObject *py_name;
1870 if (!PyArg_ParseTuple(args, "S", &py_name))
1871 return NULL;
1872
1873 char *name = PyBytes_AS_STRING(py_name);
1874 errno = 0;
1875 struct group *grp = getgrnam(name);
1876 if (!grp && errno)
1877 return appropriate_errno_ex();
1878 return grp_struct_to_py(grp);
1879 }
1880
1881
bup_gethostname(PyObject * mod,PyObject * ignore)1882 static PyObject *bup_gethostname(PyObject *mod, PyObject *ignore)
1883 {
1884 #ifdef HOST_NAME_MAX
1885 char buf[HOST_NAME_MAX + 1] = {};
1886 #else
1887 /* 'SUSv2 guarantees that "Host names are limited to 255 bytes".' */
1888 char buf[256] = {};
1889 #endif
1890
1891 if (gethostname(buf, sizeof(buf) - 1))
1892 return PyErr_SetFromErrno(PyExc_IOError);
1893 return PyBytes_FromString(buf);
1894 }
1895
1896
1897 #ifdef BUP_HAVE_READLINE
1898
cstr_from_bytes(PyObject * bytes)1899 static char *cstr_from_bytes(PyObject *bytes)
1900 {
1901 char *buf;
1902 Py_ssize_t length;
1903 int rc = PyBytes_AsStringAndSize(bytes, &buf, &length);
1904 if (rc == -1)
1905 return NULL;
1906 char *result = checked_malloc(length, sizeof(char));
1907 if (!result)
1908 return NULL;
1909 memcpy(result, buf, length);
1910 return result;
1911 }
1912
cstrs_from_seq(PyObject * seq)1913 static char **cstrs_from_seq(PyObject *seq)
1914 {
1915 char **result = NULL;
1916 seq = PySequence_Fast(seq, "Cannot convert sequence items to C strings");
1917 if (!seq)
1918 return NULL;
1919
1920 const Py_ssize_t len = PySequence_Fast_GET_SIZE(seq);
1921 if (len > PY_SSIZE_T_MAX - 1) {
1922 PyErr_Format(PyExc_OverflowError,
1923 "Sequence length %zd too large for conversion to C array",
1924 len);
1925 goto finish;
1926 }
1927 result = checked_malloc(len + 1, sizeof(char *));
1928 if (!result)
1929 goto finish;
1930 Py_ssize_t i = 0;
1931 for (i = 0; i < len; i++)
1932 {
1933 PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
1934 if (!item)
1935 goto abandon_result;
1936 result[i] = cstr_from_bytes(item);
1937 if (!result[i]) {
1938 i--;
1939 goto abandon_result;
1940 }
1941 }
1942 result[len] = NULL;
1943 goto finish;
1944
1945 abandon_result:
1946 if (result) {
1947 for (; i > 0; i--)
1948 free(result[i]);
1949 free(result);
1950 result = NULL;
1951 }
1952 finish:
1953 Py_DECREF(seq);
1954 return result;
1955 }
1956
1957 static char* our_word_break_chars = NULL;
1958
1959 static PyObject *
bup_set_completer_word_break_characters(PyObject * self,PyObject * args)1960 bup_set_completer_word_break_characters(PyObject *self, PyObject *args)
1961 {
1962 char *bytes;
1963 if (!PyArg_ParseTuple(args, cstr_argf, &bytes))
1964 return NULL;
1965 char *prev = our_word_break_chars;
1966 char *next = strdup(bytes);
1967 if (!next)
1968 return PyErr_NoMemory();
1969 our_word_break_chars = next;
1970 rl_completer_word_break_characters = next;
1971 if (prev)
1972 free(prev);
1973 Py_RETURN_NONE;
1974 }
1975
1976 static PyObject *
bup_get_completer_word_break_characters(PyObject * self,PyObject * args)1977 bup_get_completer_word_break_characters(PyObject *self, PyObject *args)
1978 {
1979 if (!PyArg_ParseTuple(args, ""))
1980 return NULL;
1981 return PyBytes_FromString(rl_completer_word_break_characters);
1982 }
1983
bup_get_line_buffer(PyObject * self,PyObject * args)1984 static PyObject *bup_get_line_buffer(PyObject *self, PyObject *args)
1985 {
1986 if (!PyArg_ParseTuple(args, ""))
1987 return NULL;
1988 return PyBytes_FromString(rl_line_buffer);
1989 }
1990
1991 static PyObject *
bup_parse_and_bind(PyObject * self,PyObject * args)1992 bup_parse_and_bind(PyObject *self, PyObject *args)
1993 {
1994 char *bytes;
1995 if (!PyArg_ParseTuple(args, cstr_argf ":parse_and_bind", &bytes))
1996 return NULL;
1997 char *tmp = strdup(bytes); // Because it may modify the arg
1998 if (!tmp)
1999 return PyErr_NoMemory();
2000 int rc = rl_parse_and_bind(tmp);
2001 free(tmp);
2002 if (rc != 0)
2003 return PyErr_Format(PyExc_OSError,
2004 "system rl_parse_and_bind failed (%d)", rc);
2005 Py_RETURN_NONE;
2006 }
2007
2008
2009 static PyObject *py_on_attempted_completion;
2010 static char **prev_completions;
2011
on_attempted_completion(const char * text,int start,int end)2012 static char **on_attempted_completion(const char *text, int start, int end)
2013 {
2014 if (!py_on_attempted_completion)
2015 return NULL;
2016
2017 char **result = NULL;
2018 PyObject *py_result = PyObject_CallFunction(py_on_attempted_completion,
2019 cstr_argf "ii",
2020 text, start, end);
2021 if (!py_result)
2022 return NULL;
2023 if (py_result != Py_None) {
2024 result = cstrs_from_seq(py_result);
2025 free(prev_completions);
2026 prev_completions = result;
2027 }
2028 Py_DECREF(py_result);
2029 return result;
2030 }
2031
2032 static PyObject *
bup_set_attempted_completion_function(PyObject * self,PyObject * args)2033 bup_set_attempted_completion_function(PyObject *self, PyObject *args)
2034 {
2035 PyObject *completer;
2036 if (!PyArg_ParseTuple(args, "O", &completer))
2037 return NULL;
2038
2039 PyObject *prev = py_on_attempted_completion;
2040 if (completer == Py_None)
2041 {
2042 py_on_attempted_completion = NULL;
2043 rl_attempted_completion_function = NULL;
2044 } else {
2045 py_on_attempted_completion = completer;
2046 rl_attempted_completion_function = on_attempted_completion;
2047 Py_INCREF(completer);
2048 }
2049 Py_XDECREF(prev);
2050 Py_RETURN_NONE;
2051 }
2052
2053
2054 static PyObject *py_on_completion_entry;
2055
on_completion_entry(const char * text,int state)2056 static char *on_completion_entry(const char *text, int state)
2057 {
2058 if (!py_on_completion_entry)
2059 return NULL;
2060
2061 PyObject *py_result = PyObject_CallFunction(py_on_completion_entry,
2062 cstr_argf "i", text, state);
2063 if (!py_result)
2064 return NULL;
2065 char *result = (py_result == Py_None) ? NULL : cstr_from_bytes(py_result);
2066 Py_DECREF(py_result);
2067 return result;
2068 }
2069
2070 static PyObject *
bup_set_completion_entry_function(PyObject * self,PyObject * args)2071 bup_set_completion_entry_function(PyObject *self, PyObject *args)
2072 {
2073 PyObject *completer;
2074 if (!PyArg_ParseTuple(args, "O", &completer))
2075 return NULL;
2076
2077 PyObject *prev = py_on_completion_entry;
2078 if (completer == Py_None) {
2079 py_on_completion_entry = NULL;
2080 rl_completion_entry_function = NULL;
2081 } else {
2082 py_on_completion_entry = completer;
2083 rl_completion_entry_function = on_completion_entry;
2084 Py_INCREF(completer);
2085 }
2086 Py_XDECREF(prev);
2087 Py_RETURN_NONE;
2088 }
2089
2090 static PyObject *
bup_readline(PyObject * self,PyObject * args)2091 bup_readline(PyObject *self, PyObject *args)
2092 {
2093 char *prompt;
2094 if (!PyArg_ParseTuple(args, cstr_argf, &prompt))
2095 return NULL;
2096 char *line = readline(prompt);
2097 if (!line)
2098 return PyErr_Format(PyExc_EOFError, "readline EOF");
2099 PyObject *result = PyBytes_FromString(line);
2100 free(line);
2101 return result;
2102 }
2103
2104 #endif // defined BUP_HAVE_READLINE
2105
2106 #if defined(HAVE_SYS_ACL_H) && \
2107 defined(HAVE_ACL_LIBACL_H) && \
2108 defined(HAVE_ACL_EXTENDED_FILE) && \
2109 defined(HAVE_ACL_GET_FILE) && \
2110 defined(HAVE_ACL_TO_ANY_TEXT) && \
2111 defined(HAVE_ACL_FROM_TEXT) && \
2112 defined(HAVE_ACL_SET_FILE)
2113 #define ACL_SUPPORT 1
2114 #include <sys/acl.h>
2115 #include <acl/libacl.h>
2116
2117 // Returns
2118 // 0 for success
2119 // -1 for errors, with python exception set
2120 // -2 for ignored errors (not supported)
bup_read_acl_to_text(const char * name,acl_type_t type,char ** txt,char ** num)2121 static int bup_read_acl_to_text(const char *name, acl_type_t type,
2122 char **txt, char **num)
2123 {
2124 acl_t acl;
2125
2126 acl = acl_get_file(name, type);
2127 if (!acl) {
2128 if (errno == EOPNOTSUPP || errno == ENOSYS)
2129 return -2;
2130 PyErr_SetFromErrno(PyExc_IOError);
2131 return -1;
2132 }
2133
2134 *num = NULL;
2135 *txt = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE);
2136 if (*txt)
2137 *num = acl_to_any_text(acl, "", '\n', TEXT_ABBREVIATE | TEXT_NUMERIC_IDS);
2138
2139 if (*txt && *num)
2140 return 0;
2141
2142 if (errno == ENOMEM)
2143 PyErr_NoMemory();
2144 else
2145 PyErr_SetFromErrno(PyExc_IOError);
2146
2147 if (*txt)
2148 acl_free((acl_t)*txt);
2149 if (*num)
2150 acl_free((acl_t)*num);
2151
2152 return -1;
2153 }
2154
bup_read_acl(PyObject * self,PyObject * args)2155 static PyObject *bup_read_acl(PyObject *self, PyObject *args)
2156 {
2157 char *name;
2158 int isdir, rv;
2159 PyObject *ret = NULL;
2160 char *acl_txt = NULL, *acl_num = NULL;
2161
2162 if (!PyArg_ParseTuple(args, cstr_argf "i", &name, &isdir))
2163 return NULL;
2164
2165 if (!acl_extended_file(name))
2166 Py_RETURN_NONE;
2167
2168 rv = bup_read_acl_to_text(name, ACL_TYPE_ACCESS, &acl_txt, &acl_num);
2169 if (rv)
2170 goto out;
2171
2172 if (isdir) {
2173 char *def_txt = NULL, *def_num = NULL;
2174
2175 rv = bup_read_acl_to_text(name, ACL_TYPE_DEFAULT, &def_txt, &def_num);
2176 if (rv)
2177 goto out;
2178
2179 ret = Py_BuildValue("[" cstr_argf cstr_argf cstr_argf cstr_argf "]",
2180 acl_txt, acl_num, def_txt, def_num);
2181
2182 if (def_txt)
2183 acl_free((acl_t)def_txt);
2184 if (def_num)
2185 acl_free((acl_t)def_num);
2186 } else {
2187 ret = Py_BuildValue("[" cstr_argf cstr_argf "]",
2188 acl_txt, acl_num);
2189 }
2190
2191 out:
2192 if (acl_txt)
2193 acl_free((acl_t)acl_txt);
2194 if (acl_num)
2195 acl_free((acl_t)acl_num);
2196 if (rv == -2)
2197 Py_RETURN_NONE;
2198 return ret;
2199 }
2200
bup_apply_acl_string(const char * name,const char * s)2201 static int bup_apply_acl_string(const char *name, const char *s)
2202 {
2203 acl_t acl = acl_from_text(s);
2204 int ret = 0;
2205
2206 if (!acl) {
2207 PyErr_SetFromErrno(PyExc_IOError);
2208 return -1;
2209 }
2210
2211 if (acl_set_file(name, ACL_TYPE_ACCESS, acl)) {
2212 PyErr_SetFromErrno(PyExc_IOError);
2213 ret = -1;
2214 }
2215
2216 acl_free(acl);
2217
2218 return ret;
2219 }
2220
bup_apply_acl(PyObject * self,PyObject * args)2221 static PyObject *bup_apply_acl(PyObject *self, PyObject *args)
2222 {
2223 char *name, *acl, *def = NULL;
2224
2225 if (!PyArg_ParseTuple(args, cstr_argf cstr_argf "|" cstr_argf, &name, &acl, &def))
2226 return NULL;
2227
2228 if (bup_apply_acl_string(name, acl))
2229 return NULL;
2230
2231 if (def && bup_apply_acl_string(name, def))
2232 return NULL;
2233
2234 Py_RETURN_NONE;
2235 }
2236 #endif
2237
2238 static PyMethodDef helper_methods[] = {
2239 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
2240 "Write buf excepting zeros at the end. Return trailing zero count." },
2241 { "selftest", selftest, METH_VARARGS,
2242 "Check that the rolling checksum rolls correctly (for unit tests)." },
2243 { "blobbits", blobbits, METH_VARARGS,
2244 "Return the number of bits in the rolling checksum." },
2245 { "splitbuf", splitbuf, METH_VARARGS,
2246 "Split a list of strings based on a rolling checksum." },
2247 { "bitmatch", bitmatch, METH_VARARGS,
2248 "Count the number of matching prefix bits between two strings." },
2249 { "firstword", firstword, METH_VARARGS,
2250 "Return an int corresponding to the first 32 bits of buf." },
2251 { "bloom_contains", bloom_contains, METH_VARARGS,
2252 "Check if a bloom filter of 2^nbits bytes contains an object" },
2253 { "bloom_add", bloom_add, METH_VARARGS,
2254 "Add an object to a bloom filter of 2^nbits bytes" },
2255 { "extract_bits", extract_bits, METH_VARARGS,
2256 "Take the first 'nbits' bits from 'buf' and return them as an int." },
2257 { "merge_into", merge_into, METH_VARARGS,
2258 "Merges a bunch of idx and midx files into a single midx." },
2259 { "write_idx", write_idx, METH_VARARGS,
2260 "Write a PackIdxV2 file from an idx list of lists of tuples" },
2261 { "write_random", write_random, METH_VARARGS,
2262 "Write random bytes to the given file descriptor" },
2263 { "random_sha", random_sha, METH_VARARGS,
2264 "Return a random 20-byte string" },
2265 { "open_noatime", open_noatime, METH_VARARGS,
2266 "open() the given filename for read with O_NOATIME if possible" },
2267 { "fadvise_done", fadvise_done, METH_VARARGS,
2268 "Inform the kernel that we're finished with earlier parts of a file" },
2269 #ifdef BUP_HAVE_FILE_ATTRS
2270 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
2271 "Return the Linux attributes for the given file." },
2272 #endif
2273 #ifdef BUP_HAVE_FILE_ATTRS
2274 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
2275 "Set the Linux attributes for the given file." },
2276 #endif
2277 #ifdef HAVE_UTIMENSAT
2278 { "bup_utimensat", bup_utimensat, METH_VARARGS,
2279 "Change path timestamps with nanosecond precision (POSIX)." },
2280 #endif
2281 #ifdef HAVE_UTIMES
2282 { "bup_utimes", bup_utimes, METH_VARARGS,
2283 "Change path timestamps with microsecond precision." },
2284 #endif
2285 #ifdef HAVE_LUTIMES
2286 { "bup_lutimes", bup_lutimes, METH_VARARGS,
2287 "Change path timestamps with microsecond precision;"
2288 " don't follow symlinks." },
2289 #endif
2290 { "stat", bup_stat, METH_VARARGS,
2291 "Extended version of stat." },
2292 { "lstat", bup_lstat, METH_VARARGS,
2293 "Extended version of lstat." },
2294 { "fstat", bup_fstat, METH_VARARGS,
2295 "Extended version of fstat." },
2296 #ifdef HAVE_TM_TM_GMTOFF
2297 { "localtime", bup_localtime, METH_VARARGS,
2298 "Return struct_time elements plus the timezone offset and name." },
2299 #endif
2300 { "bytescmp", bup_bytescmp, METH_VARARGS,
2301 "Return a negative value if x < y, zero if equal, positive otherwise."},
2302 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
2303 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
2304 #ifdef BUP_MINCORE_BUF_TYPE
2305 { "mincore", bup_mincore, METH_VARARGS,
2306 "For mincore(src, src_n, src_off, dest, dest_off)"
2307 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
2308 #endif
2309 { "getpwuid", bup_getpwuid, METH_VARARGS,
2310 "Return the password database entry for the given numeric user id,"
2311 " as a tuple with all C strings as bytes(), or None if the user does"
2312 " not exist." },
2313 { "getpwnam", bup_getpwnam, METH_VARARGS,
2314 "Return the password database entry for the given user name,"
2315 " as a tuple with all C strings as bytes(), or None if the user does"
2316 " not exist." },
2317 { "getgrgid", bup_getgrgid, METH_VARARGS,
2318 "Return the group database entry for the given numeric group id,"
2319 " as a tuple with all C strings as bytes(), or None if the group does"
2320 " not exist." },
2321 { "getgrnam", bup_getgrnam, METH_VARARGS,
2322 "Return the group database entry for the given group name,"
2323 " as a tuple with all C strings as bytes(), or None if the group does"
2324 " not exist." },
2325 { "gethostname", bup_gethostname, METH_NOARGS,
2326 "Return the current hostname (as bytes)" },
2327 #ifdef BUP_HAVE_READLINE
2328 { "set_completion_entry_function", bup_set_completion_entry_function, METH_VARARGS,
2329 "Set rl_completion_entry_function. Called as f(text, state)." },
2330 { "set_attempted_completion_function", bup_set_attempted_completion_function, METH_VARARGS,
2331 "Set rl_attempted_completion_function. Called as f(text, start, end)." },
2332 { "parse_and_bind", bup_parse_and_bind, METH_VARARGS,
2333 "Call rl_parse_and_bind." },
2334 { "get_line_buffer", bup_get_line_buffer, METH_NOARGS,
2335 "Return rl_line_buffer." },
2336 { "get_completer_word_break_characters", bup_get_completer_word_break_characters, METH_NOARGS,
2337 "Return rl_completer_word_break_characters." },
2338 { "set_completer_word_break_characters", bup_set_completer_word_break_characters, METH_VARARGS,
2339 "Set rl_completer_word_break_characters." },
2340 { "readline", bup_readline, METH_VARARGS,
2341 "Call readline(prompt)." },
2342 #endif // defined BUP_HAVE_READLINE
2343 #ifdef ACL_SUPPORT
2344 { "read_acl", bup_read_acl, METH_VARARGS,
2345 "read_acl(name, isdir)\n\n"
2346 "Read ACLs for the given file/dirname and return the correctly encoded"
2347 " list [txt, num, def_tx, def_num] (the def_* being empty bytestrings"
2348 " unless the second argument 'isdir' is True)." },
2349 { "apply_acl", bup_apply_acl, METH_VARARGS,
2350 "apply_acl(name, acl, def=None)\n\n"
2351 "Given a file/dirname (bytes) and the ACLs to restore, do that." },
2352 #endif /* HAVE_ACLS */
2353 { NULL, NULL, 0, NULL }, // sentinel
2354 };
2355
test_integral_assignment_fits(void)2356 static void test_integral_assignment_fits(void)
2357 {
2358 assert(sizeof(signed short) == sizeof(unsigned short));
2359 assert(sizeof(signed short) < sizeof(signed long long));
2360 assert(sizeof(signed short) < sizeof(unsigned long long));
2361 assert(sizeof(unsigned short) < sizeof(signed long long));
2362 assert(sizeof(unsigned short) < sizeof(unsigned long long));
2363 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
2364 {
2365 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
2366 unsigned short us, usmax = USHRT_MAX;
2367 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
2368 unsigned long long ullmax = ULLONG_MAX;
2369
2370 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
2371 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
2372 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
2373 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
2374 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
2375 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
2376
2377 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
2378 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
2379 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
2380 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
2381 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
2382 }
2383 }
2384
setup_module(PyObject * m)2385 static int setup_module(PyObject *m)
2386 {
2387 // FIXME: migrate these tests to configure, or at least don't
2388 // possibly crash the whole application. Check against the type
2389 // we're going to use when passing to python. Other stat types
2390 // are tested at runtime.
2391 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
2392 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
2393 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
2394 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
2395 // Just be sure (relevant when passing timestamps back to Python above).
2396 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
2397 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
2398
2399 test_integral_assignment_fits();
2400
2401 // Originally required by append_sparse_region()
2402 {
2403 off_t probe;
2404 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
2405 {
2406 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
2407 exit(1);
2408 }
2409 }
2410
2411 char *e;
2412 #pragma clang diagnostic push
2413 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
2414 {
2415 PyObject *value;
2416 value = INTEGER_TO_PY(INT_MAX);
2417 PyObject_SetAttrString(m, "INT_MAX", value);
2418 Py_DECREF(value);
2419 value = INTEGER_TO_PY(UINT_MAX);
2420 PyObject_SetAttrString(m, "UINT_MAX", value);
2421 Py_DECREF(value);
2422 }
2423 #ifdef HAVE_UTIMENSAT
2424 {
2425 PyObject *value;
2426 value = INTEGER_TO_PY(AT_FDCWD);
2427 PyObject_SetAttrString(m, "AT_FDCWD", value);
2428 Py_DECREF(value);
2429 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
2430 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
2431 Py_DECREF(value);
2432 value = INTEGER_TO_PY(UTIME_NOW);
2433 PyObject_SetAttrString(m, "UTIME_NOW", value);
2434 Py_DECREF(value);
2435 }
2436 #endif
2437 #ifdef BUP_HAVE_MINCORE_INCORE
2438 {
2439 PyObject *value;
2440 value = INTEGER_TO_PY(MINCORE_INCORE);
2441 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
2442 Py_DECREF(value);
2443 }
2444 #endif
2445 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
2446
2447 e = getenv("BUP_FORCE_TTY");
2448 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
2449 unpythonize_argv();
2450 return 1;
2451 }
2452
2453
2454 #if PY_MAJOR_VERSION < 3
2455
init_helpers(void)2456 PyMODINIT_FUNC init_helpers(void)
2457 {
2458 PyObject *m = Py_InitModule("_helpers", helper_methods);
2459 if (m == NULL)
2460 return;
2461
2462 if (!setup_module(m))
2463 {
2464 Py_DECREF(m);
2465 return;
2466 }
2467 }
2468
2469 # else // PY_MAJOR_VERSION >= 3
2470
2471 static struct PyModuleDef helpers_def = {
2472 PyModuleDef_HEAD_INIT,
2473 "_helpers",
2474 NULL,
2475 sizeof(state_t),
2476 helper_methods,
2477 NULL,
2478 NULL, // helpers_traverse,
2479 NULL, // helpers_clear,
2480 NULL
2481 };
2482
PyInit__helpers(void)2483 PyMODINIT_FUNC PyInit__helpers(void)
2484 {
2485 PyObject *module = PyModule_Create(&helpers_def);
2486 if (module == NULL)
2487 return NULL;
2488 if (!setup_module(module))
2489 {
2490 Py_DECREF(module);
2491 return NULL;
2492 }
2493 return module;
2494 }
2495
2496 #endif // PY_MAJOR_VERSION >= 3
2497