]> wimlib.net Git - wimlib/blob - src/textfile.c
inode.h, inode.c cleanup
[wimlib] / src / textfile.c
1 /*
2  * textfile.c
3  */
4
5 /*
6  * Copyright (C) 2014 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include "wimlib/encoding.h"
27 #include "wimlib/error.h"
28 #include "wimlib/file_io.h"
29 #include "wimlib/textfile.h"
30 #include "wimlib/util.h"
31
32 #include <ctype.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <unistd.h>
38
39 static int
40 read_file_contents(const tchar *path, void **buf_ret, size_t *bufsize_ret)
41 {
42         int raw_fd;
43         struct filedes fd;
44         struct stat st;
45         void *buf;
46         int ret;
47         int errno_save;
48
49         if (!path || !*path)
50                 return WIMLIB_ERR_INVALID_PARAM;
51
52         raw_fd = topen(path, O_RDONLY | O_BINARY);
53         if (raw_fd < 0) {
54                 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", path);
55                 return WIMLIB_ERR_OPEN;
56         }
57         if (fstat(raw_fd, &st)) {
58                 ERROR_WITH_ERRNO("Can't stat \"%"TS"\"", path);
59                 close(raw_fd);
60                 return WIMLIB_ERR_STAT;
61         }
62         if ((size_t)st.st_size != st.st_size ||
63             (buf = MALLOC(st.st_size)) == NULL)
64         {
65                 close(raw_fd);
66                 ERROR("Not enough memory to read \"%"TS"\"", path);
67                 return WIMLIB_ERR_NOMEM;
68         }
69
70         filedes_init(&fd, raw_fd);
71         ret = full_read(&fd, buf, st.st_size);
72         errno_save = errno;
73         filedes_close(&fd);
74         errno = errno_save;
75         if (ret) {
76                 ERROR_WITH_ERRNO("Error reading \"%"TS"\"", path);
77                 FREE(buf);
78                 return ret;
79         }
80
81         *buf_ret = buf;
82         *bufsize_ret = st.st_size;
83         return 0;
84 }
85
86 static int
87 translate_text_buffer(const u8 *buf_raw, size_t bufsize_raw,
88                       tchar **tstr_ret, size_t *tstr_nchars_ret)
89 {
90         size_t offset_raw;
91         bool utf8;
92         tchar *buf_tstr;
93         size_t bufsize_tstr;
94         int ret;
95
96         /* Guess the encoding: UTF-8 or UTF-16LE.  (Something weirder and you're
97          * out of luck, sorry...)  */
98         if (bufsize_raw >= 2 &&
99             buf_raw[0] == 0xFF &&
100             buf_raw[1] == 0xFE)
101         {
102                 utf8 = false;
103                 offset_raw = 2;
104         }
105         else if (bufsize_raw >= 2 &&
106                  buf_raw[0] <= 0x7F &&
107                  buf_raw[1] == 0x00)
108         {
109                 utf8 = false;
110                 offset_raw = 0;
111         }
112         else if (bufsize_raw >= 3 &&
113                  buf_raw[0] == 0xEF &&
114                  buf_raw[1] == 0xBB &&
115                  buf_raw[2] == 0xBF)
116         {
117                 utf8 = true;
118                 offset_raw = 3;
119         }
120         else
121         {
122                 utf8 = true;
123                 offset_raw = 0;
124         }
125
126         if (utf8) {
127                 ret = utf8_to_tstr((const char *)(buf_raw + offset_raw),
128                                    bufsize_raw - offset_raw,
129                                    &buf_tstr, &bufsize_tstr);
130         } else {
131                 ret = utf16le_to_tstr((const utf16lechar *)(buf_raw + offset_raw),
132                                       bufsize_raw - offset_raw,
133                                       &buf_tstr, &bufsize_tstr);
134         }
135         if (ret)
136                 return ret;
137
138         *tstr_ret = buf_tstr;
139         *tstr_nchars_ret = bufsize_tstr / sizeof(tchar);
140         return 0;
141 }
142
143 static int
144 string_set_append(struct string_set *set, tchar *str)
145 {
146         size_t num_alloc_strings = set->num_alloc_strings;
147
148         if (set->num_strings == num_alloc_strings) {
149                 tchar **new_strings;
150
151                 num_alloc_strings = max(num_alloc_strings * 3 / 2,
152                                         num_alloc_strings + 4);
153                 new_strings = REALLOC(set->strings,
154                                       sizeof(set->strings[0]) * num_alloc_strings);
155                 if (!new_strings)
156                         return WIMLIB_ERR_NOMEM;
157                 set->strings = new_strings;
158                 set->num_alloc_strings = num_alloc_strings;
159         }
160         set->strings[set->num_strings++] = str;
161         return 0;
162 }
163
164 #define NOT_IN_SECTION          -1
165 #define IN_UNKNOWN_SECTION      -2
166
167 static int
168 parse_text_file(const tchar *path, tchar *buf, size_t buflen,
169                 const struct text_file_section *pos_sections,
170                 int num_pos_sections, int flags, line_mangle_t mangle_line)
171 {
172         int current_section = NOT_IN_SECTION;
173         bool have_named_sections = false;
174         tchar *p;
175         tchar *nl;
176         unsigned long line_no = 1;
177
178         for (int i = 0; i < num_pos_sections; i++) {
179                 if (*pos_sections[i].name)
180                         have_named_sections = true;
181                 else
182                         current_section = i;
183         }
184
185         for (p = buf; p != buf + buflen; p = nl + 1, line_no++) {
186                 tchar *line_begin, *line_end;
187                 size_t line_len;
188                 int ret;
189
190                 nl = tmemchr(p, T('\n'), buf + buflen - p);
191                 if (!nl)
192                         break;
193
194                 line_begin = p;
195                 line_end = nl;
196
197                 /* Ignore leading whitespace.  */
198                 while (line_begin < nl && istspace(*line_begin))
199                         line_begin++;
200
201                 /* Ignore trailing whitespace.  */
202                 while (line_end > line_begin && istspace(*(line_end - 1)))
203                         line_end--;
204
205                 line_len = line_end - line_begin;
206
207                 /* Ignore comments and empty lines.  */
208                 if (line_len == 0 || *line_begin == T(';') || *line_begin == T('#'))
209                         continue;
210
211                 line_begin[line_len] = T('\0');
212
213                 /* Check for beginning of new section.  */
214                 if (line_begin[0] == T('[') &&
215                     line_begin[line_len - 1] == T(']') &&
216                     have_named_sections)
217                 {
218                         line_begin[line_len - 1] = T('\0');
219                         current_section = IN_UNKNOWN_SECTION;
220                         for (int i = 0; i < num_pos_sections; i++) {
221                                 if (!tstrcmp(line_begin + 1,
222                                              pos_sections[i].name))
223                                 {
224                                         current_section = i;
225                                         break;
226                                 }
227                         }
228                         line_begin[line_len - 1] = T(']');
229                         if (current_section < 0) {
230                                 if (!(flags & LOAD_TEXT_FILE_NO_WARNINGS)) {
231                                         WARNING("%"TS":%lu: Unrecognized section \"%"TS"\"",
232                                                 path, line_no, line_begin);
233                                 }
234                         }
235                         continue;
236                 }
237
238                 if (current_section < 0) {
239                         if (current_section == NOT_IN_SECTION) {
240                                 if (!(flags & LOAD_TEXT_FILE_NO_WARNINGS)) {
241                                         WARNING("%"TS":%lu: Not in a bracketed section!",
242                                                 path, line_no);
243                                 }
244                         }
245                         continue;
246                 }
247
248                 if (flags & LOAD_TEXT_FILE_REMOVE_QUOTES) {
249                         if (line_begin[0] == T('"') || line_begin[0] == T('\'')) {
250                                 tchar quote = line_begin[0];
251                                 if (line_len >= 2 &&
252                                     line_begin[line_len - 1] == quote)
253                                 {
254                                         line_begin++;
255                                         line_len -= 2;
256                                         line_begin[line_len] = T('\0');
257                                 }
258                         }
259                 }
260
261                 if (mangle_line) {
262                         ret = (*mangle_line)(line_begin, path, line_no);
263                         if (ret)
264                                 return ret;
265                 }
266
267                 ret = string_set_append(pos_sections[current_section].strings,
268                                         line_begin);
269                 if (ret)
270                         return ret;
271         }
272         return 0;
273 }
274
275 /**
276  * do_load_text_file -
277  *
278  * Read and parse lines from a text file from an on-disk file or a buffer.
279  * The file may contain sections, like in an INI file.
280  *
281  * @path
282  *      Path to the file on disk to read, or a dummy name for the buffer.
283  * @buf
284  *      If NULL, the data will be read from the @path file.  Otherwise the data
285  *      will be read from this buffer.
286  * @bufsize
287  *      Length of buffer in bytes; ignored if @buf is NULL.
288  * @mem_ret
289  *      On success, a pointer to a buffer backing the parsed lines is stored
290  *      here.  This must be freed after the parsed lines are done being used.
291  * @pos_sections
292  *      Specifications of allowed sections in the file.  Each such specification
293  *      consists of the name of the section (e.g. [ExclusionList], like in the
294  *      INI file format), along with a pointer to the list of lines parsed for
295  *      that section.  Use an empty name to indicate the destination of lines
296  *      not in any section.  Each list must be initialized to an empty string
297  *      set.
298  * @num_pos_sections
299  *      Number of entries in the @pos_sections array.
300  * @flags
301  *      Flags: LOAD_TEXT_FILE_REMOVE_QUOTES, LOAD_TEXT_FILE_NO_WARNINGS.
302  * @mangle_line
303  *      Optional callback to validate and/or modify each line being read.
304  *
305  * Returns 0 on success; nonzero on failure.
306  *
307  * Unknown sections are ignored, but a warning is printed for each, unless
308  * LOAD_TEXT_FILE_NO_WARNINGS is specified.
309  */
310 int
311 do_load_text_file(const tchar *path,
312                   const void *buf, size_t bufsize,
313                   void **mem_ret,
314                   const struct text_file_section *pos_sections,
315                   int num_pos_sections,
316                   int flags,
317                   line_mangle_t mangle_line)
318 {
319         int ret;
320         bool pathmode = (buf == NULL);
321         tchar *tstr;
322         size_t tstr_nchars;
323
324         if (pathmode) {
325                 ret = read_file_contents(path, (void **)&buf, &bufsize);
326                 if (ret)
327                         return ret;
328         }
329
330         ret = translate_text_buffer(buf, bufsize, &tstr, &tstr_nchars);
331         if (pathmode)
332                 FREE((void *)buf);
333         if (ret)
334                 return ret;
335
336         tstr[tstr_nchars++] = T('\n');
337
338         ret = parse_text_file(path, tstr, tstr_nchars, pos_sections,
339                               num_pos_sections, flags, mangle_line);
340         if (ret) {
341                 for (int i = 0; i < num_pos_sections; i++)
342                         FREE(pos_sections[i].strings->strings);
343                 FREE(tstr);
344                 return ret;
345         }
346
347         *mem_ret = tstr;
348         return 0;
349 }