1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <sys/sendfile.h>
21
22 #include "filepath_util.h"
23
24 /**
25 * @tc.name : sendfile_0100
26 * @tc.desc : transfer data between file descriptors
27 * @tc.level : Level 0
28 */
sendfile_0100(void)29 void sendfile_0100(void)
30 {
31 char fromfile[PATH_MAX] = {0};
32 char tofile[PATH_MAX] = {0};
33 FILE_ABSOLUTE_PATH(STR_FILE_FROM_TXT, fromfile);
34 FILE_ABSOLUTE_PATH(STR_FILE_TO_TXT, tofile);
35
36 FILE *f = fopen(fromfile, "w+");
37 const char src[] = "A";
38 fwrite(src, strlen(src), 1, f);
39 fclose(f);
40
41 f = fopen(tofile, "w+");
42 fclose(f);
43
44 int fromfd = open(fromfile, O_RDONLY);
45 if (fromfd < 0) {
46 t_error("%s failed: open. fromfd = %d\n", __func__, fromfd);
47 }
48
49 int tofd = open(tofile, O_WRONLY | O_CREAT, TEST_MODE);
50 if (tofd < 0) {
51 t_error("%s failed: open. tofd = %d\n", __func__, tofd);
52 }
53
54 off_t off = 0;
55 int result = sendfile(tofd, fromfd, &off, 1);
56 if (result < 0) {
57 t_error("%s failed: sendfile. result = %d\n", __func__, result);
58 }
59
60 close(fromfd);
61 close(tofd);
62
63 f = fopen(tofile, "r");
64 char buf[sizeof(src) + 1] = {0};
65 fread(buf, 1, strlen(src), f);
66 fclose(f);
67
68 if (strcmp(src, buf)) {
69 t_error("%s failed: sendfile. buf = %s\n", __func__, buf);
70 }
71
72 remove(fromfile);
73 remove(tofile);
74 }
75
76 /**
77 * @tc.name : sendfile_0200
78 * @tc.desc : transfer data between invalid file descriptors
79 * @tc.level : Level 2
80 */
sendfile_0200(void)81 void sendfile_0200(void)
82 {
83 int fromfd = -1;
84 int tofd = -1;
85 off_t off = 0;
86
87 int result = sendfile(tofd, fromfd, &off, 1);
88 if (result >= 0) {
89 t_error("%s failed: sendfile. result = %d\n", __func__, result);
90 }
91
92 if (errno != EBADF) {
93 t_error("%s failed: sendfile. errno = %d\n", __func__, errno);
94 }
95 }
96
main(int argc,char * argv[])97 int main(int argc, char *argv[])
98 {
99 sendfile_0100();
100 sendfile_0200();
101
102 return t_status;
103 }
104