summaryrefslogtreecommitdiff
path: root/Userland/cp.cpp
blob: 22c2b003ff52f732689353e511d366056909cfac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#include <AK/String.h>
#include <AK/FileSystemPath.h>
#include <AK/StringBuilder.h>
#include <LibCore/CArgsParser.h>
#include <LibCore/CDirIterator.h>
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

bool copy_file_or_directory(String, String, bool);
bool copy_file(String, String, struct stat, int);
bool copy_directory(String, String);

int main(int argc, char** argv)
{
    if (pledge("stdio rpath wpath cpath fattr", nullptr) < 0) {
        perror("pledge");
        return 1;
    }

    CArgsParser args_parser("cp");
    args_parser.add_arg("r", "copy directories recursively");
    args_parser.add_required_single_value("source");
    args_parser.add_required_single_value("destination");

    CArgsParserResult args = args_parser.parse(argc, argv);
    Vector<String> values = args.get_single_values();
    if (values.size() == 0) {
        args_parser.print_usage();
        return 0;
    }
    bool recursion_allowed = args.is_present("r");
    String src_path = values[0];
    String dst_path = values[1];
    return copy_file_or_directory(src_path, dst_path, recursion_allowed) ? 0 : 1;
}

/**
 * Copy a file or directory to a new location. Returns true if successful, false 
 * otherwise. If there is an error, its description is output to stderr.
 * 
 * Directories should only be copied if recursion_allowed is set.
 */
bool copy_file_or_directory(String src_path, String dst_path, bool recursion_allowed)
{
    int src_fd = open(src_path.characters(), O_RDONLY);
    if (src_fd < 0) {
        perror("open src");
        return false;
    }

    struct stat src_stat;
    int rc = fstat(src_fd, &src_stat);
    if (rc < 0) {
        perror("stat src");
        return false;
    }

    if (S_ISDIR(src_stat.st_mode)) {
        if (!recursion_allowed) {
            fprintf(stderr, "cp: -r not specified; omitting directory '%s'\n", src_path.characters());
            return false;
        }
        return copy_directory(src_path, dst_path);
    }
    return copy_file(src_path, dst_path, src_stat, src_fd);
}

/**
 * Copy a source file to a destination file. Returns true if successful, false 
 * otherwise. If there is an error, its description is output to stderr.
 * 
 * To avoid repeated work, the source file's stat and file descriptor are required.
 */
bool copy_file(String src_path, String dst_path, struct stat src_stat, int src_fd)
{
    int dst_fd = creat(dst_path.characters(), 0666);
    if (dst_fd < 0) {
        if (errno != EISDIR) {
            perror("open dst");
            return false;
        }
        StringBuilder builder;
        builder.append(dst_path);
        builder.append('/');
        builder.append(FileSystemPath(src_path).basename());
        dst_path = builder.to_string();
        dst_fd = creat(dst_path.characters(), 0666);
        if (dst_fd < 0) {
            perror("open dst");
            return false;
        }
    }

    if (src_stat.st_size > 0) {
        if (ftruncate(dst_fd, src_stat.st_size) < 0) {
            perror("cp: ftruncate");
            return false;
        }
    }

    for (;;) {
        char buffer[32768];
        ssize_t nread = read(src_fd, buffer, sizeof(buffer));
        if (nread < 0) {
            perror("read src");
            return false;
        }
        if (nread == 0)
            break;
        ssize_t remaining_to_write = nread;
        char* bufptr = buffer;
        while (remaining_to_write) {
            ssize_t nwritten = write(dst_fd, bufptr, remaining_to_write);
            if (nwritten < 0) {
                perror("write dst");
                return false;
            }
            assert(nwritten > 0);
            remaining_to_write -= nwritten;
            bufptr += nwritten;
        }
    }

    auto my_umask = umask(0);
    umask(my_umask);
    int rc = fchmod(dst_fd, src_stat.st_mode & ~my_umask);
    if (rc < 0) {
        perror("fchmod dst");
        return false;
    }

    close(src_fd);
    close(dst_fd);
    return true;
}

/**
 * Copy the contents of a source directory into a destination directory.
 */
bool copy_directory(String src_path, String dst_path)
{
    int rc = mkdir(dst_path.characters(), 0755);
    if (rc < 0) {
        perror("cp: mkdir");
        return false;
    }
    CDirIterator di(src_path, CDirIterator::SkipDots);
    if (di.has_error()) {
        fprintf(stderr, "cp: CDirIterator: %s\n", di.error_string());
        return false;
    }
    while (di.has_next()) {
        String filename = di.next_path();
        bool is_copied = copy_file_or_directory(
            String::format("%s/%s", src_path.characters(), filename.characters()),
            String::format("%s/%s", dst_path.characters(), filename.characters()),
            true);
        if (!is_copied) {
            return false;
        }
    }
    return true;
}