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