Merge branch 'vendor/LIBARCHIVE'
[dragonfly.git] / contrib / libarchive / libarchive / archive_read_support_format_mtree.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * Copyright (c) 2008 Joerg Sonnenberger
4  * Copyright (c) 2011 Michihiro NAKAJIMA
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_mtree.c 201165 2009-12-29 05:52:13Z kientzle $");
30
31 #ifdef HAVE_SYS_STAT_H
32 #include <sys/stat.h>
33 #endif
34 #ifdef HAVE_ERRNO_H
35 #include <errno.h>
36 #endif
37 #ifdef HAVE_FCNTL_H
38 #include <fcntl.h>
39 #endif
40 #include <stddef.h>
41 /* #include <stdint.h> */ /* See archive_platform.h */
42 #ifdef HAVE_STDLIB_H
43 #include <stdlib.h>
44 #endif
45 #ifdef HAVE_STRING_H
46 #include <string.h>
47 #endif
48
49 #include "archive.h"
50 #include "archive_entry.h"
51 #include "archive_private.h"
52 #include "archive_read_private.h"
53 #include "archive_string.h"
54
55 #ifndef O_BINARY
56 #define O_BINARY 0
57 #endif
58
59 #define MTREE_HAS_DEVICE        0x0001
60 #define MTREE_HAS_FFLAGS        0x0002
61 #define MTREE_HAS_GID           0x0004
62 #define MTREE_HAS_GNAME         0x0008
63 #define MTREE_HAS_MTIME         0x0010
64 #define MTREE_HAS_NLINK         0x0020
65 #define MTREE_HAS_PERM          0x0040
66 #define MTREE_HAS_SIZE          0x0080
67 #define MTREE_HAS_TYPE          0x0100
68 #define MTREE_HAS_UID           0x0200
69 #define MTREE_HAS_UNAME         0x0400
70
71 #define MTREE_HAS_OPTIONAL      0x0800
72
73 struct mtree_option {
74         struct mtree_option *next;
75         char *value;
76 };
77
78 struct mtree_entry {
79         struct mtree_entry *next;
80         struct mtree_option *options;
81         char *name;
82         char full;
83         char used;
84 };
85
86 struct mtree {
87         struct archive_string    line;
88         size_t                   buffsize;
89         char                    *buff;
90         int64_t                  offset;
91         int                      fd;
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         int64_t                  cur_size;
102 };
103
104 static int      cleanup(struct archive_read *);
105 static int      mtree_bid(struct archive_read *, int);
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, int64_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 /*
124  * There's no standard for TIME_T_MAX/TIME_T_MIN.  So we compute them
125  * here.  TODO: Move this to configure time, but be careful
126  * about cross-compile environments.
127  */
128 static int64_t
129 get_time_t_max(void)
130 {
131 #if defined(TIME_T_MAX)
132         return TIME_T_MAX;
133 #else
134         static time_t t;
135         time_t a;
136         if (t == 0) {
137                 a = 1;
138                 while (a > t) {
139                         t = a;
140                         a = a * 2 + 1;
141                 }
142         }
143         return t;
144 #endif
145 }
146
147 static int64_t
148 get_time_t_min(void)
149 {
150 #if defined(TIME_T_MIN)
151         return TIME_T_MIN;
152 #else
153         /* 't' will hold the minimum value, which will be zero (if
154          * time_t is unsigned) or -2^n (if time_t is signed). */
155         static int computed;
156         static time_t t;
157         time_t a;
158         if (computed == 0) {
159                 a = (time_t)-1;
160                 while (a < t) {
161                         t = a;
162                         a = a * 2;
163                 }                       
164                 computed = 1;
165         }
166         return t;
167 #endif
168 }
169
170 static void
171 free_options(struct mtree_option *head)
172 {
173         struct mtree_option *next;
174
175         for (; head != NULL; head = next) {
176                 next = head->next;
177                 free(head->value);
178                 free(head);
179         }
180 }
181
182 int
183 archive_read_support_format_mtree(struct archive *_a)
184 {
185         struct archive_read *a = (struct archive_read *)_a;
186         struct mtree *mtree;
187         int r;
188
189         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
190             ARCHIVE_STATE_NEW, "archive_read_support_format_mtree");
191
192         mtree = (struct mtree *)malloc(sizeof(*mtree));
193         if (mtree == NULL) {
194                 archive_set_error(&a->archive, ENOMEM,
195                     "Can't allocate mtree data");
196                 return (ARCHIVE_FATAL);
197         }
198         memset(mtree, 0, sizeof(*mtree));
199         mtree->fd = -1;
200
201         r = __archive_read_register_format(a, mtree, "mtree",
202             mtree_bid, NULL, read_header, read_data, skip, cleanup);
203
204         if (r != ARCHIVE_OK)
205                 free(mtree);
206         return (ARCHIVE_OK);
207 }
208
209 static int
210 cleanup(struct archive_read *a)
211 {
212         struct mtree *mtree;
213         struct mtree_entry *p, *q;
214
215         mtree = (struct mtree *)(a->format->data);
216
217         p = mtree->entries;
218         while (p != NULL) {
219                 q = p->next;
220                 free(p->name);
221                 free_options(p->options);
222                 free(p);
223                 p = q;
224         }
225         archive_string_free(&mtree->line);
226         archive_string_free(&mtree->current_dir);
227         archive_string_free(&mtree->contents_name);
228         archive_entry_linkresolver_free(mtree->resolver);
229
230         free(mtree->buff);
231         free(mtree);
232         (a->format->data) = NULL;
233         return (ARCHIVE_OK);
234 }
235
236 static ssize_t
237 get_line_size(const char *b, ssize_t avail, ssize_t *nlsize)
238 {
239         ssize_t len;
240
241         len = 0;
242         while (len < avail) {
243                 switch (*b) {
244                 case '\0':/* Non-ascii character or control character. */
245                         if (nlsize != NULL)
246                                 *nlsize = 0;
247                         return (-1);
248                 case '\r':
249                         if (avail-len > 1 && b[1] == '\n') {
250                                 if (nlsize != NULL)
251                                         *nlsize = 2;
252                                 return (len+2);
253                         }
254                         /* FALL THROUGH */
255                 case '\n':
256                         if (nlsize != NULL)
257                                 *nlsize = 1;
258                         return (len+1);
259                 default:
260                         b++;
261                         len++;
262                         break;
263                 }
264         }
265         if (nlsize != NULL)
266                 *nlsize = 0;
267         return (avail);
268 }
269
270 static ssize_t
271 next_line(struct archive_read *a,
272     const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
273 {
274         ssize_t len;
275         int quit;
276         
277         quit = 0;
278         if (*avail == 0) {
279                 *nl = 0;
280                 len = 0;
281         } else
282                 len = get_line_size(*b, *avail, nl);
283         /*
284          * Read bytes more while it does not reach the end of line.
285          */
286         while (*nl == 0 && len == *avail && !quit) {
287                 ssize_t diff = *ravail - *avail;
288                 size_t nbytes_req = (*ravail+1023) & ~1023U;
289                 ssize_t tested;
290
291                 /* Increase reading bytes if it is not enough to at least
292                  * new two lines. */
293                 if (nbytes_req < (size_t)*ravail + 160)
294                         nbytes_req <<= 1;
295
296                 *b = __archive_read_ahead(a, nbytes_req, avail);
297                 if (*b == NULL) {
298                         if (*ravail >= *avail)
299                                 return (0);
300                         /* Reading bytes reaches the end of file. */
301                         *b = __archive_read_ahead(a, *avail, avail);
302                         quit = 1;
303                 }
304                 *ravail = *avail;
305                 *b += diff;
306                 *avail -= diff;
307                 tested = len;/* Skip some bytes we already determinated. */
308                 len = get_line_size(*b, *avail, nl);
309                 if (len >= 0)
310                         len += tested;
311         }
312         return (len);
313 }
314
315 /*
316  * Compare characters with a mtree keyword.
317  * Returns the length of a mtree keyword if matched.
318  * Returns 0 if not matched.
319  */
320 int
321 bid_keycmp(const char *p, const char *key, ssize_t len)
322 {
323         int match_len = 0;
324
325         while (len > 0 && *p && *key) {
326                 if (*p == *key) {
327                         --len;
328                         ++p;
329                         ++key;
330                         ++match_len;
331                         continue;
332                 }
333                 return (0);/* Not match */
334         }
335         if (*key != '\0')
336                 return (0);/* Not match */
337
338         /* A following character should be specified characters */
339         if (p[0] == '=' || p[0] == ' ' || p[0] == '\t' ||
340             p[0] == '\n' || p[0] == '\r' ||
341            (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r')))
342                 return (match_len);
343         return (0);/* Not match */
344 }
345
346 /*
347  * Test whether the characters 'p' has is mtree keyword.
348  * Returns the length of a detected keyword.
349  * Returns 0 if any keywords were not found.
350  */
351 static ssize_t
352 bid_keyword(const char *p,  ssize_t len)
353 {
354         static const char *keys_c[] = {
355                 "content", "contents", "cksum", NULL
356         };
357         static const char *keys_df[] = {
358                 "device", "flags", NULL
359         };
360         static const char *keys_g[] = {
361                 "gid", "gname", NULL
362         };
363         static const char *keys_il[] = {
364                 "ignore", "link", NULL
365         };
366         static const char *keys_m[] = {
367                 "md5", "md5digest", "mode", NULL
368         };
369         static const char *keys_no[] = {
370                 "nlink", "optional", NULL
371         };
372         static const char *keys_r[] = {
373                 "rmd160", "rmd160digest", NULL
374         };
375         static const char *keys_s[] = {
376                 "sha1", "sha1digest",
377                 "sha256", "sha256digest",
378                 "sha384", "sha384digest",
379                 "sha512", "sha512digest",
380                 "size", NULL
381         };
382         static const char *keys_t[] = {
383                 "tags", "time", "type", NULL
384         };
385         static const char *keys_u[] = {
386                 "uid", "uname", NULL
387         };
388         const char **keys;
389         int i;
390
391         switch (*p) {
392         case 'c': keys = keys_c; break;
393         case 'd': case 'f': keys = keys_df; break;
394         case 'g': keys = keys_g; break;
395         case 'i': case 'l': keys = keys_il; break;
396         case 'm': keys = keys_m; break;
397         case 'n': case 'o': keys = keys_no; break;
398         case 'r': keys = keys_r; break;
399         case 's': keys = keys_s; break;
400         case 't': keys = keys_t; break;
401         case 'u': keys = keys_u; break;
402         default: return (0);/* Unknown key */
403         }
404
405         for (i = 0; keys[i] != NULL; i++) {
406                 int l = bid_keycmp(p, keys[i], len);
407                 if (l > 0)
408                         return (l);
409         }
410         return (0);/* Unknown key */
411 }
412
413 /*
414  * Test whether there is a set of mtree keywords.
415  * Returns the number of keyword.
416  * Returns -1 if we got incorrect sequence.
417  * This function expects a set of "<space characters>keyword=value".
418  * When "unset" is specified, expects a set of "<space characters>keyword".
419  */
420 static int
421 bid_keyword_list(const char *p,  ssize_t len, int unset)
422 {
423         int l;
424         int keycnt = 0;
425
426         while (len > 0 && *p) {
427                 int blank = 0;
428
429                 /* Test whether there are blank characters in the line. */
430                 while (len >0 && (*p == ' ' || *p == '\t')) {
431                         ++p;
432                         --len;
433                         blank = 1;
434                 }
435                 if (*p == '\n' || *p == '\r')
436                         break;
437                 if (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r'))
438                         break;
439                 if (!blank) /* No blank character. */
440                         return (-1);
441
442                 if (unset) {
443                         l = bid_keycmp(p, "all", len);
444                         if (l > 0)
445                                 return (1);
446                 }
447                 /* Test whether there is a correct key in the line. */
448                 l = bid_keyword(p, len);
449                 if (l == 0)
450                         return (-1);/* Unknown keyword was found. */
451                 p += l;
452                 len -= l;
453                 keycnt++;
454
455                 /* Skip value */
456                 if (*p == '=') {
457                         int value = 0;
458                         ++p;
459                         --len;
460                         while (len > 0 && *p != ' ' && *p != '\t') {
461                                 ++p;
462                                 --len;
463                                 value = 1;
464                         }
465                         /* A keyword should have a its value unless
466                          * "/unset" operation. */ 
467                         if (!unset && value == 0)
468                                 return (-1);
469                 }
470         }
471         return (keycnt);
472 }
473
474 static int
475 bid_entry(const char *p, ssize_t len)
476 {
477         int f = 0;
478         static const unsigned char safe_char[256] = {
479                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */
480                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */
481                 /* !"$%&'()*+,-./  EXCLUSION:( )(#) */
482                 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */
483                 /* 0123456789:;<>?  EXCLUSION:(=) */
484                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, /* 30 - 3F */
485                 /* @ABCDEFGHIJKLMNO */
486                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */
487                 /* PQRSTUVWXYZ[\]^_  */
488                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */
489                 /* `abcdefghijklmno */
490                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */
491                 /* pqrstuvwxyz{|}~ */
492                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 70 - 7F */
493                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */
494                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */
495                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */
496                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */
497                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */
498                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */
499                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */
500                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */
501         };
502
503         /*
504          * Skip the path-name which is quoted.
505          */
506         while (len > 0 && *p != ' ' && *p != '\t') {
507                 if (!safe_char[*(const unsigned char *)p])
508                         return (-1);
509                 ++p;
510                 --len;
511                 ++f;
512         }
513         /* If a path-name was not found, returns error. */
514         if (f == 0)
515                 return (-1);
516
517         return (bid_keyword_list(p, len, 0));
518 }
519
520 #define MAX_BID_ENTRY   3
521
522 static int
523 mtree_bid(struct archive_read *a, int best_bid)
524 {
525         const char *signature = "#mtree";
526         const char *p;
527         ssize_t avail, ravail;
528         ssize_t len, nl;
529         int detected_bytes = 0, entry_cnt = 0, multiline = 0;
530
531         (void)best_bid; /* UNUSED */
532
533         /* Now let's look at the actual header and see if it matches. */
534         p = __archive_read_ahead(a, strlen(signature), &avail);
535         if (p == NULL)
536                 return (-1);
537
538         if (memcmp(p, signature, strlen(signature)) == 0)
539                 return (8 * (int)strlen(signature));
540
541         /*
542          * There is not a mtree signature. Let's try to detect mtree format.
543          */
544         ravail = avail;
545         for (;;) {
546                 len = next_line(a, &p, &avail, &ravail, &nl);
547                 /* The terminal character of the line should be
548                  * a new line character, '\r\n' or '\n'. */
549                 if (len <= 0 || nl == 0)
550                         break;
551                 if (!multiline) {
552                         /* Leading whitespace is never significant,
553                          * ignore it. */
554                         while (len > 0 && (*p == ' ' || *p == '\t')) {
555                                 ++p;
556                                 --avail;
557                                 --len;
558                         }
559                         /* Skip comment or empty line. */ 
560                         if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') {
561                                 p += len;
562                                 avail -= len;
563                                 continue;
564                         }
565                 } else {
566                         /* A continuance line; the terminal
567                          * character of previous line was '\' character. */
568                         if (bid_keyword_list(p, len, 0) <= 0)
569                                 break;
570                         if (multiline == 1)
571                                 detected_bytes += len;
572                         if (p[len-nl-1] != '\\') {
573                                 if (multiline == 1 &&
574                                     ++entry_cnt >= MAX_BID_ENTRY)
575                                         break;
576                                 multiline = 0;
577                         }
578                         p += len;
579                         avail -= len;
580                         continue;
581                 }
582                 if (p[0] != '/') {
583                         if (bid_entry(p, len) >= 0) {
584                                 detected_bytes += len;
585                                 if (p[len-nl-1] == '\\')
586                                         /* This line continues. */
587                                         multiline = 1;
588                                 else {
589                                         /* We've got plenty of correct lines
590                                          * to assume that this file is a mtree
591                                          * format. */
592                                         if (++entry_cnt >= MAX_BID_ENTRY)
593                                                 break;
594                                 }
595                         } else
596                                 break;
597                 } else if (strncmp(p, "/set", 4) == 0) {
598                         if (bid_keyword_list(p+4, len-4, 0) <= 0)
599                                 break;
600                         /* This line continues. */
601                         if (p[len-nl-1] == '\\')
602                                 multiline = 2;
603                 } else if (strncmp(p, "/unset", 6) == 0) {
604                         if (bid_keyword_list(p+6, len-6, 1) <= 0)
605                                 break;
606                         /* This line continues. */
607                         if (p[len-nl-1] == '\\')
608                                 multiline = 2;
609                 } else
610                         break;
611
612                 /* Test next line. */
613                 p += len;
614                 avail -= len;
615         }
616         if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0))
617                 return (32);
618
619         return (0);
620 }
621
622 /*
623  * The extended mtree format permits multiple lines specifying
624  * attributes for each file.  For those entries, only the last line
625  * is actually used.  Practically speaking, that means we have
626  * to read the entire mtree file into memory up front.
627  *
628  * The parsing is done in two steps.  First, it is decided if a line
629  * changes the global defaults and if it is, processed accordingly.
630  * Otherwise, the options of the line are merged with the current
631  * global options.
632  */
633 static int
634 add_option(struct archive_read *a, struct mtree_option **global,
635     const char *value, size_t len)
636 {
637         struct mtree_option *opt;
638
639         if ((opt = malloc(sizeof(*opt))) == NULL) {
640                 archive_set_error(&a->archive, errno, "Can't allocate memory");
641                 return (ARCHIVE_FATAL);
642         }
643         if ((opt->value = malloc(len + 1)) == NULL) {
644                 free(opt);
645                 archive_set_error(&a->archive, errno, "Can't allocate memory");
646                 return (ARCHIVE_FATAL);
647         }
648         memcpy(opt->value, value, len);
649         opt->value[len] = '\0';
650         opt->next = *global;
651         *global = opt;
652         return (ARCHIVE_OK);
653 }
654
655 static void
656 remove_option(struct mtree_option **global, const char *value, size_t len)
657 {
658         struct mtree_option *iter, *last;
659
660         last = NULL;
661         for (iter = *global; iter != NULL; last = iter, iter = iter->next) {
662                 if (strncmp(iter->value, value, len) == 0 &&
663                     (iter->value[len] == '\0' ||
664                      iter->value[len] == '='))
665                         break;
666         }
667         if (iter == NULL)
668                 return;
669         if (last == NULL)
670                 *global = iter->next;
671         else
672                 last->next = iter->next;
673
674         free(iter->value);
675         free(iter);
676 }
677
678 static int
679 process_global_set(struct archive_read *a,
680     struct mtree_option **global, const char *line)
681 {
682         const char *next, *eq;
683         size_t len;
684         int r;
685
686         line += 4;
687         for (;;) {
688                 next = line + strspn(line, " \t\r\n");
689                 if (*next == '\0')
690                         return (ARCHIVE_OK);
691                 line = next;
692                 next = line + strcspn(line, " \t\r\n");
693                 eq = strchr(line, '=');
694                 if (eq > next)
695                         len = next - line;
696                 else
697                         len = eq - line;
698
699                 remove_option(global, line, len);
700                 r = add_option(a, global, line, next - line);
701                 if (r != ARCHIVE_OK)
702                         return (r);
703                 line = next;
704         }
705 }
706
707 static int
708 process_global_unset(struct archive_read *a,
709     struct mtree_option **global, const char *line)
710 {
711         const char *next;
712         size_t len;
713
714         line += 6;
715         if (strchr(line, '=') != NULL) {
716                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
717                     "/unset shall not contain `='");
718                 return ARCHIVE_FATAL;
719         }
720
721         for (;;) {
722                 next = line + strspn(line, " \t\r\n");
723                 if (*next == '\0')
724                         return (ARCHIVE_OK);
725                 line = next;
726                 len = strcspn(line, " \t\r\n");
727
728                 if (len == 3 && strncmp(line, "all", 3) == 0) {
729                         free_options(*global);
730                         *global = NULL;
731                 } else {
732                         remove_option(global, line, len);
733                 }
734
735                 line += len;
736         }
737 }
738
739 static int
740 process_add_entry(struct archive_read *a, struct mtree *mtree,
741     struct mtree_option **global, const char *line,
742     struct mtree_entry **last_entry)
743 {
744         struct mtree_entry *entry;
745         struct mtree_option *iter;
746         const char *next, *eq;
747         size_t len;
748         int r;
749
750         if ((entry = malloc(sizeof(*entry))) == NULL) {
751                 archive_set_error(&a->archive, errno, "Can't allocate memory");
752                 return (ARCHIVE_FATAL);
753         }
754         entry->next = NULL;
755         entry->options = NULL;
756         entry->name = NULL;
757         entry->used = 0;
758         entry->full = 0;
759
760         /* Add this entry to list. */
761         if (*last_entry == NULL)
762                 mtree->entries = entry;
763         else
764                 (*last_entry)->next = entry;
765         *last_entry = entry;
766
767         len = strcspn(line, " \t\r\n");
768         if ((entry->name = malloc(len + 1)) == NULL) {
769                 archive_set_error(&a->archive, errno, "Can't allocate memory");
770                 return (ARCHIVE_FATAL);
771         }
772
773         memcpy(entry->name, line, len);
774         entry->name[len] = '\0';
775         parse_escapes(entry->name, entry);
776
777         line += len;
778         for (iter = *global; iter != NULL; iter = iter->next) {
779                 r = add_option(a, &entry->options, iter->value,
780                     strlen(iter->value));
781                 if (r != ARCHIVE_OK)
782                         return (r);
783         }
784
785         for (;;) {
786                 next = line + strspn(line, " \t\r\n");
787                 if (*next == '\0')
788                         return (ARCHIVE_OK);
789                 line = next;
790                 next = line + strcspn(line, " \t\r\n");
791                 eq = strchr(line, '=');
792                 if (eq == NULL || eq > next)
793                         len = next - line;
794                 else
795                         len = eq - line;
796
797                 remove_option(&entry->options, line, len);
798                 r = add_option(a, &entry->options, line, next - line);
799                 if (r != ARCHIVE_OK)
800                         return (r);
801                 line = next;
802         }
803 }
804
805 static int
806 read_mtree(struct archive_read *a, struct mtree *mtree)
807 {
808         ssize_t len;
809         uintmax_t counter;
810         char *p;
811         struct mtree_option *global;
812         struct mtree_entry *last_entry;
813         int r;
814
815         mtree->archive_format = ARCHIVE_FORMAT_MTREE;
816         mtree->archive_format_name = "mtree";
817
818         global = NULL;
819         last_entry = NULL;
820
821         for (counter = 1; ; ++counter) {
822                 len = readline(a, mtree, &p, 65536);
823                 if (len == 0) {
824                         mtree->this_entry = mtree->entries;
825                         free_options(global);
826                         return (ARCHIVE_OK);
827                 }
828                 if (len < 0) {
829                         free_options(global);
830                         return (len);
831                 }
832                 /* Leading whitespace is never significant, ignore it. */
833                 while (*p == ' ' || *p == '\t') {
834                         ++p;
835                         --len;
836                 }
837                 /* Skip content lines and blank lines. */
838                 if (*p == '#')
839                         continue;
840                 if (*p == '\r' || *p == '\n' || *p == '\0')
841                         continue;
842                 if (*p != '/') {
843                         r = process_add_entry(a, mtree, &global, p,
844                             &last_entry);
845                 } else if (strncmp(p, "/set", 4) == 0) {
846                         if (p[4] != ' ' && p[4] != '\t')
847                                 break;
848                         r = process_global_set(a, &global, p);
849                 } else if (strncmp(p, "/unset", 6) == 0) {
850                         if (p[6] != ' ' && p[6] != '\t')
851                                 break;
852                         r = process_global_unset(a, &global, p);
853                 } else
854                         break;
855
856                 if (r != ARCHIVE_OK) {
857                         free_options(global);
858                         return r;
859                 }
860         }
861
862         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
863             "Can't parse line %ju", counter);
864         free_options(global);
865         return (ARCHIVE_FATAL);
866 }
867
868 /*
869  * Read in the entire mtree file into memory on the first request.
870  * Then use the next unused file to satisfy each header request.
871  */
872 static int
873 read_header(struct archive_read *a, struct archive_entry *entry)
874 {
875         struct mtree *mtree;
876         char *p;
877         int r, use_next;
878
879         mtree = (struct mtree *)(a->format->data);
880
881         if (mtree->fd >= 0) {
882                 close(mtree->fd);
883                 mtree->fd = -1;
884         }
885
886         if (mtree->entries == NULL) {
887                 mtree->resolver = archive_entry_linkresolver_new();
888                 if (mtree->resolver == NULL)
889                         return ARCHIVE_FATAL;
890                 archive_entry_linkresolver_set_strategy(mtree->resolver,
891                     ARCHIVE_FORMAT_MTREE);
892                 r = read_mtree(a, mtree);
893                 if (r != ARCHIVE_OK)
894                         return (r);
895         }
896
897         a->archive.archive_format = mtree->archive_format;
898         a->archive.archive_format_name = mtree->archive_format_name;
899
900         for (;;) {
901                 if (mtree->this_entry == NULL)
902                         return (ARCHIVE_EOF);
903                 if (strcmp(mtree->this_entry->name, "..") == 0) {
904                         mtree->this_entry->used = 1;
905                         if (archive_strlen(&mtree->current_dir) > 0) {
906                                 /* Roll back current path. */
907                                 p = mtree->current_dir.s
908                                     + mtree->current_dir.length - 1;
909                                 while (p >= mtree->current_dir.s && *p != '/')
910                                         --p;
911                                 if (p >= mtree->current_dir.s)
912                                         --p;
913                                 mtree->current_dir.length
914                                     = p - mtree->current_dir.s + 1;
915                         }
916                 }
917                 if (!mtree->this_entry->used) {
918                         use_next = 0;
919                         r = parse_file(a, entry, mtree, mtree->this_entry, &use_next);
920                         if (use_next == 0)
921                                 return (r);
922                 }
923                 mtree->this_entry = mtree->this_entry->next;
924         }
925 }
926
927 /*
928  * A single file can have multiple lines contribute specifications.
929  * Parse as many lines as necessary, then pull additional information
930  * from a backing file on disk as necessary.
931  */
932 static int
933 parse_file(struct archive_read *a, struct archive_entry *entry,
934     struct mtree *mtree, struct mtree_entry *mentry, int *use_next)
935 {
936         const char *path;
937         struct stat st_storage, *st;
938         struct mtree_entry *mp;
939         struct archive_entry *sparse_entry;
940         int r = ARCHIVE_OK, r1, parsed_kws;
941
942         mentry->used = 1;
943
944         /* Initialize reasonable defaults. */
945         archive_entry_set_filetype(entry, AE_IFREG);
946         archive_entry_set_size(entry, 0);
947         archive_string_empty(&mtree->contents_name);
948
949         /* Parse options from this line. */
950         parsed_kws = 0;
951         r = parse_line(a, entry, mtree, mentry, &parsed_kws);
952
953         if (mentry->full) {
954                 archive_entry_copy_pathname(entry, mentry->name);
955                 /*
956                  * "Full" entries are allowed to have multiple lines
957                  * and those lines aren't required to be adjacent.  We
958                  * don't support multiple lines for "relative" entries
959                  * nor do we make any attempt to merge data from
960                  * separate "relative" and "full" entries.  (Merging
961                  * "relative" and "full" entries would require dealing
962                  * with pathname canonicalization, which is a very
963                  * tricky subject.)
964                  */
965                 for (mp = mentry->next; mp != NULL; mp = mp->next) {
966                         if (mp->full && !mp->used
967                             && strcmp(mentry->name, mp->name) == 0) {
968                                 /* Later lines override earlier ones. */
969                                 mp->used = 1;
970                                 r1 = parse_line(a, entry, mtree, mp,
971                                     &parsed_kws);
972                                 if (r1 < r)
973                                         r = r1;
974                         }
975                 }
976         } else {
977                 /*
978                  * Relative entries require us to construct
979                  * the full path and possibly update the
980                  * current directory.
981                  */
982                 size_t n = archive_strlen(&mtree->current_dir);
983                 if (n > 0)
984                         archive_strcat(&mtree->current_dir, "/");
985                 archive_strcat(&mtree->current_dir, mentry->name);
986                 archive_entry_copy_pathname(entry, mtree->current_dir.s);
987                 if (archive_entry_filetype(entry) != AE_IFDIR)
988                         mtree->current_dir.length = n;
989         }
990
991         /*
992          * Try to open and stat the file to get the real size
993          * and other file info.  It would be nice to avoid
994          * this here so that getting a listing of an mtree
995          * wouldn't require opening every referenced contents
996          * file.  But then we wouldn't know the actual
997          * contents size, so I don't see a really viable way
998          * around this.  (Also, we may want to someday pull
999          * other unspecified info from the contents file on
1000          * disk.)
1001          */
1002         mtree->fd = -1;
1003         if (archive_strlen(&mtree->contents_name) > 0)
1004                 path = mtree->contents_name.s;
1005         else
1006                 path = archive_entry_pathname(entry);
1007
1008         if (archive_entry_filetype(entry) == AE_IFREG ||
1009             archive_entry_filetype(entry) == AE_IFDIR) {
1010                 mtree->fd = open(path, O_RDONLY | O_BINARY);
1011                 if (mtree->fd == -1 &&
1012                     (errno != ENOENT ||
1013                      archive_strlen(&mtree->contents_name) > 0)) {
1014                         archive_set_error(&a->archive, errno,
1015                             "Can't open %s", path);
1016                         r = ARCHIVE_WARN;
1017                 }
1018         }
1019
1020         st = &st_storage;
1021         if (mtree->fd >= 0) {
1022                 if (fstat(mtree->fd, st) == -1) {
1023                         archive_set_error(&a->archive, errno,
1024                             "Could not fstat %s", path);
1025                         r = ARCHIVE_WARN;
1026                         /* If we can't stat it, don't keep it open. */
1027                         close(mtree->fd);
1028                         mtree->fd = -1;
1029                         st = NULL;
1030                 }
1031         } else if (lstat(path, st) == -1) {
1032                 st = NULL;
1033         }
1034
1035         /*
1036          * Check for a mismatch between the type in the specification and
1037          * the type of the contents object on disk.
1038          */
1039         if (st != NULL) {
1040                 if (
1041                     ((st->st_mode & S_IFMT) == S_IFREG &&
1042                      archive_entry_filetype(entry) == AE_IFREG)
1043 #ifdef S_IFLNK
1044                     || ((st->st_mode & S_IFMT) == S_IFLNK &&
1045                         archive_entry_filetype(entry) == AE_IFLNK)
1046 #endif
1047 #ifdef S_IFSOCK
1048                     || ((st->st_mode & S_IFSOCK) == S_IFSOCK &&
1049                         archive_entry_filetype(entry) == AE_IFSOCK)
1050 #endif
1051 #ifdef S_IFCHR
1052                     || ((st->st_mode & S_IFMT) == S_IFCHR &&
1053                         archive_entry_filetype(entry) == AE_IFCHR)
1054 #endif
1055 #ifdef S_IFBLK
1056                     || ((st->st_mode & S_IFMT) == S_IFBLK &&
1057                         archive_entry_filetype(entry) == AE_IFBLK)
1058 #endif
1059                     || ((st->st_mode & S_IFMT) == S_IFDIR &&
1060                         archive_entry_filetype(entry) == AE_IFDIR)
1061 #ifdef S_IFIFO
1062                     || ((st->st_mode & S_IFMT) == S_IFIFO &&
1063                         archive_entry_filetype(entry) == AE_IFIFO)
1064 #endif
1065                     ) {
1066                         /* Types match. */
1067                 } else {
1068                         /* Types don't match; bail out gracefully. */
1069                         if (mtree->fd >= 0)
1070                                 close(mtree->fd);
1071                         mtree->fd = -1;
1072                         if (parsed_kws & MTREE_HAS_OPTIONAL) {
1073                                 /* It's not an error for an optional entry
1074                                    to not match disk. */
1075                                 *use_next = 1;
1076                         } else if (r == ARCHIVE_OK) {
1077                                 archive_set_error(&a->archive,
1078                                     ARCHIVE_ERRNO_MISC,
1079                                     "mtree specification has different type for %s",
1080                                     archive_entry_pathname(entry));
1081                                 r = ARCHIVE_WARN;
1082                         }
1083                         return r;
1084                 }
1085         }
1086
1087         /*
1088          * If there is a contents file on disk, pick some of the metadata
1089          * from that file.  For most of these, we only set it from the contents
1090          * if it wasn't already parsed from the specification.
1091          */
1092         if (st != NULL) {
1093                 if ((parsed_kws & MTREE_HAS_DEVICE) == 0 &&
1094                     (archive_entry_filetype(entry) == AE_IFCHR ||
1095                      archive_entry_filetype(entry) == AE_IFBLK))
1096                         archive_entry_set_rdev(entry, st->st_rdev);
1097                 if ((parsed_kws & (MTREE_HAS_GID | MTREE_HAS_GNAME)) == 0)
1098                         archive_entry_set_gid(entry, st->st_gid);
1099                 if ((parsed_kws & (MTREE_HAS_UID | MTREE_HAS_UNAME)) == 0)
1100                         archive_entry_set_uid(entry, st->st_uid);
1101                 if ((parsed_kws & MTREE_HAS_MTIME) == 0) {
1102 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
1103                         archive_entry_set_mtime(entry, st->st_mtime,
1104                             st->st_mtimespec.tv_nsec);
1105 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
1106                         archive_entry_set_mtime(entry, st->st_mtime,
1107                             st->st_mtim.tv_nsec);
1108 #elif HAVE_STRUCT_STAT_ST_MTIME_N
1109                         archive_entry_set_mtime(entry, st->st_mtime,
1110                             st->st_mtime_n);
1111 #elif HAVE_STRUCT_STAT_ST_UMTIME
1112                         archive_entry_set_mtime(entry, st->st_mtime,
1113                             st->st_umtime*1000);
1114 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
1115                         archive_entry_set_mtime(entry, st->st_mtime,
1116                             st->st_mtime_usec*1000);
1117 #else
1118                         archive_entry_set_mtime(entry, st->st_mtime, 0);
1119 #endif
1120                 }
1121                 if ((parsed_kws & MTREE_HAS_NLINK) == 0)
1122                         archive_entry_set_nlink(entry, st->st_nlink);
1123                 if ((parsed_kws & MTREE_HAS_PERM) == 0)
1124                         archive_entry_set_perm(entry, st->st_mode);
1125                 if ((parsed_kws & MTREE_HAS_SIZE) == 0)
1126                         archive_entry_set_size(entry, st->st_size);
1127                 archive_entry_set_ino(entry, st->st_ino);
1128                 archive_entry_set_dev(entry, st->st_dev);
1129
1130                 archive_entry_linkify(mtree->resolver, &entry, &sparse_entry);
1131         } else if (parsed_kws & MTREE_HAS_OPTIONAL) {
1132                 /*
1133                  * Couldn't open the entry, stat it or the on-disk type
1134                  * didn't match.  If this entry is optional, just ignore it
1135                  * and read the next header entry.
1136                  */
1137                 *use_next = 1;
1138                 return ARCHIVE_OK;
1139         }
1140
1141         mtree->cur_size = archive_entry_size(entry);
1142         mtree->offset = 0;
1143
1144         return r;
1145 }
1146
1147 /*
1148  * Each line contains a sequence of keywords.
1149  */
1150 static int
1151 parse_line(struct archive_read *a, struct archive_entry *entry,
1152     struct mtree *mtree, struct mtree_entry *mp, int *parsed_kws)
1153 {
1154         struct mtree_option *iter;
1155         int r = ARCHIVE_OK, r1;
1156
1157         for (iter = mp->options; iter != NULL; iter = iter->next) {
1158                 r1 = parse_keyword(a, mtree, entry, iter, parsed_kws);
1159                 if (r1 < r)
1160                         r = r1;
1161         }
1162         if (r == ARCHIVE_OK && (*parsed_kws & MTREE_HAS_TYPE) == 0) {
1163                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1164                     "Missing type keyword in mtree specification");
1165                 return (ARCHIVE_WARN);
1166         }
1167         return (r);
1168 }
1169
1170 /*
1171  * Device entries have one of the following forms:
1172  * raw dev_t
1173  * format,major,minor[,subdevice]
1174  *
1175  * Just use major and minor, no translation etc is done
1176  * between formats.
1177  */
1178 static int
1179 parse_device(struct archive *a, struct archive_entry *entry, char *val)
1180 {
1181         char *comma1, *comma2;
1182
1183         comma1 = strchr(val, ',');
1184         if (comma1 == NULL) {
1185                 archive_entry_set_dev(entry, mtree_atol10(&val));
1186                 return (ARCHIVE_OK);
1187         }
1188         ++comma1;
1189         comma2 = strchr(comma1, ',');
1190         if (comma2 == NULL) {
1191                 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1192                     "Malformed device attribute");
1193                 return (ARCHIVE_WARN);
1194         }
1195         ++comma2;
1196         archive_entry_set_rdevmajor(entry, mtree_atol(&comma1));
1197         archive_entry_set_rdevminor(entry, mtree_atol(&comma2));
1198         return (ARCHIVE_OK);
1199 }
1200
1201 /*
1202  * Parse a single keyword and its value.
1203  */
1204 static int
1205 parse_keyword(struct archive_read *a, struct mtree *mtree,
1206     struct archive_entry *entry, struct mtree_option *opt, int *parsed_kws)
1207 {
1208         char *val, *key;
1209
1210         key = opt->value;
1211
1212         if (*key == '\0')
1213                 return (ARCHIVE_OK);
1214
1215         if (strcmp(key, "optional") == 0) {
1216                 *parsed_kws |= MTREE_HAS_OPTIONAL;
1217                 return (ARCHIVE_OK);
1218         }
1219         if (strcmp(key, "ignore") == 0) {
1220                 /*
1221                  * The mtree processing is not recursive, so
1222                  * recursion will only happen for explicitly listed
1223                  * entries.
1224                  */
1225                 return (ARCHIVE_OK);
1226         }
1227
1228         val = strchr(key, '=');
1229         if (val == NULL) {
1230                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1231                     "Malformed attribute \"%s\" (%d)", key, key[0]);
1232                 return (ARCHIVE_WARN);
1233         }
1234
1235         *val = '\0';
1236         ++val;
1237
1238         switch (key[0]) {
1239         case 'c':
1240                 if (strcmp(key, "content") == 0
1241                     || strcmp(key, "contents") == 0) {
1242                         parse_escapes(val, NULL);
1243                         archive_strcpy(&mtree->contents_name, val);
1244                         break;
1245                 }
1246                 if (strcmp(key, "cksum") == 0)
1247                         break;
1248         case 'd':
1249                 if (strcmp(key, "device") == 0) {
1250                         *parsed_kws |= MTREE_HAS_DEVICE;
1251                         return parse_device(&a->archive, entry, val);
1252                 }
1253         case 'f':
1254                 if (strcmp(key, "flags") == 0) {
1255                         *parsed_kws |= MTREE_HAS_FFLAGS;
1256                         archive_entry_copy_fflags_text(entry, val);
1257                         break;
1258                 }
1259         case 'g':
1260                 if (strcmp(key, "gid") == 0) {
1261                         *parsed_kws |= MTREE_HAS_GID;
1262                         archive_entry_set_gid(entry, mtree_atol10(&val));
1263                         break;
1264                 }
1265                 if (strcmp(key, "gname") == 0) {
1266                         *parsed_kws |= MTREE_HAS_GNAME;
1267                         archive_entry_copy_gname(entry, val);
1268                         break;
1269                 }
1270         case 'l':
1271                 if (strcmp(key, "link") == 0) {
1272                         archive_entry_copy_symlink(entry, val);
1273                         break;
1274                 }
1275         case 'm':
1276                 if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
1277                         break;
1278                 if (strcmp(key, "mode") == 0) {
1279                         if (val[0] >= '0' && val[0] <= '9') {
1280                                 *parsed_kws |= MTREE_HAS_PERM;
1281                                 archive_entry_set_perm(entry,
1282                                     mtree_atol8(&val));
1283                         } else {
1284                                 archive_set_error(&a->archive,
1285                                     ARCHIVE_ERRNO_FILE_FORMAT,
1286                                     "Symbolic mode \"%s\" unsupported", val);
1287                                 return ARCHIVE_WARN;
1288                         }
1289                         break;
1290                 }
1291         case 'n':
1292                 if (strcmp(key, "nlink") == 0) {
1293                         *parsed_kws |= MTREE_HAS_NLINK;
1294                         archive_entry_set_nlink(entry, mtree_atol10(&val));
1295                         break;
1296                 }
1297         case 'r':
1298                 if (strcmp(key, "rmd160") == 0 ||
1299                     strcmp(key, "rmd160digest") == 0)
1300                         break;
1301         case 's':
1302                 if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0)
1303                         break;
1304                 if (strcmp(key, "sha256") == 0 ||
1305                     strcmp(key, "sha256digest") == 0)
1306                         break;
1307                 if (strcmp(key, "sha384") == 0 ||
1308                     strcmp(key, "sha384digest") == 0)
1309                         break;
1310                 if (strcmp(key, "sha512") == 0 ||
1311                     strcmp(key, "sha512digest") == 0)
1312                         break;
1313                 if (strcmp(key, "size") == 0) {
1314                         archive_entry_set_size(entry, mtree_atol10(&val));
1315                         break;
1316                 }
1317         case 't':
1318                 if (strcmp(key, "tags") == 0) {
1319                         /*
1320                          * Comma delimited list of tags.
1321                          * Ignore the tags for now, but the interface
1322                          * should be extended to allow inclusion/exclusion.
1323                          */
1324                         break;
1325                 }
1326                 if (strcmp(key, "time") == 0) {
1327                         int64_t m;
1328                         int64_t my_time_t_max = get_time_t_max();
1329                         int64_t my_time_t_min = get_time_t_min();
1330                         long ns;
1331
1332                         *parsed_kws |= MTREE_HAS_MTIME;
1333                         m = mtree_atol10(&val);
1334                         /* Replicate an old mtree bug:
1335                          * 123456789.1 represents 123456789
1336                          * seconds and 1 nanosecond. */
1337                         if (*val == '.') {
1338                                 ++val;
1339                                 ns = (long)mtree_atol10(&val);
1340                         } else
1341                                 ns = 0;
1342                         if (m > my_time_t_max)
1343                                 m = my_time_t_max;
1344                         else if (m < my_time_t_min)
1345                                 m = my_time_t_min;
1346                         archive_entry_set_mtime(entry, (time_t)m, ns);
1347                         break;
1348                 }
1349                 if (strcmp(key, "type") == 0) {
1350                         switch (val[0]) {
1351                         case 'b':
1352                                 if (strcmp(val, "block") == 0) {
1353                                         archive_entry_set_filetype(entry, AE_IFBLK);
1354                                         break;
1355                                 }
1356                         case 'c':
1357                                 if (strcmp(val, "char") == 0) {
1358                                         archive_entry_set_filetype(entry, AE_IFCHR);
1359                                         break;
1360                                 }
1361                         case 'd':
1362                                 if (strcmp(val, "dir") == 0) {
1363                                         archive_entry_set_filetype(entry, AE_IFDIR);
1364                                         break;
1365                                 }
1366                         case 'f':
1367                                 if (strcmp(val, "fifo") == 0) {
1368                                         archive_entry_set_filetype(entry, AE_IFIFO);
1369                                         break;
1370                                 }
1371                                 if (strcmp(val, "file") == 0) {
1372                                         archive_entry_set_filetype(entry, AE_IFREG);
1373                                         break;
1374                                 }
1375                         case 'l':
1376                                 if (strcmp(val, "link") == 0) {
1377                                         archive_entry_set_filetype(entry, AE_IFLNK);
1378                                         break;
1379                                 }
1380                         default:
1381                                 archive_set_error(&a->archive,
1382                                     ARCHIVE_ERRNO_FILE_FORMAT,
1383                                     "Unrecognized file type \"%s\"; assuming \"file\"", val);
1384                                 archive_entry_set_filetype(entry, AE_IFREG);
1385                                 return (ARCHIVE_WARN);
1386                         }
1387                         *parsed_kws |= MTREE_HAS_TYPE;
1388                         break;
1389                 }
1390         case 'u':
1391                 if (strcmp(key, "uid") == 0) {
1392                         *parsed_kws |= MTREE_HAS_UID;
1393                         archive_entry_set_uid(entry, mtree_atol10(&val));
1394                         break;
1395                 }
1396                 if (strcmp(key, "uname") == 0) {
1397                         *parsed_kws |= MTREE_HAS_UNAME;
1398                         archive_entry_copy_uname(entry, val);
1399                         break;
1400                 }
1401         default:
1402                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1403                     "Unrecognized key %s=%s", key, val);
1404                 return (ARCHIVE_WARN);
1405         }
1406         return (ARCHIVE_OK);
1407 }
1408
1409 static int
1410 read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset)
1411 {
1412         size_t bytes_to_read;
1413         ssize_t bytes_read;
1414         struct mtree *mtree;
1415
1416         mtree = (struct mtree *)(a->format->data);
1417         if (mtree->fd < 0) {
1418                 *buff = NULL;
1419                 *offset = 0;
1420                 *size = 0;
1421                 return (ARCHIVE_EOF);
1422         }
1423         if (mtree->buff == NULL) {
1424                 mtree->buffsize = 64 * 1024;
1425                 mtree->buff = malloc(mtree->buffsize);
1426                 if (mtree->buff == NULL) {
1427                         archive_set_error(&a->archive, ENOMEM,
1428                             "Can't allocate memory");
1429                         return (ARCHIVE_FATAL);
1430                 }
1431         }
1432
1433         *buff = mtree->buff;
1434         *offset = mtree->offset;
1435         if ((int64_t)mtree->buffsize > mtree->cur_size - mtree->offset)
1436                 bytes_to_read = mtree->cur_size - mtree->offset;
1437         else
1438                 bytes_to_read = mtree->buffsize;
1439         bytes_read = read(mtree->fd, mtree->buff, bytes_to_read);
1440         if (bytes_read < 0) {
1441                 archive_set_error(&a->archive, errno, "Can't read");
1442                 return (ARCHIVE_WARN);
1443         }
1444         if (bytes_read == 0) {
1445                 *size = 0;
1446                 return (ARCHIVE_EOF);
1447         }
1448         mtree->offset += bytes_read;
1449         *size = bytes_read;
1450         return (ARCHIVE_OK);
1451 }
1452
1453 /* Skip does nothing except possibly close the contents file. */
1454 static int
1455 skip(struct archive_read *a)
1456 {
1457         struct mtree *mtree;
1458
1459         mtree = (struct mtree *)(a->format->data);
1460         if (mtree->fd >= 0) {
1461                 close(mtree->fd);
1462                 mtree->fd = -1;
1463         }
1464         return (ARCHIVE_OK);
1465 }
1466
1467 /*
1468  * Since parsing backslash sequences always makes strings shorter,
1469  * we can always do this conversion in-place.
1470  */
1471 static void
1472 parse_escapes(char *src, struct mtree_entry *mentry)
1473 {
1474         char *dest = src;
1475         char c;
1476
1477         if (mentry != NULL && strcmp(src, ".") == 0)
1478                 mentry->full = 1;
1479
1480         while (*src != '\0') {
1481                 c = *src++;
1482                 if (c == '/' && mentry != NULL)
1483                         mentry->full = 1;
1484                 if (c == '\\') {
1485                         switch (src[0]) {
1486                         case '0':
1487                                 if (src[1] < '0' || src[1] > '7') {
1488                                         c = 0;
1489                                         ++src;
1490                                         break;
1491                                 }
1492                                 /* FALLTHROUGH */
1493                         case '1':
1494                         case '2':
1495                         case '3':
1496                                 if (src[1] >= '0' && src[1] <= '7' &&
1497                                     src[2] >= '0' && src[2] <= '7') {
1498                                         c = (src[0] - '0') << 6;
1499                                         c |= (src[1] - '0') << 3;
1500                                         c |= (src[2] - '0');
1501                                         src += 3;
1502                                 }
1503                                 break;
1504                         case 'a':
1505                                 c = '\a';
1506                                 ++src;
1507                                 break;
1508                         case 'b':
1509                                 c = '\b';
1510                                 ++src;
1511                                 break;
1512                         case 'f':
1513                                 c = '\f';
1514                                 ++src;
1515                                 break;
1516                         case 'n':
1517                                 c = '\n';
1518                                 ++src;
1519                                 break;
1520                         case 'r':
1521                                 c = '\r';
1522                                 ++src;
1523                                 break;
1524                         case 's':
1525                                 c = ' ';
1526                                 ++src;
1527                                 break;
1528                         case 't':
1529                                 c = '\t';
1530                                 ++src;
1531                                 break;
1532                         case 'v':
1533                                 c = '\v';
1534                                 ++src;
1535                                 break;
1536                         }
1537                 }
1538                 *dest++ = c;
1539         }
1540         *dest = '\0';
1541 }
1542
1543 /*
1544  * Note that this implementation does not (and should not!) obey
1545  * locale settings; you cannot simply substitute strtol here, since
1546  * it does obey locale.
1547  */
1548 static int64_t
1549 mtree_atol8(char **p)
1550 {
1551         int64_t l, limit, last_digit_limit;
1552         int digit, base;
1553
1554         base = 8;
1555         limit = INT64_MAX / base;
1556         last_digit_limit = INT64_MAX % base;
1557
1558         l = 0;
1559         digit = **p - '0';
1560         while (digit >= 0 && digit < base) {
1561                 if (l>limit || (l == limit && digit > last_digit_limit)) {
1562                         l = INT64_MAX; /* Truncate on overflow. */
1563                         break;
1564                 }
1565                 l = (l * base) + digit;
1566                 digit = *++(*p) - '0';
1567         }
1568         return (l);
1569 }
1570
1571 /*
1572  * Note that this implementation does not (and should not!) obey
1573  * locale settings; you cannot simply substitute strtol here, since
1574  * it does obey locale.
1575  */
1576 static int64_t
1577 mtree_atol10(char **p)
1578 {
1579         int64_t l, limit, last_digit_limit;
1580         int base, digit, sign;
1581
1582         base = 10;
1583
1584         if (**p == '-') {
1585                 sign = -1;
1586                 limit = ((uint64_t)(INT64_MAX) + 1) / base;
1587                 last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
1588                 ++(*p);
1589         } else {
1590                 sign = 1;
1591                 limit = INT64_MAX / base;
1592                 last_digit_limit = INT64_MAX % base;
1593         }
1594
1595         l = 0;
1596         digit = **p - '0';
1597         while (digit >= 0 && digit < base) {
1598                 if (l > limit || (l == limit && digit > last_digit_limit))
1599                         return (sign < 0) ? INT64_MIN : INT64_MAX;
1600                 l = (l * base) + digit;
1601                 digit = *++(*p) - '0';
1602         }
1603         return (sign < 0) ? -l : l;
1604 }
1605
1606 /* Parse a hex digit. */
1607 static int
1608 parsehex(char c)
1609 {
1610         if (c >= '0' && c <= '9')
1611                 return c - '0';
1612         else if (c >= 'a' && c <= 'f')
1613                 return c - 'a';
1614         else if (c >= 'A' && c <= 'F')
1615                 return c - 'A';
1616         else
1617                 return -1;
1618 }
1619
1620 /*
1621  * Note that this implementation does not (and should not!) obey
1622  * locale settings; you cannot simply substitute strtol here, since
1623  * it does obey locale.
1624  */
1625 static int64_t
1626 mtree_atol16(char **p)
1627 {
1628         int64_t l, limit, last_digit_limit;
1629         int base, digit, sign;
1630
1631         base = 16;
1632
1633         if (**p == '-') {
1634                 sign = -1;
1635                 limit = ((uint64_t)(INT64_MAX) + 1) / base;
1636                 last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
1637                 ++(*p);
1638         } else {
1639                 sign = 1;
1640                 limit = INT64_MAX / base;
1641                 last_digit_limit = INT64_MAX % base;
1642         }
1643
1644         l = 0;
1645         digit = parsehex(**p);
1646         while (digit >= 0 && digit < base) {
1647                 if (l > limit || (l == limit && digit > last_digit_limit))
1648                         return (sign < 0) ? INT64_MIN : INT64_MAX;
1649                 l = (l * base) + digit;
1650                 digit = parsehex(*++(*p));
1651         }
1652         return (sign < 0) ? -l : l;
1653 }
1654
1655 static int64_t
1656 mtree_atol(char **p)
1657 {
1658         if (**p != '0')
1659                 return mtree_atol10(p);
1660         if ((*p)[1] == 'x' || (*p)[1] == 'X') {
1661                 *p += 2;
1662                 return mtree_atol16(p);
1663         }
1664         return mtree_atol8(p);
1665 }
1666
1667 /*
1668  * Returns length of line (including trailing newline)
1669  * or negative on error.  'start' argument is updated to
1670  * point to first character of line.
1671  */
1672 static ssize_t
1673 readline(struct archive_read *a, struct mtree *mtree, char **start, ssize_t limit)
1674 {
1675         ssize_t bytes_read;
1676         ssize_t total_size = 0;
1677         ssize_t find_off = 0;
1678         const void *t;
1679         const char *s;
1680         void *p;
1681         char *u;
1682
1683         /* Accumulate line in a line buffer. */
1684         for (;;) {
1685                 /* Read some more. */
1686                 t = __archive_read_ahead(a, 1, &bytes_read);
1687                 if (t == NULL)
1688                         return (0);
1689                 if (bytes_read < 0)
1690                         return (ARCHIVE_FATAL);
1691                 s = t;  /* Start of line? */
1692                 p = memchr(t, '\n', bytes_read);
1693                 /* If we found '\n', trim the read. */
1694                 if (p != NULL) {
1695                         bytes_read = 1 + ((const char *)p) - s;
1696                 }
1697                 if (total_size + bytes_read + 1 > limit) {
1698                         archive_set_error(&a->archive,
1699                             ARCHIVE_ERRNO_FILE_FORMAT,
1700                             "Line too long");
1701                         return (ARCHIVE_FATAL);
1702                 }
1703                 if (archive_string_ensure(&mtree->line,
1704                         total_size + bytes_read + 1) == NULL) {
1705                         archive_set_error(&a->archive, ENOMEM,
1706                             "Can't allocate working buffer");
1707                         return (ARCHIVE_FATAL);
1708                 }
1709                 memcpy(mtree->line.s + total_size, t, bytes_read);
1710                 __archive_read_consume(a, bytes_read);
1711                 total_size += bytes_read;
1712                 /* Null terminate. */
1713                 mtree->line.s[total_size] = '\0';
1714                 /* If we found an unescaped '\n', clean up and return. */
1715                 for (u = mtree->line.s + find_off; *u; ++u) {
1716                         if (u[0] == '\n') {
1717                                 *start = mtree->line.s;
1718                                 return total_size;
1719                         }
1720                         if (u[0] == '#') {
1721                                 if (p == NULL)
1722                                         break;
1723                                 *start = mtree->line.s;
1724                                 return total_size;
1725                         }
1726                         if (u[0] != '\\')
1727                                 continue;
1728                         if (u[1] == '\\') {
1729                                 ++u;
1730                                 continue;
1731                         }
1732                         if (u[1] == '\n') {
1733                                 memmove(u, u + 1,
1734                                     total_size - (u - mtree->line.s) + 1);
1735                                 --total_size;
1736                                 ++u;
1737                                 break;
1738                         }
1739                         if (u[1] == '\0')
1740                                 break;
1741                 }
1742                 find_off = u - mtree->line.s;
1743         }
1744 }