]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libarchive/archive_read_support_format_mtree.c
Merge r552,r559 from libarchive.googlecode.com: Support high-resolution
[FreeBSD/FreeBSD.git] / lib / libarchive / archive_read_support_format_mtree.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * Copyright (c) 2008 Joerg Sonnenberger
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD$");
29
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #ifdef HAVE_ERRNO_H
34 #include <errno.h>
35 #endif
36 #ifdef HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39 #include <stddef.h>
40 /* #include <stdint.h> */ /* See archive_platform.h */
41 #ifdef HAVE_STDLIB_H
42 #include <stdlib.h>
43 #endif
44 #ifdef HAVE_STRING_H
45 #include <string.h>
46 #endif
47
48 #include "archive.h"
49 #include "archive_entry.h"
50 #include "archive_private.h"
51 #include "archive_read_private.h"
52 #include "archive_string.h"
53
54 #ifndef O_BINARY
55 #define O_BINARY 0
56 #endif
57
58 #define MTREE_HAS_DEVICE        0x0001
59 #define MTREE_HAS_FFLAGS        0x0002
60 #define MTREE_HAS_GID           0x0004
61 #define MTREE_HAS_GNAME         0x0008
62 #define MTREE_HAS_MTIME         0x0010
63 #define MTREE_HAS_NLINK         0x0020
64 #define MTREE_HAS_PERM          0x0040
65 #define MTREE_HAS_SIZE          0x0080
66 #define MTREE_HAS_TYPE          0x0100
67 #define MTREE_HAS_UID           0x0200
68 #define MTREE_HAS_UNAME         0x0400
69
70 #define MTREE_HAS_OPTIONAL      0x0800
71
72 struct mtree_option {
73         struct mtree_option *next;
74         char *value;
75 };
76
77 struct mtree_entry {
78         struct mtree_entry *next;
79         struct mtree_option *options;
80         char *name;
81         char full;
82         char used;
83 };
84
85 struct mtree {
86         struct archive_string    line;
87         size_t                   buffsize;
88         char                    *buff;
89         off_t                    offset;
90         int                      fd;
91         int                      filetype;
92         int                      archive_format;
93         const char              *archive_format_name;
94         struct mtree_entry      *entries;
95         struct mtree_entry      *this_entry;
96         struct archive_string    current_dir;
97         struct archive_string    contents_name;
98
99         struct archive_entry_linkresolver *resolver;
100
101         off_t                    cur_size, cur_offset;
102 };
103
104 static int      cleanup(struct archive_read *);
105 static int      mtree_bid(struct archive_read *);
106 static int      parse_file(struct archive_read *, struct archive_entry *,
107                     struct mtree *, struct mtree_entry *, int *);
108 static void     parse_escapes(char *, struct mtree_entry *);
109 static int      parse_line(struct archive_read *, struct archive_entry *,
110                     struct mtree *, struct mtree_entry *, int *);
111 static int      parse_keyword(struct archive_read *, struct mtree *,
112                     struct archive_entry *, struct mtree_option *, int *);
113 static int      read_data(struct archive_read *a,
114                     const void **buff, size_t *size, off_t *offset);
115 static ssize_t  readline(struct archive_read *, struct mtree *, char **, ssize_t);
116 static int      skip(struct archive_read *a);
117 static int      read_header(struct archive_read *,
118                     struct archive_entry *);
119 static int64_t  mtree_atol10(char **);
120 static int64_t  mtree_atol8(char **);
121 static int64_t  mtree_atol(char **);
122
123 static void
124 free_options(struct mtree_option *head)
125 {
126         struct mtree_option *next;
127
128         for (; head != NULL; head = next) {
129                 next = head->next;
130                 free(head->value);
131                 free(head);
132         }
133 }
134
135 int
136 archive_read_support_format_mtree(struct archive *_a)
137 {
138         struct archive_read *a = (struct archive_read *)_a;
139         struct mtree *mtree;
140         int r;
141
142         mtree = (struct mtree *)malloc(sizeof(*mtree));
143         if (mtree == NULL) {
144                 archive_set_error(&a->archive, ENOMEM,
145                     "Can't allocate mtree data");
146                 return (ARCHIVE_FATAL);
147         }
148         memset(mtree, 0, sizeof(*mtree));
149         mtree->fd = -1;
150
151         r = __archive_read_register_format(a, mtree, "mtree",
152             mtree_bid, NULL, read_header, read_data, skip, cleanup);
153
154         if (r != ARCHIVE_OK)
155                 free(mtree);
156         return (ARCHIVE_OK);
157 }
158
159 static int
160 cleanup(struct archive_read *a)
161 {
162         struct mtree *mtree;
163         struct mtree_entry *p, *q;
164
165         mtree = (struct mtree *)(a->format->data);
166
167         p = mtree->entries;
168         while (p != NULL) {
169                 q = p->next;
170                 free(p->name);
171                 free_options(p->options);
172                 free(p);
173                 p = q;
174         }
175         archive_string_free(&mtree->line);
176         archive_string_free(&mtree->current_dir);
177         archive_string_free(&mtree->contents_name);
178         archive_entry_linkresolver_free(mtree->resolver);
179
180         free(mtree->buff);
181         free(mtree);
182         (a->format->data) = NULL;
183         return (ARCHIVE_OK);
184 }
185
186
187 static int
188 mtree_bid(struct archive_read *a)
189 {
190         const char *signature = "#mtree";
191         const char *p;
192
193         /* Now let's look at the actual header and see if it matches. */
194         p = __archive_read_ahead(a, strlen(signature), NULL);
195         if (p == NULL)
196                 return (-1);
197
198         if (strncmp(p, signature, strlen(signature)) == 0)
199                 return (8 * strlen(signature));
200         return (0);
201 }
202
203 /*
204  * The extended mtree format permits multiple lines specifying
205  * attributes for each file.  For those entries, only the last line
206  * is actually used.  Practically speaking, that means we have
207  * to read the entire mtree file into memory up front.
208  *
209  * The parsing is done in two steps.  First, it is decided if a line
210  * changes the global defaults and if it is, processed accordingly.
211  * Otherwise, the options of the line are merged with the current
212  * global options.
213  */
214 static int
215 add_option(struct archive_read *a, struct mtree_option **global,
216     const char *value, size_t len)
217 {
218         struct mtree_option *option;
219
220         if ((option = malloc(sizeof(*option))) == NULL) {
221                 archive_set_error(&a->archive, errno, "Can't allocate memory");
222                 return (ARCHIVE_FATAL);
223         }
224         if ((option->value = malloc(len + 1)) == NULL) {
225                 free(option);
226                 archive_set_error(&a->archive, errno, "Can't allocate memory");
227                 return (ARCHIVE_FATAL);
228         }
229         memcpy(option->value, value, len);
230         option->value[len] = '\0';
231         option->next = *global;
232         *global = option;
233         return (ARCHIVE_OK);
234 }
235
236 static void
237 remove_option(struct mtree_option **global, const char *value, size_t len)
238 {
239         struct mtree_option *iter, *last;
240
241         last = NULL;
242         for (iter = *global; iter != NULL; last = iter, iter = iter->next) {
243                 if (strncmp(iter->value, value, len) == 0 &&
244                     (iter->value[len] == '\0' ||
245                      iter->value[len] == '='))
246                         break;
247         }
248         if (iter == NULL)
249                 return;
250         if (last == NULL)
251                 *global = iter->next;
252         else
253                 last->next = iter->next;
254
255         free(iter->value);
256         free(iter);
257 }
258
259 static int
260 process_global_set(struct archive_read *a,
261     struct mtree_option **global, const char *line)
262 {
263         const char *next, *eq;
264         size_t len;
265         int r;
266
267         line += 4;
268         for (;;) {
269                 next = line + strspn(line, " \t\r\n");
270                 if (*next == '\0')
271                         return (ARCHIVE_OK);
272                 line = next;
273                 next = line + strcspn(line, " \t\r\n");
274                 eq = strchr(line, '=');
275                 if (eq > next)
276                         len = next - line;
277                 else
278                         len = eq - line;
279
280                 remove_option(global, line, len);
281                 r = add_option(a, global, line, next - line);
282                 if (r != ARCHIVE_OK)
283                         return (r);
284                 line = next;
285         }
286 }
287
288 static int
289 process_global_unset(struct archive_read *a,
290     struct mtree_option **global, const char *line)
291 {
292         const char *next;
293         size_t len;
294
295         line += 6;
296         if (strchr(line, '=') != NULL) {
297                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
298                     "/unset shall not contain `='");
299                 return ARCHIVE_FATAL;
300         }
301
302         for (;;) {
303                 next = line + strspn(line, " \t\r\n");
304                 if (*next == '\0')
305                         return (ARCHIVE_OK);
306                 line = next;
307                 len = strcspn(line, " \t\r\n");
308
309                 if (len == 3 && strncmp(line, "all", 3) == 0) {
310                         free_options(*global);
311                         *global = NULL;
312                 } else {
313                         remove_option(global, line, len);
314                 }
315
316                 line += len;
317         }
318 }
319
320 static int
321 process_add_entry(struct archive_read *a, struct mtree *mtree,
322     struct mtree_option **global, const char *line,
323     struct mtree_entry **last_entry)
324 {
325         struct mtree_entry *entry;
326         struct mtree_option *iter;
327         const char *next, *eq;
328         size_t len;
329         int r;
330
331         if ((entry = malloc(sizeof(*entry))) == NULL) {
332                 archive_set_error(&a->archive, errno, "Can't allocate memory");
333                 return (ARCHIVE_FATAL);
334         }
335         entry->next = NULL;
336         entry->options = NULL;
337         entry->name = NULL;
338         entry->used = 0;
339         entry->full = 0;
340
341         /* Add this entry to list. */
342         if (*last_entry == NULL)
343                 mtree->entries = entry;
344         else
345                 (*last_entry)->next = entry;
346         *last_entry = entry;
347
348         len = strcspn(line, " \t\r\n");
349         if ((entry->name = malloc(len + 1)) == NULL) {
350                 archive_set_error(&a->archive, errno, "Can't allocate memory");
351                 return (ARCHIVE_FATAL);
352         }
353
354         memcpy(entry->name, line, len);
355         entry->name[len] = '\0';
356         parse_escapes(entry->name, entry);
357
358         line += len;
359         for (iter = *global; iter != NULL; iter = iter->next) {
360                 r = add_option(a, &entry->options, iter->value,
361                     strlen(iter->value));
362                 if (r != ARCHIVE_OK)
363                         return (r);
364         }
365
366         for (;;) {
367                 next = line + strspn(line, " \t\r\n");
368                 if (*next == '\0')
369                         return (ARCHIVE_OK);
370                 line = next;
371                 next = line + strcspn(line, " \t\r\n");
372                 eq = strchr(line, '=');
373                 if (eq > next)
374                         len = next - line;
375                 else
376                         len = eq - line;
377
378                 remove_option(&entry->options, line, len);
379                 r = add_option(a, &entry->options, line, next - line);
380                 if (r != ARCHIVE_OK)
381                         return (r);
382                 line = next;
383         }
384 }
385
386 static int
387 read_mtree(struct archive_read *a, struct mtree *mtree)
388 {
389         ssize_t len;
390         uintmax_t counter;
391         char *p;
392         struct mtree_option *global;
393         struct mtree_entry *last_entry;
394         int r;
395
396         mtree->archive_format = ARCHIVE_FORMAT_MTREE;
397         mtree->archive_format_name = "mtree";
398
399         global = NULL;
400         last_entry = NULL;
401         r = ARCHIVE_OK;
402
403         for (counter = 1; ; ++counter) {
404                 len = readline(a, mtree, &p, 256);
405                 if (len == 0) {
406                         mtree->this_entry = mtree->entries;
407                         return (ARCHIVE_OK);
408                 }
409                 if (len < 0)
410                         return (len);
411                 /* Leading whitespace is never significant, ignore it. */
412                 while (*p == ' ' || *p == '\t') {
413                         ++p;
414                         --len;
415                 }
416                 /* Skip content lines and blank lines. */
417                 if (*p == '#')
418                         continue;
419                 if (*p == '\r' || *p == '\n' || *p == '\0')
420                         continue;
421                 if (*p != '/') {
422                         r = process_add_entry(a, mtree, &global, p,
423                             &last_entry);
424                 } else if (strncmp(p, "/set", 4) == 0) {
425                         if (p[4] != ' ' && p[4] != '\t')
426                                 break;
427                         r = process_global_set(a, &global, p);
428                 } else if (strncmp(p, "/unset", 6) == 0) {
429                         if (p[6] != ' ' && p[6] != '\t')
430                                 break;
431                         r = process_global_unset(a, &global, p);
432                 } else
433                         break;
434
435                 if (r != ARCHIVE_OK)
436                         return r;
437         }
438
439         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
440             "Can't parse line %ju", counter);
441         return ARCHIVE_FATAL;
442 }
443
444 /*
445  * Read in the entire mtree file into memory on the first request.
446  * Then use the next unused file to satisfy each header request.
447  */
448 static int
449 read_header(struct archive_read *a, struct archive_entry *entry)
450 {
451         struct mtree *mtree;
452         char *p;
453         int r, use_next;
454
455         mtree = (struct mtree *)(a->format->data);
456
457         if (mtree->fd >= 0) {
458                 close(mtree->fd);
459                 mtree->fd = -1;
460         }
461
462         if (mtree->entries == NULL) {
463                 mtree->resolver = archive_entry_linkresolver_new();
464                 if (mtree->resolver == NULL)
465                         return ARCHIVE_FATAL;
466                 archive_entry_linkresolver_set_strategy(mtree->resolver,
467                     ARCHIVE_FORMAT_MTREE);
468                 r = read_mtree(a, mtree);
469                 if (r != ARCHIVE_OK)
470                         return (r);
471         }
472
473         a->archive.archive_format = mtree->archive_format;
474         a->archive.archive_format_name = mtree->archive_format_name;
475
476         for (;;) {
477                 if (mtree->this_entry == NULL)
478                         return (ARCHIVE_EOF);
479                 if (strcmp(mtree->this_entry->name, "..") == 0) {
480                         mtree->this_entry->used = 1;
481                         if (archive_strlen(&mtree->current_dir) > 0) {
482                                 /* Roll back current path. */
483                                 p = mtree->current_dir.s
484                                     + mtree->current_dir.length - 1;
485                                 while (p >= mtree->current_dir.s && *p != '/')
486                                         --p;
487                                 if (p >= mtree->current_dir.s)
488                                         --p;
489                                 mtree->current_dir.length
490                                     = p - mtree->current_dir.s + 1;
491                         }
492                 }
493                 if (!mtree->this_entry->used) {
494                         use_next = 0;
495                         r = parse_file(a, entry, mtree, mtree->this_entry, &use_next);
496                         if (use_next == 0)
497                                 return (r);
498                 }
499                 mtree->this_entry = mtree->this_entry->next;
500         }
501 }
502
503 /*
504  * A single file can have multiple lines contribute specifications.
505  * Parse as many lines as necessary, then pull additional information
506  * from a backing file on disk as necessary.
507  */
508 static int
509 parse_file(struct archive_read *a, struct archive_entry *entry,
510     struct mtree *mtree, struct mtree_entry *mentry, int *use_next)
511 {
512         const char *path;
513         struct stat st_storage, *st;
514         struct mtree_entry *mp;
515         struct archive_entry *sparse_entry;
516         int r = ARCHIVE_OK, r1, parsed_kws, mismatched_type;
517
518         mentry->used = 1;
519
520         /* Initialize reasonable defaults. */
521         mtree->filetype = AE_IFREG;
522         archive_entry_set_size(entry, 0);
523
524         /* Parse options from this line. */
525         parsed_kws = 0;
526         r = parse_line(a, entry, mtree, mentry, &parsed_kws);
527
528         if (mentry->full) {
529                 archive_entry_copy_pathname(entry, mentry->name);
530                 /*
531                  * "Full" entries are allowed to have multiple lines
532                  * and those lines aren't required to be adjacent.  We
533                  * don't support multiple lines for "relative" entries
534                  * nor do we make any attempt to merge data from
535                  * separate "relative" and "full" entries.  (Merging
536                  * "relative" and "full" entries would require dealing
537                  * with pathname canonicalization, which is a very
538                  * tricky subject.)
539                  */
540                 for (mp = mentry->next; mp != NULL; mp = mp->next) {
541                         if (mp->full && !mp->used
542                             && strcmp(mentry->name, mp->name) == 0) {
543                                 /* Later lines override earlier ones. */
544                                 mp->used = 1;
545                                 r1 = parse_line(a, entry, mtree, mp,
546                                     &parsed_kws);
547                                 if (r1 < r)
548                                         r = r1;
549                         }
550                 }
551         } else {
552                 /*
553                  * Relative entries require us to construct
554                  * the full path and possibly update the
555                  * current directory.
556                  */
557                 size_t n = archive_strlen(&mtree->current_dir);
558                 if (n > 0)
559                         archive_strcat(&mtree->current_dir, "/");
560                 archive_strcat(&mtree->current_dir, mentry->name);
561                 archive_entry_copy_pathname(entry, mtree->current_dir.s);
562                 if (archive_entry_filetype(entry) != AE_IFDIR)
563                         mtree->current_dir.length = n;
564         }
565
566         /*
567          * Try to open and stat the file to get the real size
568          * and other file info.  It would be nice to avoid
569          * this here so that getting a listing of an mtree
570          * wouldn't require opening every referenced contents
571          * file.  But then we wouldn't know the actual
572          * contents size, so I don't see a really viable way
573          * around this.  (Also, we may want to someday pull
574          * other unspecified info from the contents file on
575          * disk.)
576          */
577         mtree->fd = -1;
578         if (archive_strlen(&mtree->contents_name) > 0)
579                 path = mtree->contents_name.s;
580         else
581                 path = archive_entry_pathname(entry);
582
583         if (archive_entry_filetype(entry) == AE_IFREG ||
584             archive_entry_filetype(entry) == AE_IFDIR) {
585                 mtree->fd = open(path,
586                     O_RDONLY | O_BINARY);
587                 if (mtree->fd == -1 &&
588                     (errno != ENOENT ||
589                      archive_strlen(&mtree->contents_name) > 0)) {
590                         archive_set_error(&a->archive, errno,
591                             "Can't open %s", path);
592                         r = ARCHIVE_WARN;
593                 }
594         }
595
596         st = &st_storage;
597         if (mtree->fd >= 0) {
598                 if (fstat(mtree->fd, st) == -1) {
599                         archive_set_error(&a->archive, errno,
600                             "Could not fstat %s", path);
601                         r = ARCHIVE_WARN;
602                         /* If we can't stat it, don't keep it open. */
603                         close(mtree->fd);
604                         mtree->fd = -1;
605                         st = NULL;
606                 }
607         } else if (lstat(path, st) == -1) {
608                 st = NULL;
609         }
610
611         /*
612          * If there is a contents file on disk, use that size;
613          * otherwise leave it as-is (it might have been set from
614          * the mtree size= keyword).
615          */
616         if (st != NULL) {
617                 mismatched_type = 0;
618                 if ((st->st_mode & S_IFMT) == S_IFREG &&
619                     archive_entry_filetype(entry) != AE_IFREG)
620                         mismatched_type = 1;
621                 if ((st->st_mode & S_IFMT) == S_IFLNK &&
622                     archive_entry_filetype(entry) != AE_IFLNK)
623                         mismatched_type = 1;
624                 if ((st->st_mode & S_IFSOCK) == S_IFSOCK &&
625                     archive_entry_filetype(entry) != AE_IFSOCK)
626                         mismatched_type = 1;
627                 if ((st->st_mode & S_IFMT) == S_IFCHR &&
628                     archive_entry_filetype(entry) != AE_IFCHR)
629                         mismatched_type = 1;
630                 if ((st->st_mode & S_IFMT) == S_IFBLK &&
631                     archive_entry_filetype(entry) != AE_IFBLK)
632                         mismatched_type = 1;
633                 if ((st->st_mode & S_IFMT) == S_IFDIR &&
634                     archive_entry_filetype(entry) != AE_IFDIR)
635                         mismatched_type = 1;
636                 if ((st->st_mode & S_IFMT) == S_IFIFO &&
637                     archive_entry_filetype(entry) != AE_IFIFO)
638                         mismatched_type = 1;
639
640                 if (mismatched_type) {
641                         if ((parsed_kws & MTREE_HAS_OPTIONAL) == 0) {
642                                 archive_set_error(&a->archive,
643                                     ARCHIVE_ERRNO_MISC,
644                                     "mtree specification has different type for %s",
645                                     archive_entry_pathname(entry));
646                                 r = ARCHIVE_WARN;
647                         } else {
648                                 *use_next = 1;
649                         }
650                         /* Don't hold a non-regular file open. */
651                         if (mtree->fd >= 0)
652                                 close(mtree->fd);
653                         mtree->fd = -1;
654                         st = NULL;
655                         return r;
656                 }
657         }
658
659         if (st != NULL) {
660                 if ((parsed_kws & MTREE_HAS_DEVICE) == 0 &&
661                     (archive_entry_filetype(entry) == AE_IFCHR ||
662                      archive_entry_filetype(entry) == AE_IFBLK))
663                         archive_entry_set_rdev(entry, st->st_rdev);
664                 if ((parsed_kws & (MTREE_HAS_GID | MTREE_HAS_GNAME)) == 0)
665                         archive_entry_set_gid(entry, st->st_gid);
666                 if ((parsed_kws & (MTREE_HAS_UID | MTREE_HAS_UNAME)) == 0)
667                         archive_entry_set_uid(entry, st->st_uid);
668                 if ((parsed_kws & MTREE_HAS_MTIME) == 0) {
669 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
670                         archive_entry_set_mtime(entry, st->st_mtime,
671                             st->st_mtimespec.tv_nsec);
672 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
673                         archive_entry_set_mtime(entry, st->st_mtime,
674                             st->st_mtim.tv_nsec);
675 #elif HAVE_STRUCT_STAT_ST_MTIME_N
676                         archive_entry_set_mtime(entry, st->st_mtime,
677                             st->st_mtime_n);
678 #elif HAVE_STRUCT_STAT_ST_UMTIME
679                         archive_entry_set_mtime(entry, st->st_mtime,
680                             st->st_umtime*1000);
681 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
682                         archive_entry_set_mtime(entry, st->st_mtime,
683                             st->st_mtime_usec*1000);
684 #else
685                         archive_entry_set_mtime(entry, st->st_mtime, 0);
686 #endif
687                 }
688                 if ((parsed_kws & MTREE_HAS_NLINK) == 0)
689                         archive_entry_set_nlink(entry, st->st_nlink);
690                 if ((parsed_kws & MTREE_HAS_PERM) == 0)
691                         archive_entry_set_perm(entry, st->st_mode);
692                 if ((parsed_kws & MTREE_HAS_SIZE) == 0)
693                         archive_entry_set_size(entry, st->st_size);
694                 archive_entry_set_ino(entry, st->st_ino);
695                 archive_entry_set_dev(entry, st->st_dev);
696
697                 archive_entry_linkify(mtree->resolver, &entry, &sparse_entry);
698         } else if (parsed_kws & MTREE_HAS_OPTIONAL) {
699                 /*
700                  * Couldn't open the entry, stat it or the on-disk type
701                  * didn't match.  If this entry is optional, just ignore it
702                  * and read the next header entry.
703                  */
704                 *use_next = 1;
705                 return ARCHIVE_OK;
706         }
707
708         mtree->cur_size = archive_entry_size(entry);
709         mtree->offset = 0;
710
711         return r;
712 }
713
714 /*
715  * Each line contains a sequence of keywords.
716  */
717 static int
718 parse_line(struct archive_read *a, struct archive_entry *entry,
719     struct mtree *mtree, struct mtree_entry *mp, int *parsed_kws)
720 {
721         struct mtree_option *iter;
722         int r = ARCHIVE_OK, r1;
723
724         for (iter = mp->options; iter != NULL; iter = iter->next) {
725                 r1 = parse_keyword(a, mtree, entry, iter, parsed_kws);
726                 if (r1 < r)
727                         r = r1;
728         }
729         if ((*parsed_kws & MTREE_HAS_TYPE) == 0) {
730                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
731                     "Missing type keyword in mtree specification");
732                 return (ARCHIVE_WARN);
733         }
734         return (r);
735 }
736
737 /*
738  * Device entries have one of the following forms:
739  * raw dev_t
740  * format,major,minor[,subdevice]
741  *
742  * Just use major and minor, no translation etc is done
743  * between formats.
744  */
745 static int
746 parse_device(struct archive *a, struct archive_entry *entry, char *val)
747 {
748         char *comma1, *comma2;
749
750         comma1 = strchr(val, ',');
751         if (comma1 == NULL) {
752                 archive_entry_set_dev(entry, mtree_atol10(&val));
753                 return (ARCHIVE_OK);
754         }
755         ++comma1;
756         comma2 = strchr(comma1, ',');
757         if (comma2 == NULL) {
758                 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
759                     "Malformed device attribute");
760                 return (ARCHIVE_WARN);
761         }
762         ++comma2;
763         archive_entry_set_rdevmajor(entry, mtree_atol(&comma1));
764         archive_entry_set_rdevminor(entry, mtree_atol(&comma2));
765         return (ARCHIVE_OK);
766 }
767
768 /*
769  * Parse a single keyword and its value.
770  */
771 static int
772 parse_keyword(struct archive_read *a, struct mtree *mtree,
773     struct archive_entry *entry, struct mtree_option *option, int *parsed_kws)
774 {
775         char *val, *key;
776
777         key = option->value;
778
779         if (*key == '\0')
780                 return (ARCHIVE_OK);
781
782         if (strcmp(key, "optional") == 0) {
783                 *parsed_kws |= MTREE_HAS_OPTIONAL;
784                 return (ARCHIVE_OK);
785         }
786         if (strcmp(key, "ignore") == 0) {
787                 /*
788                  * The mtree processing is not recursive, so
789                  * recursion will only happen for explicitly listed
790                  * entries.
791                  */
792                 return (ARCHIVE_OK);
793         }
794
795         val = strchr(key, '=');
796         if (val == NULL) {
797                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
798                     "Malformed attribute \"%s\" (%d)", key, key[0]);
799                 return (ARCHIVE_WARN);
800         }
801
802         *val = '\0';
803         ++val;
804
805         switch (key[0]) {
806         case 'c':
807                 if (strcmp(key, "content") == 0
808                     || strcmp(key, "contents") == 0) {
809                         parse_escapes(val, NULL);
810                         archive_strcpy(&mtree->contents_name, val);
811                         break;
812                 }
813                 if (strcmp(key, "cksum") == 0)
814                         break;
815         case 'd':
816                 if (strcmp(key, "device") == 0) {
817                         *parsed_kws |= MTREE_HAS_DEVICE;
818                         return parse_device(&a->archive, entry, val);
819                 }
820         case 'f':
821                 if (strcmp(key, "flags") == 0) {
822                         *parsed_kws |= MTREE_HAS_FFLAGS;
823                         archive_entry_copy_fflags_text(entry, val);
824                         break;
825                 }
826         case 'g':
827                 if (strcmp(key, "gid") == 0) {
828                         *parsed_kws |= MTREE_HAS_GID;
829                         archive_entry_set_gid(entry, mtree_atol10(&val));
830                         break;
831                 }
832                 if (strcmp(key, "gname") == 0) {
833                         *parsed_kws |= MTREE_HAS_GNAME;
834                         archive_entry_copy_gname(entry, val);
835                         break;
836                 }
837         case 'l':
838                 if (strcmp(key, "link") == 0) {
839                         archive_entry_copy_symlink(entry, val);
840                         break;
841                 }
842         case 'm':
843                 if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
844                         break;
845                 if (strcmp(key, "mode") == 0) {
846                         if (val[0] >= '0' && val[0] <= '9') {
847                                 *parsed_kws |= MTREE_HAS_PERM;
848                                 archive_entry_set_perm(entry,
849                                     mtree_atol8(&val));
850                         } else {
851                                 archive_set_error(&a->archive,
852                                     ARCHIVE_ERRNO_FILE_FORMAT,
853                                     "Symbolic mode \"%s\" unsupported", val);
854                                 return ARCHIVE_WARN;
855                         }
856                         break;
857                 }
858         case 'n':
859                 if (strcmp(key, "nlink") == 0) {
860                         *parsed_kws |= MTREE_HAS_NLINK;
861                         archive_entry_set_nlink(entry, mtree_atol10(&val));
862                         break;
863                 }
864         case 'r':
865                 if (strcmp(key, "rmd160") == 0 ||
866                     strcmp(key, "rmd160digest") == 0)
867                         break;
868         case 's':
869                 if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0)
870                         break;
871                 if (strcmp(key, "sha256") == 0 ||
872                     strcmp(key, "sha256digest") == 0)
873                         break;
874                 if (strcmp(key, "sha384") == 0 ||
875                     strcmp(key, "sha384digest") == 0)
876                         break;
877                 if (strcmp(key, "sha512") == 0 ||
878                     strcmp(key, "sha512digest") == 0)
879                         break;
880                 if (strcmp(key, "size") == 0) {
881                         archive_entry_set_size(entry, mtree_atol10(&val));
882                         break;
883                 }
884         case 't':
885                 if (strcmp(key, "tags") == 0) {
886                         /*
887                          * Comma delimited list of tags.
888                          * Ignore the tags for now, but the interface
889                          * should be extended to allow inclusion/exclusion.
890                          */
891                         break;
892                 }
893                 if (strcmp(key, "time") == 0) {
894                         *parsed_kws |= MTREE_HAS_MTIME;
895                         archive_entry_set_mtime(entry, mtree_atol10(&val), 0);
896                         break;
897                 }
898                 if (strcmp(key, "type") == 0) {
899                         *parsed_kws |= MTREE_HAS_TYPE;
900                         switch (val[0]) {
901                         case 'b':
902                                 if (strcmp(val, "block") == 0) {
903                                         mtree->filetype = AE_IFBLK;
904                                         break;
905                                 }
906                         case 'c':
907                                 if (strcmp(val, "char") == 0) {
908                                         mtree->filetype = AE_IFCHR;
909                                         break;
910                                 }
911                         case 'd':
912                                 if (strcmp(val, "dir") == 0) {
913                                         mtree->filetype = AE_IFDIR;
914                                         break;
915                                 }
916                         case 'f':
917                                 if (strcmp(val, "fifo") == 0) {
918                                         mtree->filetype = AE_IFIFO;
919                                         break;
920                                 }
921                                 if (strcmp(val, "file") == 0) {
922                                         mtree->filetype = AE_IFREG;
923                                         break;
924                                 }
925                         case 'l':
926                                 if (strcmp(val, "link") == 0) {
927                                         mtree->filetype = AE_IFLNK;
928                                         break;
929                                 }
930                         default:
931                                 archive_set_error(&a->archive,
932                                     ARCHIVE_ERRNO_FILE_FORMAT,
933                                     "Unrecognized file type \"%s\"", val);
934                                 return (ARCHIVE_WARN);
935                         }
936                         archive_entry_set_filetype(entry, mtree->filetype);
937                         break;
938                 }
939         case 'u':
940                 if (strcmp(key, "uid") == 0) {
941                         *parsed_kws |= MTREE_HAS_UID;
942                         archive_entry_set_uid(entry, mtree_atol10(&val));
943                         break;
944                 }
945                 if (strcmp(key, "uname") == 0) {
946                         *parsed_kws |= MTREE_HAS_UNAME;
947                         archive_entry_copy_uname(entry, val);
948                         break;
949                 }
950         default:
951                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
952                     "Unrecognized key %s=%s", key, val);
953                 return (ARCHIVE_WARN);
954         }
955         return (ARCHIVE_OK);
956 }
957
958 static int
959 read_data(struct archive_read *a, const void **buff, size_t *size, off_t *offset)
960 {
961         size_t bytes_to_read;
962         ssize_t bytes_read;
963         struct mtree *mtree;
964
965         mtree = (struct mtree *)(a->format->data);
966         if (mtree->fd < 0) {
967                 *buff = NULL;
968                 *offset = 0;
969                 *size = 0;
970                 return (ARCHIVE_EOF);
971         }
972         if (mtree->buff == NULL) {
973                 mtree->buffsize = 64 * 1024;
974                 mtree->buff = malloc(mtree->buffsize);
975                 if (mtree->buff == NULL) {
976                         archive_set_error(&a->archive, ENOMEM,
977                             "Can't allocate memory");
978                 }
979                 return (ARCHIVE_FATAL);
980         }
981
982         *buff = mtree->buff;
983         *offset = mtree->offset;
984         if ((off_t)mtree->buffsize > mtree->cur_size - mtree->offset)
985                 bytes_to_read = mtree->cur_size - mtree->offset;
986         else
987                 bytes_to_read = mtree->buffsize;
988         bytes_read = read(mtree->fd, mtree->buff, bytes_to_read);
989         if (bytes_read < 0) {
990                 archive_set_error(&a->archive, errno, "Can't read");
991                 return (ARCHIVE_WARN);
992         }
993         if (bytes_read == 0) {
994                 *size = 0;
995                 return (ARCHIVE_EOF);
996         }
997         mtree->offset += bytes_read;
998         *size = bytes_read;
999         return (ARCHIVE_OK);
1000 }
1001
1002 /* Skip does nothing except possibly close the contents file. */
1003 static int
1004 skip(struct archive_read *a)
1005 {
1006         struct mtree *mtree;
1007
1008         mtree = (struct mtree *)(a->format->data);
1009         if (mtree->fd >= 0) {
1010                 close(mtree->fd);
1011                 mtree->fd = -1;
1012         }
1013         return (ARCHIVE_OK);
1014 }
1015
1016 /*
1017  * Since parsing backslash sequences always makes strings shorter,
1018  * we can always do this conversion in-place.
1019  */
1020 static void
1021 parse_escapes(char *src, struct mtree_entry *mentry)
1022 {
1023         char *dest = src;
1024         char c;
1025
1026         /*
1027          * The current directory is somewhat special, it should be archived
1028          * only once as it will confuse extraction otherwise.
1029          */
1030         if (strcmp(src, ".") == 0)
1031                 mentry->full = 1;
1032
1033         while (*src != '\0') {
1034                 c = *src++;
1035                 if (c == '/' && mentry != NULL)
1036                         mentry->full = 1;
1037                 if (c == '\\') {
1038                         switch (src[0]) {
1039                         case '0':
1040                                 if (src[1] < '0' || src[1] > '7') {
1041                                         c = 0;
1042                                         ++src;
1043                                         break;
1044                                 }
1045                                 /* FALLTHROUGH */
1046                         case '1':
1047                         case '2':
1048                         case '3':
1049                                 if (src[1] >= '0' && src[1] <= '7' &&
1050                                     src[2] >= '0' && src[2] <= '7') {
1051                                         c = (src[0] - '0') << 6;
1052                                         c |= (src[1] - '0') << 3;
1053                                         c |= (src[2] - '0');
1054                                         src += 3;
1055                                 }
1056                                 break;
1057                         case 'a':
1058                                 c = '\a';
1059                                 ++src;
1060                                 break;
1061                         case 'b':
1062                                 c = '\b';
1063                                 ++src;
1064                                 break;
1065                         case 'f':
1066                                 c = '\f';
1067                                 ++src;
1068                                 break;
1069                         case 'n':
1070                                 c = '\n';
1071                                 ++src;
1072                                 break;
1073                         case 'r':
1074                                 c = '\r';
1075                                 ++src;
1076                                 break;
1077                         case 's':
1078                                 c = ' ';
1079                                 ++src;
1080                                 break;
1081                         case 't':
1082                                 c = '\t';
1083                                 ++src;
1084                                 break;
1085                         case 'v':
1086                                 c = '\v';
1087                                 ++src;
1088                                 break;
1089                         }
1090                 }
1091                 *dest++ = c;
1092         }
1093         *dest = '\0';
1094 }
1095
1096 /*
1097  * Note that this implementation does not (and should not!) obey
1098  * locale settings; you cannot simply substitute strtol here, since
1099  * it does obey locale.
1100  */
1101 static int64_t
1102 mtree_atol8(char **p)
1103 {
1104         int64_t l, limit, last_digit_limit;
1105         int digit, base;
1106
1107         base = 8;
1108         limit = INT64_MAX / base;
1109         last_digit_limit = INT64_MAX % base;
1110
1111         l = 0;
1112         digit = **p - '0';
1113         while (digit >= 0 && digit < base) {
1114                 if (l>limit || (l == limit && digit > last_digit_limit)) {
1115                         l = INT64_MAX; /* Truncate on overflow. */
1116                         break;
1117                 }
1118                 l = (l * base) + digit;
1119                 digit = *++(*p) - '0';
1120         }
1121         return (l);
1122 }
1123
1124 /*
1125  * Note that this implementation does not (and should not!) obey
1126  * locale settings; you cannot simply substitute strtol here, since
1127  * it does obey locale.
1128  */
1129 static int64_t
1130 mtree_atol10(char **p)
1131 {
1132         int64_t l, limit, last_digit_limit;
1133         int base, digit, sign;
1134
1135         base = 10;
1136         limit = INT64_MAX / base;
1137         last_digit_limit = INT64_MAX % base;
1138
1139         if (**p == '-') {
1140                 sign = -1;
1141                 ++(*p);
1142         } else
1143                 sign = 1;
1144
1145         l = 0;
1146         digit = **p - '0';
1147         while (digit >= 0 && digit < base) {
1148                 if (l > limit || (l == limit && digit > last_digit_limit)) {
1149                         l = UINT64_MAX; /* Truncate on overflow. */
1150                         break;
1151                 }
1152                 l = (l * base) + digit;
1153                 digit = *++(*p) - '0';
1154         }
1155         return (sign < 0) ? -l : l;
1156 }
1157
1158 /*
1159  * Note that this implementation does not (and should not!) obey
1160  * locale settings; you cannot simply substitute strtol here, since
1161  * it does obey locale.
1162  */
1163 static int64_t
1164 mtree_atol16(char **p)
1165 {
1166         int64_t l, limit, last_digit_limit;
1167         int base, digit, sign;
1168
1169         base = 16;
1170         limit = INT64_MAX / base;
1171         last_digit_limit = INT64_MAX % base;
1172
1173         if (**p == '-') {
1174                 sign = -1;
1175                 ++(*p);
1176         } else
1177                 sign = 1;
1178
1179         l = 0;
1180         if (**p >= '0' && **p <= '9')
1181                 digit = **p - '0';
1182         else if (**p >= 'a' && **p <= 'f')
1183                 digit = **p - 'a' + 10;
1184         else if (**p >= 'A' && **p <= 'F')
1185                 digit = **p - 'A' + 10;
1186         else
1187                 digit = -1;
1188         while (digit >= 0 && digit < base) {
1189                 if (l > limit || (l == limit && digit > last_digit_limit)) {
1190                         l = UINT64_MAX; /* Truncate on overflow. */
1191                         break;
1192                 }
1193                 l = (l * base) + digit;
1194                 if (**p >= '0' && **p <= '9')
1195                         digit = **p - '0';
1196                 else if (**p >= 'a' && **p <= 'f')
1197                         digit = **p - 'a' + 10;
1198                 else if (**p >= 'A' && **p <= 'F')
1199                         digit = **p - 'A' + 10;
1200                 else
1201                         digit = -1;
1202         }
1203         return (sign < 0) ? -l : l;
1204 }
1205
1206 static int64_t
1207 mtree_atol(char **p)
1208 {
1209         if (**p != '0')
1210                 return mtree_atol10(p);
1211         if ((*p)[1] == 'x' || (*p)[1] == 'X') {
1212                 *p += 2;
1213                 return mtree_atol16(p);
1214         }
1215         return mtree_atol8(p);
1216 }
1217
1218 /*
1219  * Returns length of line (including trailing newline)
1220  * or negative on error.  'start' argument is updated to
1221  * point to first character of line.
1222  */
1223 static ssize_t
1224 readline(struct archive_read *a, struct mtree *mtree, char **start, ssize_t limit)
1225 {
1226         ssize_t bytes_read;
1227         ssize_t total_size = 0;
1228         const void *t;
1229         const char *s;
1230         void *p;
1231         char *u;
1232
1233         /* Accumulate line in a line buffer. */
1234         for (;;) {
1235                 /* Read some more. */
1236                 t = __archive_read_ahead(a, 1, &bytes_read);
1237                 if (t == NULL)
1238                         return (0);
1239                 if (bytes_read < 0)
1240                         return (ARCHIVE_FATAL);
1241                 s = t;  /* Start of line? */
1242                 p = memchr(t, '\n', bytes_read);
1243                 /* If we found '\n', trim the read. */
1244                 if (p != NULL) {
1245                         bytes_read = 1 + ((const char *)p) - s;
1246                 }
1247                 if (total_size + bytes_read + 1 > limit) {
1248                         archive_set_error(&a->archive,
1249                             ARCHIVE_ERRNO_FILE_FORMAT,
1250                             "Line too long");
1251                         return (ARCHIVE_FATAL);
1252                 }
1253                 if (archive_string_ensure(&mtree->line,
1254                         total_size + bytes_read + 1) == NULL) {
1255                         archive_set_error(&a->archive, ENOMEM,
1256                             "Can't allocate working buffer");
1257                         return (ARCHIVE_FATAL);
1258                 }
1259                 memcpy(mtree->line.s + total_size, t, bytes_read);
1260                 __archive_read_consume(a, bytes_read);
1261                 total_size += bytes_read;
1262                 /* Null terminate. */
1263                 mtree->line.s[total_size] = '\0';
1264                 /* If we found an unescaped '\n', clean up and return. */
1265                 if (p == NULL)
1266                         continue;
1267                 for (u = mtree->line.s; *u; ++u) {
1268                         if (u[0] == '\n') {
1269                                 *start = mtree->line.s;
1270                                 return total_size;
1271                         }
1272                         if (u[0] == '#') {
1273                                 if (p == NULL)
1274                                         break;
1275                                 *start = mtree->line.s;
1276                                 return total_size;
1277                         }
1278                         if (u[0] != '\\')
1279                                 continue;
1280                         if (u[1] == '\\') {
1281                                 ++u;
1282                                 continue;
1283                         }
1284                         if (u[1] == '\n') {
1285                                 memmove(u, u + 1,
1286                                     total_size - (u - mtree->line.s) + 1);
1287                                 --total_size;
1288                                 continue;    
1289                         }
1290                 }
1291         }
1292 }