aboutsummaryrefslogtreecommitdiff
path: root/src/std/file.c
blob: 84f4b0ce88e1b6f2780f8177f6f7978716b0ce36 (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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#include "../../include/std/file.h"
#include "../../include/std/mem.h"
#include "../../include/std/log.h"
#include "../../include/std/alloc.h"
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define SCANDIR_PATH_LENGTH 4096
#define MAX_FILE_SIZE 1024*1024*48 /* 48 mb */
#if 0

static int scan_dir_recursive_internal(char *dir_path, int path_length, scan_dir_callback_func callback_func, void *userdata) {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stats;
    int filename_length;
    int path_length_start;

    path_length_start = path_length;
    if((dir = opendir(dir_path)) == NULL) {
        int error;
        error = errno;
        amal_log_perror("scan_dir_recursive");
        return error;
    }

    while((entry = readdir(dir)) != NULL) {
        /*
        Skip hidden files. Name will always at least include null terminator
        so it's ok to not check filename length. And file names are never empty, right???
        */
        if(entry->d_name[0] == '.')
            continue;

        /* Reset path concat, because it's overwritten by recursive call to scan dir */
        path_length = path_length_start;
        filename_length = strlen(entry->d_name);
        /* current path '/' filename '\0' */
        if(path_length + 1 + filename_length + 1 > SCANDIR_PATH_LENGTH) {
            amal_log_error("Filepath too long. Trying to append %s to %s", entry->d_name, dir_path);
            return -1;
        }

        /* Replace '\0' with '/' */
        dir_path[path_length] = '/';
        ++path_length;
        am_memcpy(&dir_path[path_length], entry->d_name, filename_length);
        path_length += filename_length;
        dir_path[path_length] = '\0';
        
        if(stat(dir_path, &file_stats) == -1) {
            amal_log_perror("scan_dir_recursive_internal");
            goto cleanup;
        }

        if(S_ISDIR(file_stats.st_mode)) {
            cleanup_if_error(scan_dir_recursive_internal(dir_path, path_length, callback_func, userdata));
        } else if(S_ISREG(file_stats.st_mode)) {
            if(!callback_func(dir_path, path_length, userdata))
                goto cleanup_noerr;
        } else if(S_ISLNK(file_stats.st_mode)) {
            amal_log_warning("Symlink ignored: %s", entry->d_name);
        } else {
            /* Ignore block devices and all other types of files */
        }
    }

    cleanup_noerr:
    closedir(dir);
    return 0;

    cleanup:
    closedir(dir);
    return -1;
}

int scan_dir_recursive(const char *dir_path, scan_dir_callback_func callback_func, void *userdata) {
    char scandir_path[SCANDIR_PATH_LENGTH];
    int dir_path_length = strlen(dir_path) + 1; /* include null terminator */
    am_memcpy(scandir_path, dir_path, dir_path_length);
    return scan_dir_recursive_internal(scandir_path, dir_path_length - 1, callback_func, userdata);
}

static int mapped_file_mode_to_system_file_mode(MappedFileMode file_mode) {
    switch(file_mode) {
        case MAPPED_FILE_READ:          return PROT_READ;
        case MAPPED_FILE_WRITE:         return PROT_WRITE;
        case MAPPED_FILE_READ_WRITE:    return PROT_READ | PROT_WRITE;
        default:
            assert(bool_false);
            return PROT_READ;
    }
}

static int mapped_file_mode_to_open_mode(MappedFileMode file_mode) {
    switch(file_mode) {
        case MAPPED_FILE_READ:          return O_RDONLY;
        case MAPPED_FILE_WRITE:         return O_WRONLY;
        case MAPPED_FILE_READ_WRITE:    return O_RDWR;
        default:
            assert(bool_false);
            return O_RDONLY;
    }
}

int mapped_file_init(MappedFile *self, const char *filepath, MappedFileMode file_mode) {
    struct stat file_stats;
    int fd;
    const char *memblock;
    int map_file_system_mode;

    self->file_data = NULL;
    self->file_size = 0;
    self->fd = -1;

    fd = open(filepath, mapped_file_mode_to_open_mode(file_mode));
    if(fd == -1) return errno;
    if(fstat(fd, &file_stats) == -1) {
        amal_log_perror(filepath);
        goto cleanup;
    }

    map_file_system_mode = mapped_file_mode_to_system_file_mode(file_mode);
    memblock = mmap(NULL, file_stats.st_size, map_file_system_mode, MAP_SHARED, fd, 0);
    if(memblock == MAP_FAILED) {
        amal_log_perror(filepath);
        goto cleanup;
    }

    self->file_data = memblock;
    self->file_size = file_stats.st_size;
    self->fd = fd;
    return 0;

    cleanup:
    close(fd);
    return -1;
}

int mapped_file_deinit(MappedFile *self) {
    int result_munmap;
    int result_close;

    if(!self->file_data)
        return 0;
    
    result_munmap = munmap((void*)self->file_data, self->file_size);
    if(result_munmap == -1)
        amal_log_perror("mapped_file_deinit");
    result_close = close(self->fd);
    if(result_close == -1)
        amal_log_perror("mapped_file_deinit");
    self->file_data = NULL;
    self->file_size = 0;
    self->fd = 0;
    if(result_munmap == -1 || result_close == -1)
        return -1;
    else
        return 0;
}
#endif

typedef enum {
    REGULAR,
    DIRECTORY,
    OTHER
} FileType;

static CHECK_RESULT int file_get_type(const char *filepath, FileType *type) {
    struct stat file_stats;
    if(stat(filepath, &file_stats) == -1) {
        amal_log_error("file_get_type: %s failed: ", filepath, strerror(errno));
        return -1;
    }

    if(file_stats.st_mode & S_IFDIR)
        *type = DIRECTORY;
    else if(file_stats.st_mode & S_IFREG)
        *type = REGULAR;
    else
        *type = OTHER;
    return 0;
}

int read_whole_file(const char *filepath, Buffer *data_result) {
    FileType file_type;
    FILE *file;
    int result;
    usize bytes_read;
    usize size;

    return_if_error(file_get_type(filepath, &file_type));
    if(file_type != REGULAR) {
        amal_log_error("Expected file %s to be a regular file", filepath);
        return -2;
    }

    file = fopen(filepath, "rb");
    if(!file) {
        int error;
        error = errno;
        amal_log_error("read_whole_file: %s failed: ", filepath, strerror(error));
        return error;
    }

    result = fseek(file, 0, SEEK_END);
    if(result != 0) {
        result = ferror(file);
        goto cleanup;
    }
    
    size = ftell(file);
    result = fseek(file, 0, SEEK_SET);
    if(result != 0) {
        result = ferror(file);
        goto cleanup;
    }

    if(size > MAX_FILE_SIZE) {
        amal_log_error("File %s is too large (larger than 48 megabytes)", filepath);
        result = -1;
        goto cleanup;
    }

    assert(data_result->capacity == 0 && data_result->size == 0);
    cleanup_if_error(buffer_append_empty(data_result, size));
    bytes_read = fread(data_result->data, 1, data_result->size, file);
    if(bytes_read != size)
        result = ferror(file);

    cleanup:
    fclose(file);
    return result;
}

int file_get_canonical_path(const char *filepath, char **result_path, usize *result_path_size) {
    char result_path_tmp[PATH_MAX];
    if(!realpath(filepath, result_path_tmp)) {
        int ret;
        ret = errno;
        amal_log_error("file_get_canonical_path: realpath failed for path %s, error: %s", filepath, strerror(ret));
        return ret;
    }
    *result_path_size = strnlen(result_path_tmp, PATH_MAX);
    return_if_error(am_malloc(*result_path_size + 1, (void**)result_path));
    am_memcpy(*result_path, result_path_tmp, *result_path_size);
    (*result_path)[*result_path_size] = '\0';
    return 0;
}

BufferView file_get_parent_directory(BufferView filepath) {
    int i;
    for(i = filepath.size - 1; i >= 0; --i) {
        if(filepath.data[i] == '/')
            return create_buffer_view(filepath.data, i);
    }
    return create_buffer_view(filepath.data, 0);
}

BufferView file_get_name(BufferView filepath) {
    int i;
    for(i = filepath.size - 1; i >= 0; --i) {
        if(filepath.data[i] == '/')
            return create_buffer_view(filepath.data + i, filepath.size - i);
    }
    return filepath;
}