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