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 <fcntl.h>
17#include <stdlib.h>
18#include <unistd.h>
19#include "functionalext.h"
20
21const int32_t CREAT_MODE = 666;
22
23/**
24 * @tc.name      : linkat_0100
25 * @tc.desc      : Vertify linkat process success.
26 * @tc.level     : Level 0
27 */
28void linkat_0100(void)
29{
30    int fd1 = creat("/etc/test.txt", CREAT_MODE);
31    int fd2 = -1;
32    if (fd1 < 0) {
33        EXPECT_MT("linkat_0100", fd1, 0);
34        return;
35    } else {
36        close(fd1);
37    }
38    int result = linkat(fd1, "/etc/test.txt", fd2, "/etc/linkat.txt", AT_SYMLINK_FOLLOW);
39    EXPECT_EQ("linkat_0100", result, 0);
40    EXPECT_EQ("linkat_0100", access("/etc/linkat.txt", F_OK), 0);
41    system("rm -f /etc/linkat.txt");
42}
43
44/**
45 * @tc.name      : linkat_0200
46 * @tc.desc      : Vertify linkat process fail. Beceause creating a hard linkat file with the same name.
47 * @tc.level     : Level 2
48 */
49void linkat_0200(void)
50{
51    int fd1 = creat("/etc/test.txt", CREAT_MODE);
52    int fd2 = -1;
53    if (access("/etc/linkat.txt", F_OK) != 0) {
54        system("touch /etc/test.txt");
55        if (fd1 < 0) {
56            EXPECT_MT("linkat_0100", fd1, 0);
57            return;
58        } else {
59            close(fd1);
60        }
61        int result = linkat(fd1, "/etc/test.txt", fd2, "/etc/linkat.txt", AT_SYMLINK_FOLLOW);
62        EXPECT_EQ("linkat_0200", result, 0);
63    }
64    EXPECT_NE("linkat_0200", linkat(fd1, "/etc/test.txt", fd2, "/etc/linkat.txt", AT_SYMLINK_FOLLOW), 0);
65    EXPECT_EQ("linkat_0200", errno, EEXIST);
66    system("rm -f /etc/linkat.txt");
67}
68
69/**
70 * @tc.name      : linkat_0300
71 * @tc.desc      : Vertify linkat process fail. Beceause param is invalid.
72 * @tc.level     : Level 2
73 */
74void linkat_0300(void)
75{
76    int result = linkat(-1, NULL, -1, NULL, -1);
77    EXPECT_EQ("linkat_0300", result, ERREXPECT);
78    EXPECT_EQ("linkat_0300", errno, EINVAL);
79
80    if (access("/etc/test.txt", F_OK) == 0) {
81        system("rm -f /etc/test.txt");
82    }
83
84    if (access("/etc/linkat.txt", F_OK) == 0) {
85        system("rm -f /etc/linkat.txt");
86    }
87}
88
89int main(void)
90{
91    linkat_0100();
92    linkat_0200();
93    linkat_0300();
94    return t_status;
95}