Debian Codegraph @

src/import/test-tar.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/stat.h>
4
5 #include "errno-util.h"
6 #include "fd-util.h"
7 #include "libarchive-util.h"
8 #include "main-func.h"
9 #include "tar-util.h"
10 #include "tests.h"
11
12 static int run(int argc, char **argv) {
13 int r;
14
15 test_setup_logging(LOG_DEBUG);
16
17 if (argc != 4)
18 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
19 "Need three arguments exactly: -c <output> <input> | -x <input> <output>");
20
21 bool create;
22 if (streq(argv[1], "-c"))
23 create = true;
24 else if (streq(argv[1], "-x"))
25 create = false;
26 else
27 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown operation '%s'.", argv[1]);
28
29 r = dlopen_libarchive(LOG_DEBUG);
30 if (r < 0)
31 return r;
32
33 int flags = create ? O_CREAT | O_WRONLY | O_TRUNC : O_RDONLY;
34 _cleanup_close_ int fd1 = RET_NERRNO(open(argv[2], flags | O_CLOEXEC, 0666));
35 if (fd1 < 0)
36 return log_error_errno(fd1, "Cannot open %s: %m", argv[2]);
37
38 if (!create) {
39 r = RET_NERRNO(mkdir(argv[3], 0777));
40 if (r < 0 && r != -EEXIST)
41 return log_error_errno(r, "Failed to mkdir %s: %m", argv[3]);
42 }
43
44 _cleanup_close_ int fd2 = RET_NERRNO(open(argv[3], O_DIRECTORY | O_CLOEXEC));
45 if (fd2 < 0)
46 return log_error_errno(fd2, "Cannot open %s: %m", argv[3]);
47
48 if (create)
49 r = tar_c(fd2, fd1, argv[2], /* flags= */ TAR_SELINUX);
50 else
51 r = tar_x(fd1, fd2, /* flags= */ TAR_SELINUX);
52 if (r < 0)
53 return log_error_errno(r, "tar %s failed: %m", argv[1]);
54
55 return 0;
56 }
57
58 DEFINE_MAIN_FUNCTION(run);