xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/splice/splice05.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Red Hat, Inc.
4  * Author: Boyang Xue <[email protected]>
5  */
6 
7 /*
8  * Functional test for splice(2): pipe <-> socket
9  *
10  * This test case tests splice(2) from a pipe to a socket and vice versa
11  */
12 
13 #define _GNU_SOURCE
14 #include <errno.h>
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <sys/stat.h>
18 #include <sys/wait.h>
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include "tst_test.h"
23 #include "lapi/splice.h"
24 #include "splice.h"
25 
26 #define PIPE_MAX (64*1024)
27 
28 static char *str_len_data;
29 static int num_len_data = PIPE_MAX;
30 static char *arr_in, *arr_out;
31 
setup(void)32 static void setup(void)
33 {
34 	int i, pipe_limit;
35 
36 	pipe_limit = get_max_limit(num_len_data);
37 	num_len_data = pipe_limit;
38 
39 	if (tst_parse_int(str_len_data, &num_len_data, 1, pipe_limit)) {
40 		tst_brk(TBROK, "Invalid length of data: '%s', "
41 			"valid value: [1, %d]", str_len_data, pipe_limit);
42 	}
43 	tst_res(TINFO, "splice size = %d", num_len_data);
44 	arr_in = SAFE_MALLOC(num_len_data);
45 	arr_out = SAFE_MALLOC(num_len_data);
46 	for (i = 0; i < num_len_data; i++)
47 		arr_in[i] = i & 0xff;
48 
49 }
50 
cleanup(void)51 static void cleanup(void)
52 {
53 	free(arr_in);
54 	free(arr_out);
55 }
56 
pipe_socket(void)57 static void pipe_socket(void)
58 {
59 	int pp1[2], pp2[2], sv[2], i, ret;
60 
61 	SAFE_PIPE(pp1);
62 	SAFE_PIPE(pp2);
63 	SAFE_SOCKETPAIR(AF_UNIX, SOCK_STREAM, 0, sv);
64 
65 	SAFE_WRITE(SAFE_WRITE_ALL, pp1[1], arr_in, num_len_data);
66 	for (i = num_len_data; i > 0; i = i - ret) {
67 		ret = splice(pp1[0], NULL, sv[0], 0, i, 0);
68 		if (ret == -1) {
69 			tst_res(TFAIL | TERRNO, "splice error");
70 			goto exit;
71 		}
72 	}
73 	for (i = num_len_data; i > 0; i = i - ret) {
74 		ret = splice(sv[1], 0, pp2[1], NULL, i, 0);
75 		if (ret == -1) {
76 			if (errno == EINVAL) {
77 				tst_res(TCONF, "splice does not support "
78 					"af_unix sockets");
79 			} else {
80 				tst_res(TFAIL | TERRNO, "splice error");
81 			}
82 			goto exit;
83 		}
84 		SAFE_READ(1, pp2[0], arr_out + num_len_data - i, ret);
85 	}
86 
87 	for (i = 0; i < num_len_data; i++) {
88 		if (arr_in[i] != arr_out[i]) {
89 			tst_res(TFAIL, "wrong data at %d: expected: %d, "
90 				"actual: %d", i, arr_in[i], arr_out[i]);
91 			goto exit;
92 		}
93 	}
94 	tst_res(TPASS, "splice(2): pipe <-> socket run pass.");
95 exit:
96 	for (i = 0; i < 2; i++) {
97 		SAFE_CLOSE(pp1[i]);
98 		SAFE_CLOSE(pp2[i]);
99 		SAFE_CLOSE(sv[i]);
100 	}
101 }
102 
103 static struct tst_test test = {
104 	.test_all = pipe_socket,
105 	.setup = setup,
106 	.cleanup = cleanup,
107 	.options = (struct tst_option[]) {
108 		{"l:", &str_len_data, "Length of test data (in bytes)"},
109 		{}
110 	},
111 };
112