]> ruderich.org/simon Gitweb - nsscash/nsscash.git/blob - nss/file.c
nss: simplify initialization of struct file in map_file()
[nsscash/nsscash.git] / nss / file.c
1 /*
2  * Load and unload nsscash files
3  *
4  * Copyright (C) 2019  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
18  */
19
20 #include "file.h"
21
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/mman.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31
32 bool map_file(const char *path, struct file *f) {
33     // Fully initialize the struct for unmap_file() and other users
34     memset(f, 0, sizeof(*f));
35
36     f->fd = open(path, O_RDONLY | O_CLOEXEC);
37     if (f->fd < 0) {
38         goto fail;
39     }
40     struct stat s;
41     if (fstat(f->fd, &s)) {
42         goto fail;
43     }
44     f->size = (size_t)s.st_size;
45
46     void *x = mmap(NULL, f->size, PROT_READ, MAP_PRIVATE, f->fd, 0);
47     if (x == MAP_FAILED) {
48         goto fail;
49     }
50
51     const struct header *h = x;
52     f->header = h;
53
54     // Check MAGIC
55     if (memcmp(h->magic, MAGIC, sizeof(h->magic))) {
56         errno = EINVAL;
57         goto fail;
58     }
59     // Only version 1 is supported at the moment; this will also prevent
60     // running on big-endian systems which is currently not possible
61     if (h->version != 1) {
62         errno = EINVAL;
63         goto fail;
64     }
65
66     return true;
67
68 fail: {
69         int save_errno = errno;
70         unmap_file(f);
71         errno = save_errno;
72         return false;
73     }
74 }
75
76 void unmap_file(struct file *f) {
77     if (f->header != NULL) {
78         munmap((void *)f->header, f->size);
79         f->header = NULL;
80     }
81     if (f->fd >= 0) {
82         close(f->fd);
83         f->fd = -1;
84     }
85 }