xref: /freebsd/contrib/libarchive/cpio/test/test_extract_cpio_absolute_paths.c (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2024 Mostyn Bramley-Moore <mostyn@antipode.se>
5  */
6 
7 #include "test.h"
8 
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #if defined(_WIN32) && !defined(__CYGWIN__)
13 #define UNLINK _unlink
14 #else
15 #define UNLINK unlink
16 #endif
17 
18 DEFINE_TEST(test_extract_cpio_absolute_paths)
19 {
20 	int r;
21 
22 	// Create an absolute path for a test file inside testworkdir.
23 	const char *entry_suffix = "/cpio-noabs";
24 	size_t entry_suffix_length = strlen(entry_suffix);
25 	size_t testworkdir_length = strlen(testworkdir);
26 	size_t temp_absolute_file_name_length = testworkdir_length + entry_suffix_length;
27 	char *temp_absolute_file_name = calloc(1, temp_absolute_file_name_length + 1); // +1 for null character.
28 	assertEqualInt(snprintf(temp_absolute_file_name, temp_absolute_file_name_length + 1, "%s%s", testworkdir, entry_suffix),
29 		temp_absolute_file_name_length);
30 
31 	// Create the file.
32 	const char *sample_data = "test file from test_extract_cpio_absolute_paths";
33 	assertMakeFile(temp_absolute_file_name, 0644, sample_data);
34 
35 	// Create an archive with the test file, using an absolute path.
36 	assertMakeFile("filelist", 0644, temp_absolute_file_name);
37 	r = systemf("%s -o < filelist > archive.cpio 2> stderr1.txt", testprog);
38 	assertEqualInt(r, 0);
39 
40 	// Ensure that the temp file does not exist.
41 	UNLINK(temp_absolute_file_name);
42 
43 	// We should refuse to create the absolute path without --insecure.
44 	r = systemf("%s -i < archive.cpio 2> stderr2.txt", testprog);
45 	assert(r != 0);
46 	assertFileNotExists(temp_absolute_file_name);
47 	UNLINK(temp_absolute_file_name); // Cleanup just in case.
48 
49 	// But if we specify --insecure then the absolute path should be created.
50 	r = systemf("%s -i --insecure < archive.cpio 2> stderr3.txt", testprog);
51 	assert(r == 0);
52 	assertFileExists(temp_absolute_file_name);
53 }
54