avoid signed<->unsigned warning
[oweals/busybox.git] / e2fsprogs / blkid / read.c
1 /*
2  * read.c - read the blkid cache from disk, to avoid scanning all devices
3  *
4  * Copyright (C) 2001, 2003 Theodore Y. Ts'o
5  * Copyright (C) 2001 Andreas Dilger
6  *
7  * %Begin-Header%
8  * This file may be redistributed under the terms of the
9  * GNU Lesser General Public License.
10  * %End-Header%
11  */
12
13 #include <stdio.h>
14 #include <ctype.h>
15 #include <string.h>
16 #include <time.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <errno.h>
22
23 #include "blkidP.h"
24 #include "../uuid/uuid.h"
25
26 #ifdef HAVE_STRTOULL
27 #define __USE_ISOC9X
28 #define STRTOULL strtoull /* defined in stdlib.h if you try hard enough */
29 #else
30 /* FIXME: need to support real strtoull here */
31 #define STRTOULL strtoul
32 #endif
33
34 #include <stdlib.h>
35
36 /*
37  * File format:
38  *
39  *      <device [<NAME="value"> ...]>device_name</device>
40  *
41  *      The following tags are required for each entry:
42  *      <ID="id">       unique (within this file) ID number of this device
43  *      <TIME="time">   (ascii time_t) time this entry was last read from disk
44  *      <TYPE="type">   (detected) type of filesystem/data for this partition
45  *
46  *      The following tags may be present, depending on the device contents
47  *      <LABEL="label"> (user supplied) label (volume name, etc)
48  *      <UUID="uuid">   (generated) universally unique identifier (serial no)
49  */
50
51 static char *skip_over_blank(char *cp)
52 {
53         while (*cp && isspace(*cp))
54                 cp++;
55         return cp;
56 }
57
58 static char *skip_over_word(char *cp)
59 {
60         char ch;
61
62         while ((ch = *cp)) {
63                 /* If we see a backslash, skip the next character */
64                 if (ch == '\\') {
65                         cp++;
66                         if (*cp == '\0')
67                                 break;
68                         cp++;
69                         continue;
70                 }
71                 if (isspace(ch) || ch == '<' || ch == '>')
72                         break;
73                 cp++;
74         }
75         return cp;
76 }
77
78 static char *strip_line(char *line)
79 {
80         char    *p;
81
82         line = skip_over_blank(line);
83
84         p = line + strlen(line) - 1;
85
86         while (*line) {
87                 if (isspace(*p))
88                         *p-- = '\0';
89                 else
90                         break;
91         }
92
93         return line;
94 }
95
96 #if 0
97 static char *parse_word(char **buf)
98 {
99         char *word, *next;
100
101         word = *buf;
102         if (*word == '\0')
103                 return NULL;
104
105         word = skip_over_blank(word);
106         next = skip_over_word(word);
107         if (*next) {
108                 char *end = next - 1;
109                 if (*end == '"' || *end == '\'')
110                         *end = '\0';
111                 *next++ = '\0';
112         }
113         *buf = next;
114
115         if (*word == '"' || *word == '\'')
116                 word++;
117         return word;
118 }
119 #endif
120
121 /*
122  * Start parsing a new line from the cache.
123  *
124  * line starts with "<device" return 1 -> continue parsing line
125  * line starts with "<foo", empty, or # return 0 -> skip line
126  * line starts with other, return -BLKID_ERR_CACHE -> error
127  */
128 static int parse_start(char **cp)
129 {
130         char *p;
131
132         p = strip_line(*cp);
133
134         /* Skip comment or blank lines.  We can't just NUL the first '#' char,
135          * in case it is inside quotes, or escaped.
136          */
137         if (*p == '\0' || *p == '#')
138                 return 0;
139
140         if (!strncmp(p, "<device", 7)) {
141                 DBG(DEBUG_READ, printf("found device header: %8s\n", p));
142                 p += 7;
143
144                 *cp = p;
145                 return 1;
146         }
147
148         if (*p == '<')
149                 return 0;
150
151         return -BLKID_ERR_CACHE;
152 }
153
154 /* Consume the remaining XML on the line (cosmetic only) */
155 static int parse_end(char **cp)
156 {
157         *cp = skip_over_blank(*cp);
158
159         if (!strncmp(*cp, "</device>", 9)) {
160                 DBG(DEBUG_READ, printf("found device trailer %9s\n", *cp));
161                 *cp += 9;
162                 return 0;
163         }
164
165         return -BLKID_ERR_CACHE;
166 }
167
168 /*
169  * Allocate a new device struct with device name filled in.  Will handle
170  * finding the device on lines of the form:
171  * <device foo=bar>devname</device>
172  * <device>devname<foo>bar</foo></device>
173  */
174 static int parse_dev(blkid_cache cache, blkid_dev *dev, char **cp)
175 {
176         char *start, *tmp, *end, *name;
177         int ret;
178
179         if ((ret = parse_start(cp)) <= 0)
180                 return ret;
181
182         start = tmp = strchr(*cp, '>');
183         if (!start) {
184                 DBG(DEBUG_READ,
185                     printf("blkid: short line parsing dev: %s\n", *cp));
186                 return -BLKID_ERR_CACHE;
187         }
188         start = skip_over_blank(start + 1);
189         end = skip_over_word(start);
190
191         DBG(DEBUG_READ, printf("device should be %*s\n", end - start, start));
192
193         if (**cp == '>')
194                 *cp = end;
195         else
196                 (*cp)++;
197
198         *tmp = '\0';
199
200         if (!(tmp = strrchr(end, '<')) || parse_end(&tmp) < 0) {
201                 DBG(DEBUG_READ,
202                     printf("blkid: missing </device> ending: %s\n", end));
203         } else if (tmp)
204                 *tmp = '\0';
205
206         if (end - start <= 1) {
207                 DBG(DEBUG_READ, printf("blkid: empty device name: %s\n", *cp));
208                 return -BLKID_ERR_CACHE;
209         }
210
211         name = blkid_strndup(start, end-start);
212         if (name == NULL)
213                 return -BLKID_ERR_MEM;
214
215         DBG(DEBUG_READ, printf("found dev %s\n", name));
216
217         if (!(*dev = blkid_get_dev(cache, name, BLKID_DEV_CREATE)))
218                 return -BLKID_ERR_MEM;
219
220         free(name);
221         return 1;
222 }
223
224 /*
225  * Extract a tag of the form NAME="value" from the line.
226  */
227 static int parse_token(char **name, char **value, char **cp)
228 {
229         char *end;
230
231         if (!name || !value || !cp)
232                 return -BLKID_ERR_PARAM;
233
234         if (!(*value = strchr(*cp, '=')))
235                 return 0;
236
237         **value = '\0';
238         *name = strip_line(*cp);
239         *value = skip_over_blank(*value + 1);
240
241         if (**value == '"') {
242                 end = strchr(*value + 1, '"');
243                 if (!end) {
244                         DBG(DEBUG_READ,
245                             printf("unbalanced quotes at: %s\n", *value));
246                         *cp = *value;
247                         return -BLKID_ERR_CACHE;
248                 }
249                 (*value)++;
250                 *end = '\0';
251                 end++;
252         } else {
253                 end = skip_over_word(*value);
254                 if (*end) {
255                         *end = '\0';
256                         end++;
257                 }
258         }
259         *cp = end;
260
261         return 1;
262 }
263
264 /*
265  * Extract a tag of the form <NAME>value</NAME> from the line.
266  */
267 /*
268 static int parse_xml(char **name, char **value, char **cp)
269 {
270         char *end;
271
272         if (!name || !value || !cp)
273                 return -BLKID_ERR_PARAM;
274
275         *name = strip_line(*cp);
276
277         if ((*name)[0] != '<' || (*name)[1] == '/')
278                 return 0;
279
280         FIXME: finish this.
281 }
282 */
283
284 /*
285  * Extract a tag from the line.
286  *
287  * Return 1 if a valid tag was found.
288  * Return 0 if no tag found.
289  * Return -ve error code.
290  */
291 static int parse_tag(blkid_cache cache, blkid_dev dev, char **cp)
292 {
293         char *name;
294         char *value;
295         int ret;
296
297         if (!cache || !dev)
298                 return -BLKID_ERR_PARAM;
299
300         if ((ret = parse_token(&name, &value, cp)) <= 0 /* &&
301             (ret = parse_xml(&name, &value, cp)) <= 0 */)
302                 return ret;
303
304         /* Some tags are stored directly in the device struct */
305         if (!strcmp(name, "DEVNO"))
306                 dev->bid_devno = STRTOULL(value, 0, 0);
307         else if (!strcmp(name, "PRI"))
308                 dev->bid_pri = strtol(value, 0, 0);
309         else if (!strcmp(name, "TIME"))
310                 /* FIXME: need to parse a long long eventually */
311                 dev->bid_time = strtol(value, 0, 0);
312         else
313                 ret = blkid_set_tag(dev, name, value, strlen(value));
314
315         DBG(DEBUG_READ, printf("    tag: %s=\"%s\"\n", name, value));
316
317         return ret < 0 ? ret : 1;
318 }
319
320 /*
321  * Parse a single line of data, and return a newly allocated dev struct.
322  * Add the new device to the cache struct, if one was read.
323  *
324  * Lines are of the form <device [TAG="value" ...]>/dev/foo</device>
325  *
326  * Returns -ve value on error.
327  * Returns 0 otherwise.
328  * If a valid device was read, *dev_p is non-NULL, otherwise it is NULL
329  * (e.g. comment lines, unknown XML content, etc).
330  */
331 static int blkid_parse_line(blkid_cache cache, blkid_dev *dev_p, char *cp)
332 {
333         blkid_dev dev;
334         int ret;
335
336         if (!cache || !dev_p)
337                 return -BLKID_ERR_PARAM;
338
339         *dev_p = NULL;
340
341         DBG(DEBUG_READ, printf("line: %s\n", cp));
342
343         if ((ret = parse_dev(cache, dev_p, &cp)) <= 0)
344                 return ret;
345
346         dev = *dev_p;
347
348         while ((ret = parse_tag(cache, dev, &cp)) > 0) {
349                 ;
350         }
351
352         if (dev->bid_type == NULL) {
353                 DBG(DEBUG_READ,
354                     printf("blkid: device %s has no TYPE\n",dev->bid_name));
355                 blkid_free_dev(dev);
356         }
357
358         DEB_DUMP_DEV(DEBUG_READ, dev);
359
360         return ret;
361 }
362
363 /*
364  * Parse the specified filename, and return the data in the supplied or
365  * a newly allocated cache struct.  If the file doesn't exist, return a
366  * new empty cache struct.
367  */
368 void blkid_read_cache(blkid_cache cache)
369 {
370         FILE *file;
371         char buf[4096];
372         int fd, lineno = 0;
373         struct stat st;
374
375         if (!cache)
376                 return;
377
378         /*
379          * If the file doesn't exist, then we just return an empty
380          * struct so that the cache can be populated.
381          */
382         if ((fd = open(cache->bic_filename, O_RDONLY)) < 0)
383                 return;
384         if (fstat(fd, &st) < 0)
385                 goto errout;
386         if ((st.st_mtime == cache->bic_ftime) ||
387             (cache->bic_flags & BLKID_BIC_FL_CHANGED)) {
388                 DBG(DEBUG_CACHE, printf("skipping re-read of %s\n",
389                                         cache->bic_filename));
390                 goto errout;
391         }
392
393         DBG(DEBUG_CACHE, printf("reading cache file %s\n",
394                                 cache->bic_filename));
395
396         file = fdopen(fd, "r");
397         if (!file)
398                 goto errout;
399
400         while (fgets(buf, sizeof(buf), file)) {
401                 blkid_dev dev;
402                 unsigned int end;
403
404                 lineno++;
405                 if (buf[0] == 0)
406                         continue;
407                 end = strlen(buf) - 1;
408                 /* Continue reading next line if it ends with a backslash */
409                 while (buf[end] == '\\' && end < sizeof(buf) - 2 &&
410                        fgets(buf + end, sizeof(buf) - end, file)) {
411                         end = strlen(buf) - 1;
412                         lineno++;
413                 }
414
415                 if (blkid_parse_line(cache, &dev, buf) < 0) {
416                         DBG(DEBUG_READ,
417                             printf("blkid: bad format on line %d\n", lineno));
418                         continue;
419                 }
420         }
421         fclose(file);
422
423         /*
424          * Initially we do not need to write out the cache file.
425          */
426         cache->bic_flags &= ~BLKID_BIC_FL_CHANGED;
427         cache->bic_ftime = st.st_mtime;
428
429         return;
430 errout:
431         close(fd);
432         return;
433 }
434
435 #ifdef TEST_PROGRAM
436 int main(int argc, char**argv)
437 {
438         blkid_cache cache = NULL;
439         int ret;
440
441         blkid_debug_mask = DEBUG_ALL;
442         if (argc > 2) {
443                 fprintf(stderr, "Usage: %s [filename]\n"
444                         "Test parsing of the cache (filename)\n", argv[0]);
445                 exit(1);
446         }
447         if ((ret = blkid_get_cache(&cache, argv[1])) < 0)
448                 fprintf(stderr, "error %d reading cache file %s\n", ret,
449                         argv[1] ? argv[1] : BLKID_CACHE_FILE);
450
451         blkid_put_cache(cache);
452
453         return ret;
454 }
455 #endif