]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/makefs/mtree.c
Merge ^/head r319801 through r320041.
[FreeBSD/FreeBSD.git] / usr.sbin / makefs / mtree.c
1 /*-
2  * Copyright (c) 2011 Marcel Moolenaar
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/sbuf.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <assert.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <grp.h>
38 #include <inttypes.h>
39 #include <pwd.h>
40 #include <stdarg.h>
41 #include <stdbool.h>
42 #include <stddef.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <strings.h>
47 #include <time.h>
48 #include <unistd.h>
49 #include <util.h>
50
51 #include "makefs.h"
52
53 #ifndef ENOATTR
54 #define ENOATTR ENOMSG
55 #endif
56
57 #define IS_DOT(nm)      ((nm)[0] == '.' && (nm)[1] == '\0')
58 #define IS_DOTDOT(nm)   ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
59
60 struct mtree_fileinfo {
61         SLIST_ENTRY(mtree_fileinfo) next;
62         FILE *fp;
63         const char *name;
64         u_int line;
65 };
66
67 /* Global state used while parsing. */
68 static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
69     SLIST_HEAD_INITIALIZER(mtree_fileinfo);
70 static fsnode *mtree_root;
71 static fsnode *mtree_current;
72 static fsnode mtree_global;
73 static fsinode mtree_global_inode;
74 static u_int errors, warnings;
75
76 static void mtree_error(const char *, ...) __printflike(1, 2);
77 static void mtree_warning(const char *, ...) __printflike(1, 2);
78
79 static int
80 mtree_file_push(const char *name, FILE *fp)
81 {
82         struct mtree_fileinfo *fi;
83
84         fi = emalloc(sizeof(*fi));
85         if (strcmp(name, "-") == 0)
86                 fi->name = estrdup("(stdin)");
87         else
88                 fi->name = estrdup(name);
89         if (fi->name == NULL) {
90                 free(fi);
91                 return (ENOMEM);
92         }
93
94         fi->fp = fp;
95         fi->line = 0;
96
97         SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
98         return (0);
99 }
100
101 static void
102 mtree_print(const char *msgtype, const char *fmt, va_list ap)
103 {
104         struct mtree_fileinfo *fi;
105
106         if (msgtype != NULL) {
107                 fi = SLIST_FIRST(&mtree_fileinfo);
108                 if (fi != NULL)
109                         fprintf(stderr, "%s:%u: ", fi->name, fi->line);
110                 fprintf(stderr, "%s: ", msgtype);
111         }
112         vfprintf(stderr, fmt, ap);
113 }
114
115 static void
116 mtree_error(const char *fmt, ...)
117 {
118         va_list ap;
119
120         va_start(ap, fmt);
121         mtree_print("error", fmt, ap);
122         va_end(ap);
123
124         errors++;
125         fputc('\n', stderr);
126 }
127
128 static void
129 mtree_warning(const char *fmt, ...)
130 {
131         va_list ap;
132
133         va_start(ap, fmt);
134         mtree_print("warning", fmt, ap);
135         va_end(ap);
136
137         warnings++;
138         fputc('\n', stderr);
139 }
140
141 #ifndef MAKEFS_MAX_TREE_DEPTH
142 # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
143 #endif
144
145 /* construct path to node->name */
146 static char *
147 mtree_file_path(fsnode *node)
148 {
149         fsnode *pnode;
150         struct sbuf *sb;
151         char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
152         int depth;
153
154         depth = 0;
155         rp[depth] = node->name;
156         for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
157              pnode = pnode->parent) {
158                 if (strcmp(pnode->name, ".") == 0)
159                         break;
160                 rp[++depth] = pnode->name;
161         }
162         
163         sb = sbuf_new_auto();
164         if (sb == NULL) {
165                 errno = ENOMEM;
166                 return (NULL);
167         }
168         while (depth > 0) {
169                 sbuf_cat(sb, rp[depth--]);
170                 sbuf_putc(sb, '/');
171         }
172         sbuf_cat(sb, rp[depth]);
173         sbuf_finish(sb);
174         res = estrdup(sbuf_data(sb));
175         sbuf_delete(sb);
176         if (res == NULL)
177                 errno = ENOMEM;
178         return res;
179
180 }
181
182 /* mtree_resolve() sets errno to indicate why NULL was returned. */
183 static char *
184 mtree_resolve(const char *spec, int *istemp)
185 {
186         struct sbuf *sb;
187         char *res, *var = NULL;
188         const char *base, *p, *v;
189         size_t len;
190         int c, error, quoted, subst;
191
192         len = strlen(spec);
193         if (len == 0) {
194                 errno = EINVAL;
195                 return (NULL);
196         }
197
198         c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
199         *istemp = (c == '`') ? 1 : 0;
200         subst = (c == '`' || c == '"') ? 1 : 0;
201         quoted = (subst || c == '\'') ? 1 : 0;
202
203         if (!subst) {
204                 res = estrdup(spec + quoted);
205                 if (quoted)
206                         res[len - 2] = '\0';
207                 return (res);
208         }
209
210         sb = sbuf_new_auto();
211         if (sb == NULL) {
212                 errno = ENOMEM;
213                 return (NULL);
214         }
215
216         base = spec + 1;
217         len -= 2;
218         error = 0;
219         while (len > 0) {
220                 p = strchr(base, '$');
221                 if (p == NULL) {
222                         sbuf_bcat(sb, base, len);
223                         base += len;
224                         len = 0;
225                         continue;
226                 }
227                 /* The following is safe. spec always starts with a quote. */
228                 if (p[-1] == '\\')
229                         p--;
230                 if (base != p) {
231                         sbuf_bcat(sb, base, p - base);
232                         len -= p - base;
233                         base = p;
234                 }
235                 if (*p == '\\') {
236                         sbuf_putc(sb, '$');
237                         base += 2;
238                         len -= 2;
239                         continue;
240                 }
241                 /* Skip the '$'. */
242                 base++;
243                 len--;
244                 /* Handle ${X} vs $X. */
245                 v = base;
246                 if (*base == '{') {
247                         p = strchr(v, '}');
248                         if (p == NULL)
249                                 p = v;
250                 } else
251                         p = v;
252                 len -= (p + 1) - base;
253                 base = p + 1;
254
255                 if (v == p) {
256                         sbuf_putc(sb, *v);
257                         continue;
258                 }
259
260                 error = ENOMEM;
261                 var = ecalloc(p - v, 1);
262                 memcpy(var, v + 1, p - v - 1);
263                 if (strcmp(var, ".CURDIR") == 0) {
264                         res = getcwd(NULL, 0);
265                         if (res == NULL)
266                                 break;
267                 } else if (strcmp(var, ".PROG") == 0) {
268                         res = estrdup(getprogname());
269                 } else {
270                         v = getenv(var);
271                         if (v != NULL) {
272                                 res = estrdup(v);
273                         } else
274                                 res = NULL;
275                 }
276                 error = 0;
277
278                 if (res != NULL) {
279                         sbuf_cat(sb, res);
280                         free(res);
281                 }
282                 free(var);
283                 var = NULL;
284         }
285
286         free(var);
287         sbuf_finish(sb);
288         res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
289         sbuf_delete(sb);
290         if (res == NULL)
291                 errno = ENOMEM;
292         return (res);
293 }
294
295 static int
296 skip_over(FILE *fp, const char *cs)
297 {
298         int c;
299
300         c = getc(fp);
301         while (c != EOF && strchr(cs, c) != NULL)
302                 c = getc(fp);
303         if (c != EOF) {
304                 ungetc(c, fp);
305                 return (0);
306         }
307         return (ferror(fp) ? errno : -1);
308 }
309
310 static int
311 skip_to(FILE *fp, const char *cs)
312 {
313         int c;
314
315         c = getc(fp);
316         while (c != EOF && strchr(cs, c) == NULL)
317                 c = getc(fp);
318         if (c != EOF) {
319                 ungetc(c, fp);
320                 return (0);
321         }
322         return (ferror(fp) ? errno : -1);
323 }
324
325 static int
326 read_word(FILE *fp, char *buf, size_t bufsz)
327 {
328         struct mtree_fileinfo *fi;
329         size_t idx, qidx;
330         int c, done, error, esc, qlvl;
331
332         if (bufsz == 0)
333                 return (EINVAL);
334
335         done = 0;
336         esc = 0;
337         idx = 0;
338         qidx = -1;
339         qlvl = 0;
340         do {
341                 c = getc(fp);
342                 switch (c) {
343                 case EOF:
344                         buf[idx] = '\0';
345                         error = ferror(fp) ? errno : -1;
346                         if (error == -1)
347                                 mtree_error("unexpected end of file");
348                         return (error);
349                 case '#':               /* comment -- skip to end of line. */
350                         if (!esc) {
351                                 error = skip_to(fp, "\n");
352                                 if (!error)
353                                         continue;
354                         }
355                         break;
356                 case '\\':
357                         esc++;
358                         if (esc == 1)
359                                 continue;
360                         break;
361                 case '`':
362                 case '\'':
363                 case '"':
364                         if (esc)
365                                 break;
366                         if (qlvl == 0) {
367                                 qlvl++;
368                                 qidx = idx;
369                         } else if (c == buf[qidx]) {
370                                 qlvl--;
371                                 if (qlvl > 0) {
372                                         do {
373                                                 qidx--;
374                                         } while (buf[qidx] != '`' &&
375                                             buf[qidx] != '\'' &&
376                                             buf[qidx] != '"');
377                                 } else
378                                         qidx = -1;
379                         } else {
380                                 qlvl++;
381                                 qidx = idx;
382                         }
383                         break;
384                 case ' ':
385                 case '\t':
386                 case '\n':
387                         if (!esc && qlvl == 0) {
388                                 ungetc(c, fp);
389                                 c = '\0';
390                                 done = 1;
391                                 break;
392                         }
393                         if (c == '\n') {
394                                 /*
395                                  * We going to eat the newline ourselves.
396                                  */
397                                 if (qlvl > 0)
398                                         mtree_warning("quoted word straddles "
399                                             "onto next line.");
400                                 fi = SLIST_FIRST(&mtree_fileinfo);
401                                 fi->line++;
402                         }
403                         break;
404                 case 'a':
405                         if (esc)
406                                 c = '\a';
407                         break;
408                 case 'b':
409                         if (esc)
410                                 c = '\b';
411                         break;
412                 case 'f':
413                         if (esc)
414                                 c = '\f';
415                         break;
416                 case 'n':
417                         if (esc)
418                                 c = '\n';
419                         break;
420                 case 'r':
421                         if (esc)
422                                 c = '\r';
423                         break;
424                 case 't':
425                         if (esc)
426                                 c = '\t';
427                         break;
428                 case 'v':
429                         if (esc)
430                                 c = '\v';
431                         break;
432                 }
433                 buf[idx++] = c;
434                 esc = 0;
435         } while (idx < bufsz && !done);
436
437         if (idx >= bufsz) {
438                 mtree_error("word too long to fit buffer (max %zu characters)",
439                     bufsz);
440                 skip_to(fp, " \t\n");
441         }
442         return (0);
443 }
444
445 static fsnode *
446 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
447 {
448         fsnode *n;
449
450         n = ecalloc(1, sizeof(*n));
451         n->name = estrdup(name);
452         n->type = (type == 0) ? global->type : type;
453         n->parent = parent;
454
455         n->inode = ecalloc(1, sizeof(*n->inode));
456
457         /* Assign global options/defaults. */
458         memcpy(n->inode, global->inode, sizeof(*n->inode));
459         n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
460
461         if (n->type == S_IFLNK)
462                 n->symlink = global->symlink;
463         else if (n->type == S_IFREG)
464                 n->contents = global->contents;
465
466         return (n);
467 }
468
469 static void
470 destroy_node(fsnode *n)
471 {
472
473         assert(n != NULL);
474         assert(n->name != NULL);
475         assert(n->inode != NULL);
476
477         free(n->inode);
478         free(n->name);
479         free(n);
480 }
481
482 static int
483 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
484     intmax_t max)
485 {
486         char *end;
487         intmax_t val;
488
489         val = strtoimax(tok, &end, base);
490         if (end == tok || end[0] != '\0')
491                 return (EINVAL);
492         if (val < min || val > max)
493                 return (EDOM);
494         *res = val;
495         return (0);
496 }
497
498 static int
499 read_mtree_keywords(FILE *fp, fsnode *node)
500 {
501         char keyword[PATH_MAX];
502         char *name, *p, *value;
503         gid_t gid;
504         uid_t uid;
505         struct stat *st, sb;
506         intmax_t num;
507         u_long flset, flclr;
508         int error, istemp;
509         uint32_t type;
510
511         st = &node->inode->st;
512         do {
513                 error = skip_over(fp, " \t");
514                 if (error)
515                         break;
516
517                 error = read_word(fp, keyword, sizeof(keyword));
518                 if (error)
519                         break;
520
521                 if (keyword[0] == '\0')
522                         break;
523
524                 value = strchr(keyword, '=');
525                 if (value != NULL)
526                         *value++ = '\0';
527
528                 /*
529                  * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
530                  * certain conditions:
531                  *   EINVAL -   Value provided for a keyword that does
532                  *              not take a value. The value is ignored.
533                  *   ENOATTR -  Value missing for a keyword that needs
534                  *              a value. The keyword is ignored.
535                  *   ENOSYS -   Unsupported keyword encountered. The
536                  *              keyword is ignored.
537                  *   ENXIO -    Value provided for a keyword that does
538                  *              not take a value. The value is ignored.
539                  */
540                 switch (keyword[0]) {
541                 case 'c':
542                         if (strcmp(keyword, "contents") == 0) {
543                                 if (value == NULL) {
544                                         error = ENOATTR;
545                                         break;
546                                 }
547                                 node->contents = estrdup(value);
548                         } else
549                                 error = ENOSYS;
550                         break;
551                 case 'f':
552                         if (strcmp(keyword, "flags") == 0) {
553                                 if (value == NULL) {
554                                         error = ENOATTR;
555                                         break;
556                                 }
557                                 flset = flclr = 0;
558                                 if (!strtofflags(&value, &flset, &flclr)) {
559                                         st->st_flags &= ~flclr;
560                                         st->st_flags |= flset;
561                                 } else
562                                         error = errno;
563                         } else
564                                 error = ENOSYS;
565                         break;
566                 case 'g':
567                         if (strcmp(keyword, "gid") == 0) {
568                                 if (value == NULL) {
569                                         error = ENOATTR;
570                                         break;
571                                 }
572                                 error = read_number(value, 10, &num,
573                                     0, UINT_MAX);
574                                 if (!error)
575                                         st->st_gid = num;
576                         } else if (strcmp(keyword, "gname") == 0) {
577                                 if (value == NULL) {
578                                         error = ENOATTR;
579                                         break;
580                                 }
581                                 if (gid_from_group(value, &gid) == 0)
582                                         st->st_gid = gid;
583                                 else
584                                         error = EINVAL;
585                         } else
586                                 error = ENOSYS;
587                         break;
588                 case 'l':
589                         if (strcmp(keyword, "link") == 0) {
590                                 if (value == NULL) {
591                                         error = ENOATTR;
592                                         break;
593                                 }
594                                 node->symlink = estrdup(value);
595                         } else
596                                 error = ENOSYS;
597                         break;
598                 case 'm':
599                         if (strcmp(keyword, "mode") == 0) {
600                                 if (value == NULL) {
601                                         error = ENOATTR;
602                                         break;
603                                 }
604                                 if (value[0] >= '0' && value[0] <= '9') {
605                                         error = read_number(value, 8, &num,
606                                             0, 07777);
607                                         if (!error) {
608                                                 st->st_mode &= S_IFMT;
609                                                 st->st_mode |= num;
610                                         }
611                                 } else {
612                                         /* Symbolic mode not supported. */
613                                         error = EINVAL;
614                                         break;
615                                 }
616                         } else
617                                 error = ENOSYS;
618                         break;
619                 case 'o':
620                         if (strcmp(keyword, "optional") == 0) {
621                                 if (value != NULL)
622                                         error = ENXIO;
623                                 node->flags |= FSNODE_F_OPTIONAL;
624                         } else
625                                 error = ENOSYS;
626                         break;
627                 case 's':
628                         if (strcmp(keyword, "size") == 0) {
629                                 if (value == NULL) {
630                                         error = ENOATTR;
631                                         break;
632                                 }
633                                 error = read_number(value, 10, &num,
634                                     0, INTMAX_MAX);
635                                 if (!error)
636                                         st->st_size = num;
637                         } else
638                                 error = ENOSYS;
639                         break;
640                 case 't':
641                         if (strcmp(keyword, "time") == 0) {
642                                 if (value == NULL) {
643                                         error = ENOATTR;
644                                         break;
645                                 }
646                                 p = strchr(value, '.');
647                                 if (p != NULL)
648                                         *p++ = '\0';
649                                 error = read_number(value, 10, &num, 0,
650                                     INTMAX_MAX);
651                                 if (error)
652                                         break;
653                                 st->st_atime = num;
654                                 st->st_ctime = num;
655                                 st->st_mtime = num;
656                                 if (p == NULL)
657                                         break;
658                                 error = read_number(p, 10, &num, 0,
659                                     INTMAX_MAX);
660                                 if (error)
661                                         break;
662                                 if (num != 0)
663                                         error = EINVAL;
664                         } else if (strcmp(keyword, "type") == 0) {
665                                 if (value == NULL) {
666                                         error = ENOATTR;
667                                         break;
668                                 }
669                                 if (strcmp(value, "dir") == 0)
670                                         node->type = S_IFDIR;
671                                 else if (strcmp(value, "file") == 0)
672                                         node->type = S_IFREG;
673                                 else if (strcmp(value, "link") == 0)
674                                         node->type = S_IFLNK;
675                                 else
676                                         error = EINVAL;
677                         } else
678                                 error = ENOSYS;
679                         break;
680                 case 'u':
681                         if (strcmp(keyword, "uid") == 0) {
682                                 if (value == NULL) {
683                                         error = ENOATTR;
684                                         break;
685                                 }
686                                 error = read_number(value, 10, &num,
687                                     0, UINT_MAX);
688                                 if (!error)
689                                         st->st_uid = num;
690                         } else if (strcmp(keyword, "uname") == 0) {
691                                 if (value == NULL) {
692                                         error = ENOATTR;
693                                         break;
694                                 }
695                                 if (uid_from_user(value, &uid) == 0)
696                                         st->st_uid = uid;
697                                 else
698                                         error = EINVAL;
699                         } else
700                                 error = ENOSYS;
701                         break;
702                 default:
703                         error = ENOSYS;
704                         break;
705                 }
706
707                 switch (error) {
708                 case EINVAL:
709                         mtree_error("%s: invalid value '%s'", keyword, value);
710                         break;
711                 case ENOATTR:
712                         mtree_error("%s: keyword needs a value", keyword);
713                         break;
714                 case ENOSYS:
715                         mtree_warning("%s: unsupported keyword", keyword);
716                         break;
717                 case ENXIO:
718                         mtree_error("%s: keyword does not take a value",
719                             keyword);
720                         break;
721                 }
722         } while (1);
723
724         if (error)
725                 return (error);
726
727         st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
728
729         /* Nothing more to do for the global defaults. */
730         if (node->name == NULL)
731                 return (0);
732
733         /*
734          * Be intelligent about the file type.
735          */
736         if (node->contents != NULL) {
737                 if (node->symlink != NULL) {
738                         mtree_error("%s: both link and contents keywords "
739                             "defined", node->name);
740                         return (0);
741                 }
742                 type = S_IFREG;
743         } else if (node->type != 0) {
744                 type = node->type;
745                 if (type == S_IFREG) {
746                         /* the named path is the default contents */
747                         node->contents = mtree_file_path(node);
748                 }
749         } else
750                 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
751
752         if (node->type == 0)
753                 node->type = type;
754
755         if (node->type != type) {
756                 mtree_error("%s: file type and defined keywords to not match",
757                     node->name);
758                 return (0);
759         }
760
761         st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
762
763         if (node->contents == NULL)
764                 return (0);
765
766         name = mtree_resolve(node->contents, &istemp);
767         if (name == NULL)
768                 return (errno);
769
770         if (stat(name, &sb) != 0) {
771                 mtree_error("%s: contents file '%s' not found", node->name,
772                     name);
773                 free(name);
774                 return (0);
775         }
776
777         /*
778          * Check for hardlinks. If the contents key is used, then the check
779          * will only trigger if the contents file is a link even if it is used
780          * by more than one file
781          */
782         if (sb.st_nlink > 1) {
783                 fsinode *curino;
784
785                 st->st_ino = sb.st_ino;
786                 st->st_dev = sb.st_dev;
787                 curino = link_check(node->inode);
788                 if (curino != NULL) {
789                         free(node->inode);
790                         node->inode = curino;
791                         node->inode->nlink++;
792                 }
793         }
794
795         free(node->contents);
796         node->contents = name;
797         st->st_size = sb.st_size;
798         return (0);
799 }
800
801 static int
802 read_mtree_command(FILE *fp)
803 {
804         char cmd[10];
805         int error;
806
807         error = read_word(fp, cmd, sizeof(cmd));
808         if (error)
809                 goto out;
810
811         error = read_mtree_keywords(fp, &mtree_global);
812
813  out:
814         skip_to(fp, "\n");
815         (void)getc(fp);
816         return (error);
817 }
818
819 static int
820 read_mtree_spec1(FILE *fp, bool def, const char *name)
821 {
822         fsnode *last, *node, *parent;
823         u_int type;
824         int error;
825
826         assert(name[0] != '\0');
827
828         /*
829          * Treat '..' specially, because it only changes our current
830          * directory. We don't create a node for it. We simply ignore
831          * any keywords that may appear on the line as well.
832          * Going up a directory is a little non-obvious. A directory
833          * node has a corresponding '.' child. The parent of '.' is
834          * not the '.' node of the parent directory, but the directory
835          * node within the parent to which the child relates. However,
836          * going up a directory means we need to find the '.' node to
837          * which the directoy node is linked.  This we can do via the
838          * first * pointer, because '.' is always the first entry in a
839          * directory.
840          */
841         if (IS_DOTDOT(name)) {
842                 /* This deals with NULL pointers as well. */
843                 if (mtree_current == mtree_root) {
844                         mtree_warning("ignoring .. in root directory");
845                         return (0);
846                 }
847
848                 node = mtree_current;
849
850                 assert(node != NULL);
851                 assert(IS_DOT(node->name));
852                 assert(node->first == node);
853
854                 /* Get the corresponding directory node in the parent. */
855                 node = mtree_current->parent;
856
857                 assert(node != NULL);
858                 assert(!IS_DOT(node->name));
859
860                 node = node->first;
861
862                 assert(node != NULL);
863                 assert(IS_DOT(node->name));
864                 assert(node->first == node);
865
866                 mtree_current = node;
867                 return (0);
868         }
869
870         /*
871          * If we don't have a current directory and the first specification
872          * (either implicit or defined) is not '.', then we need to create
873          * a '.' node first (using a recursive call).
874          */
875         if (!IS_DOT(name) && mtree_current == NULL) {
876                 error = read_mtree_spec1(fp, false, ".");
877                 if (error)
878                         return (error);
879         }
880
881         /*
882          * Lookup the name in the current directory (if we have a current
883          * directory) to make sure we do not create multiple nodes for the
884          * same component. For non-definitions, if we find a node with the
885          * same name, simply change the current directory. For definitions
886          * more happens.
887          */
888         last = NULL;
889         node = mtree_current;
890         while (node != NULL) {
891                 assert(node->first == mtree_current);
892
893                 if (strcmp(name, node->name) == 0) {
894                         if (def == true) {
895                                 if (!dupsok)
896                                         mtree_error(
897                                             "duplicate definition of %s",
898                                             name);
899                                 else
900                                         mtree_warning(
901                                             "duplicate definition of %s",
902                                             name);
903                                 return (0);
904                         }
905
906                         if (node->type != S_IFDIR) {
907                                 mtree_error("%s is not a directory", name);
908                                 return (0);
909                         }
910
911                         assert(!IS_DOT(name));
912
913                         node = node->child;
914
915                         assert(node != NULL);
916                         assert(IS_DOT(node->name));
917
918                         mtree_current = node;
919                         return (0);
920                 }
921
922                 last = node;
923                 node = last->next;
924         }
925
926         parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
927         type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
928         node = create_node(name, type, parent, &mtree_global);
929         if (node == NULL)
930                 return (ENOMEM);
931
932         if (def == true) {
933                 error = read_mtree_keywords(fp, node);
934                 if (error) {
935                         destroy_node(node);
936                         return (error);
937                 }
938         }
939
940         node->first = (mtree_current != NULL) ? mtree_current : node;
941
942         if (last != NULL)
943                 last->next = node;
944
945         if (node->type != S_IFDIR)
946                 return (0);
947
948         if (!IS_DOT(node->name)) {
949                 parent = node;
950                 node = create_node(".", S_IFDIR, parent, parent);
951                 if (node == NULL) {
952                         last->next = NULL;
953                         destroy_node(parent);
954                         return (ENOMEM);
955                 }
956                 parent->child = node;
957                 node->first = node;
958         }
959
960         assert(node != NULL);
961         assert(IS_DOT(node->name));
962         assert(node->first == node);
963
964         mtree_current = node;
965         if (mtree_root == NULL)
966                 mtree_root = node;
967
968         return (0);
969 }
970
971 static int
972 read_mtree_spec(FILE *fp)
973 {
974         char pathspec[PATH_MAX];
975         char *cp;
976         int error;
977
978         error = read_word(fp, pathspec, sizeof(pathspec));
979         if (error)
980                 goto out;
981
982         cp = strchr(pathspec, '/');
983         if (cp != NULL) {
984                 /* Absolute pathname */
985                 mtree_current = mtree_root;
986
987                 do {
988                         *cp++ = '\0';
989
990                         /* Disallow '..' as a component. */
991                         if (IS_DOTDOT(pathspec)) {
992                                 mtree_error("absolute path cannot contain "
993                                     ".. component");
994                                 goto out;
995                         }
996
997                         /* Ignore multiple adjacent slashes and '.'. */
998                         if (pathspec[0] != '\0' && !IS_DOT(pathspec))
999                                 error = read_mtree_spec1(fp, false, pathspec);
1000                         memmove(pathspec, cp, strlen(cp) + 1);
1001                         cp = strchr(pathspec, '/');
1002                 } while (!error && cp != NULL);
1003
1004                 /* Disallow '.' and '..' as the last component. */
1005                 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1006                         mtree_error("absolute path cannot contain . or .. "
1007                             "components");
1008                         goto out;
1009                 }
1010         }
1011
1012         /* Ignore absolute specfications that end with a slash. */
1013         if (!error && pathspec[0] != '\0')
1014                 error = read_mtree_spec1(fp, true, pathspec);
1015
1016  out:
1017         skip_to(fp, "\n");
1018         (void)getc(fp);
1019         return (error);
1020 }
1021
1022 fsnode *
1023 read_mtree(const char *fname, fsnode *node)
1024 {
1025         struct mtree_fileinfo *fi;
1026         FILE *fp;
1027         int c, error;
1028
1029         /* We do not yet support nesting... */
1030         assert(node == NULL);
1031
1032         if (strcmp(fname, "-") == 0)
1033                 fp = stdin;
1034         else {
1035                 fp = fopen(fname, "r");
1036                 if (fp == NULL)
1037                         err(1, "Can't open `%s'", fname);
1038         }
1039
1040         error = mtree_file_push(fname, fp);
1041         if (error)
1042                 goto out;
1043
1044         memset(&mtree_global, 0, sizeof(mtree_global));
1045         memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1046         mtree_global.inode = &mtree_global_inode;
1047         mtree_global_inode.nlink = 1;
1048         mtree_global_inode.st.st_nlink = 1;
1049         mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1050             mtree_global_inode.st.st_mtime = time(NULL);
1051         errors = warnings = 0;
1052
1053         setgroupent(1);
1054         setpassent(1);
1055
1056         mtree_root = node;
1057         mtree_current = node;
1058         do {
1059                 /* Start of a new line... */
1060                 fi = SLIST_FIRST(&mtree_fileinfo);
1061                 fi->line++;
1062
1063                 error = skip_over(fp, " \t");
1064                 if (error)
1065                         break;
1066
1067                 c = getc(fp);
1068                 if (c == EOF) {
1069                         error = ferror(fp) ? errno : -1;
1070                         break;
1071                 }
1072
1073                 switch (c) {
1074                 case '\n':              /* empty line */
1075                         error = 0;
1076                         break;
1077                 case '#':               /* comment -- skip to end of line. */
1078                         error = skip_to(fp, "\n");
1079                         if (!error)
1080                                 (void)getc(fp);
1081                         break;
1082                 case '/':               /* special commands */
1083                         error = read_mtree_command(fp);
1084                         break;
1085                 default:                /* specification */
1086                         ungetc(c, fp);
1087                         error = read_mtree_spec(fp);
1088                         break;
1089                 }
1090         } while (!error);
1091
1092         endpwent();
1093         endgrent();
1094
1095         if (error <= 0 && (errors || warnings)) {
1096                 warnx("%u error(s) and %u warning(s) in mtree manifest",
1097                     errors, warnings);
1098                 if (errors)
1099                         exit(1);
1100         }
1101
1102  out:
1103         if (error > 0)
1104                 errc(1, error, "Error reading mtree file");
1105
1106         if (fp != stdin)
1107                 fclose(fp);
1108
1109         if (mtree_root != NULL)
1110                 return (mtree_root);
1111
1112         /* Handle empty specifications. */
1113         node = create_node(".", S_IFDIR, NULL, &mtree_global);
1114         node->first = node;
1115         return (node);
1116 }