xref: /netbsd-src/usr.sbin/makefs/walk.c (revision ccd9df534e375a4366c5b55f23782053c7a98d82)
1 /*	$NetBSD: walk.c,v 1.40 2024/05/08 15:57:56 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2001 Wasabi Systems, Inc.
5  * All rights reserved.
6  *
7  * Written by Luke Mewburn for Wasabi Systems, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed for the NetBSD Project by
20  *      Wasabi Systems, Inc.
21  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
22  *    or promote products derived from this software without specific prior
23  *    written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #if HAVE_NBTOOL_CONFIG_H
39 #include "nbtool_config.h"
40 #endif
41 
42 #include <sys/cdefs.h>
43 #if defined(__RCSID) && !defined(__lint)
44 __RCSID("$NetBSD: walk.c,v 1.40 2024/05/08 15:57:56 christos Exp $");
45 #endif	/* !__lint */
46 
47 #include <sys/param.h>
48 #include <sys/stat.h>
49 
50 #include <assert.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdio.h>
54 #include <dirent.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <util.h>
59 
60 #include "makefs.h"
61 #include "mtree.h"
62 
63 static	void	 apply_specdir(const char *, NODE *, fsnode *, int);
64 static	void	 apply_specentry(const char *, NODE *, fsnode *);
65 static	fsnode	*create_fsnode(const char *, const char *, const char *,
66 			       struct stat *);
67 static	fsinode	*link_check(fsinode *);
68 static size_t missing = 0;
69 
70 /*
71  * fsnode_cmp --
72  *	This function is used by `qsort` so sort one directory's
73  *	entries.  `.` is always first, sollowed by anything else
74  *	as compared by `strcmp()`.
75  */
76 static int
77 fsnode_cmp(const void *vleft, const void *vright)
78 {
79 	const fsnode * const *left  = vleft;
80 	const fsnode * const *right = vright;
81 	const char *lname = (*left)->name, *rname = (*right)->name;
82 
83 	if (strcmp(lname, ".") == 0)
84 		return -1;
85 	if (strcmp(rname, ".") == 0)
86 		return 1;
87 	return strcmp(lname, rname);
88 }
89 
90 static fsnode *
91 fsnode_sort(fsnode *first, const char *root, const char *dir)
92 {
93 	fsnode **list, **listptr;
94 	size_t num = 0;
95 
96 	for (fsnode *tmp = first; tmp; tmp = tmp->next, num++) {
97 		if (debug & DEBUG_DUMP_FSNODES_VERBOSE)
98 			printf("%s: pre sort: %s %s %s\n",
99 			    __func__, root, dir, tmp->name);
100 	}
101 
102 	list = listptr = ecalloc(num, sizeof(*list));
103 	for (fsnode *tmp = first; tmp; tmp = tmp->next)
104 		*listptr++ = tmp;
105 
106 	qsort(list, num, sizeof(*list), fsnode_cmp);
107 
108 	for (size_t i = 0; i < num - 1; ++i)
109 		list[i]->next = list[i + 1];
110 	list[num - 1]->next = NULL;
111 	first = list[0];
112 	assert(strcmp(first->name, ".") == 0);
113 	free(list);
114 	if (debug & DEBUG_DUMP_FSNODES_VERBOSE)
115 		for (fsnode *tmp = first; tmp; tmp = tmp->next)
116 			printf("%s: post sort: %s %s %s\n",
117 			    __func__, root, dir, tmp->name);
118 
119 	return first;
120 }
121 
122 /*
123  * walk_dir --
124  *	build a tree of fsnodes from `root' and `dir', with a parent
125  *	fsnode of `parent' (which may be NULL for the root of the tree).
126  *	append the tree to a fsnode of `join' if it is not NULL.
127  *	each "level" is a directory, with the "." entry guaranteed to be
128  *	at the start of the list, and without ".." entries.
129  */
130 fsnode *
131 walk_dir(const char *root, const char *dir, fsnode *parent, fsnode *join,
132     int replace, int follow)
133 {
134 	fsnode		*first, *cur, *prev, *last;
135 	DIR		*dirp;
136 	struct dirent	*dent;
137 	char		path[MAXPATHLEN + 1];
138 	struct stat	stbuf;
139 	char		*name, *rp;
140 	int		dot, len;
141 
142 	assert(root != NULL);
143 	assert(dir != NULL);
144 
145 	len = snprintf(path, sizeof(path), "%s/%s", root, dir);
146 	if ((size_t)len >= sizeof(path))
147 		errx(EXIT_FAILURE, "Pathname too long.");
148 	if (debug & DEBUG_WALK_DIR)
149 		printf("%s: %s %p\n", __func__, path, parent);
150 	if ((dirp = opendir(path)) == NULL)
151 		err(EXIT_FAILURE, "Can't opendir `%s'", path);
152 	rp = path + strlen(root) + 1;
153 	if (join != NULL) {
154 		first = cur = join;
155 		while (cur->next != NULL)
156 			cur = cur->next;
157 		prev = last = cur;
158 	} else
159 		last = first = prev = NULL;
160 	while ((dent = readdir(dirp)) != NULL) {
161 		name = dent->d_name;
162 		dot = 0;
163 		if (name[0] == '.')
164 			switch (name[1]) {
165 			case '\0':	/* "." */
166 				if (join != NULL)
167 					continue;
168 				dot = 1;
169 				break;
170 			case '.':	/* ".." */
171 				if (name[2] == '\0')
172 					continue;
173 				/* FALLTHROUGH */
174 			default:
175 				dot = 0;
176 			}
177 		if (debug & DEBUG_WALK_DIR_NODE)
178 			printf("%s: scanning %s/%s/%s\n",
179 			    __func__, root, dir, name);
180 		if (snprintf(path + len, sizeof(path) - len, "/%s", name) >=
181 		    (int)sizeof(path) - len)
182 			errx(EXIT_FAILURE, "Pathname too long.");
183 		if (follow) {
184 			if (stat(path, &stbuf) == -1)
185 				err(EXIT_FAILURE, "Can't stat `%s'", path);
186 		} else {
187 			if (lstat(path, &stbuf) == -1)
188 				err(EXIT_FAILURE, "Can't lstat `%s'", path);
189 			/*
190 			 * Symlink permission bits vary between filesystems/OSs
191 			 * (ie. 0755 on FFS/NetBSD, 0777 for ext[234]/Linux),
192 			 * force them to 0755.
193 			 */
194 			if (S_ISLNK(stbuf.st_mode)) {
195 				stbuf.st_mode &= ~(S_IRWXU | S_IRWXG | S_IRWXO);
196 				stbuf.st_mode |= S_IRWXU
197 				    | S_IRGRP | S_IXGRP
198 				    | S_IROTH | S_IXOTH;
199 			}
200 		}
201 #ifdef S_ISSOCK
202 		if (S_ISSOCK(stbuf.st_mode & S_IFMT)) {
203 			if (debug & DEBUG_WALK_DIR_NODE)
204 				printf("%s: skipping socket %s\n", __func__, path);
205 			continue;
206 		}
207 #endif
208 
209 		if (join != NULL) {
210 			cur = join->next;
211 			for (;;) {
212 				if (cur == NULL || strcmp(cur->name, name) == 0)
213 					break;
214 				if (cur == last) {
215 					cur = NULL;
216 					break;
217 				}
218 				cur = cur->next;
219 			}
220 			if (cur != NULL) {
221 				if (S_ISDIR(cur->type) &&
222 				    S_ISDIR(stbuf.st_mode)) {
223 					if (debug & DEBUG_WALK_DIR_NODE)
224 						printf("%s: merging %s with %p\n",
225 						    __func__, path, cur->child);
226 					cur->child = walk_dir(root, rp, cur,
227 					    cur->child, replace, follow);
228 					continue;
229 				}
230 				if (!replace)
231 					errx(EXIT_FAILURE,
232 					    "Can't merge %s `%s' with "
233 					    "existing %s",
234 					    inode_type(stbuf.st_mode), path,
235 					    inode_type(cur->type));
236 				else {
237 					if (debug & DEBUG_WALK_DIR_NODE)
238 						printf("%s: replacing %s %s\n",
239 						    __func__,
240 						    inode_type(stbuf.st_mode),
241 						    path);
242 					if (cur == join->next)
243 						join->next = cur->next;
244 					else {
245 						fsnode *p;
246 						for (p = join->next;
247 						    p->next != cur; p = p->next)
248 							continue;
249 						p->next = cur->next;
250 					}
251 					free(cur);
252 				}
253 			}
254 		}
255 
256 		cur = create_fsnode(root, dir, name, &stbuf);
257 		cur->parent = parent;
258 		if (dot) {
259 				/* ensure "." is at the start of the list */
260 			cur->next = first;
261 			first = cur;
262 			if (! prev)
263 				prev = cur;
264 			cur->first = first;
265 		} else {			/* not "." */
266 			if (prev)
267 				prev->next = cur;
268 			prev = cur;
269 			if (!first)
270 				first = cur;
271 			cur->first = first;
272 			if (S_ISDIR(cur->type)) {
273 				cur->child = walk_dir(root, rp, cur, NULL,
274 				    replace, follow);
275 				continue;
276 			}
277 		}
278 		if (stbuf.st_nlink > 1) {
279 			fsinode	*curino;
280 
281 			curino = link_check(cur->inode);
282 			if (curino != NULL) {
283 				free(cur->inode);
284 				cur->inode = curino;
285 				cur->inode->nlink++;
286 				if (debug & DEBUG_WALK_DIR_LINKCHECK)
287 					printf("%s: link check found [%ju, %ju]\n",
288 					    __func__,
289 					    (uintmax_t)curino->st.st_dev,
290 					    (uintmax_t)curino->st.st_ino);
291 			}
292 		}
293 		if (S_ISLNK(cur->type)) {
294 			char	slink[PATH_MAX+1];
295 			ssize_t	llen;
296 
297 			llen = readlink(path, slink, sizeof(slink) - 1);
298 			if (llen == -1)
299 				err(EXIT_FAILURE, "Readlink `%s'", path);
300 			slink[llen] = '\0';
301 			cur->symlink = estrdup(slink);
302 		}
303 	}
304 	assert(first != NULL);
305 	if (join == NULL)
306 		for (cur = first->next; cur != NULL; cur = cur->next)
307 			cur->first = first;
308 	if (closedir(dirp) == -1)
309 		err(EXIT_FAILURE, "Can't closedir `%s/%s'", root, dir);
310 
311 	return fsnode_sort(first, root, dir);
312 }
313 
314 static fsnode *
315 create_fsnode(const char *root, const char *path, const char *name,
316     struct stat *stbuf)
317 {
318 	fsnode *cur;
319 
320 	cur = ecalloc(1, sizeof(*cur));
321 	cur->path = estrdup(path);
322 	cur->name = estrdup(name);
323 	cur->inode = ecalloc(1, sizeof(*cur->inode));
324 	cur->root = root;
325 	cur->type = stbuf->st_mode & S_IFMT;
326 	cur->inode->nlink = 1;
327 	cur->inode->st = *stbuf;
328 	if (stampst.st_ino) {
329 		cur->inode->st.st_atime = stampst.st_atime;
330 		cur->inode->st.st_mtime = stampst.st_mtime;
331 		cur->inode->st.st_ctime = stampst.st_ctime;
332 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
333 		cur->inode->st.st_atimensec = stampst.st_atimensec;
334 		cur->inode->st.st_mtimensec = stampst.st_mtimensec;
335 		cur->inode->st.st_ctimensec = stampst.st_ctimensec;
336 #endif
337 #if HAVE_STRUCT_STAT_BIRTHTIME
338 		cur->inode->st.st_birthtime = stampst.st_birthtime;
339 		cur->inode->st.st_birthtimensec = stampst.st_birthtimensec;
340 #endif
341 	}
342 	return (cur);
343 }
344 
345 /*
346  * free_fsnodes --
347  *	Removes node from tree and frees it and all of
348  *   its descendents.
349  */
350 void
351 free_fsnodes(fsnode *node)
352 {
353 	fsnode	*cur, *next;
354 
355 	assert(node != NULL);
356 
357 	/* for ".", start with actual parent node */
358 	if (node->first == node) {
359 		assert(node->name[0] == '.' && node->name[1] == '\0');
360 		if (node->parent) {
361 			assert(node->parent->child == node);
362 			node = node->parent;
363 		}
364 	}
365 
366 	/* Find ourselves in our sibling list and unlink */
367 	if (node->first != node) {
368 		for (cur = node->first; cur->next; cur = cur->next) {
369 			if (cur->next == node) {
370 				cur->next = node->next;
371 				node->next = NULL;
372 				break;
373 			}
374 		}
375 	}
376 
377 	for (cur = node; cur != NULL; cur = next) {
378 		next = cur->next;
379 		if (cur->child) {
380 			cur->child->parent = NULL;
381 			free_fsnodes(cur->child);
382 		}
383 		if (cur->inode->nlink-- == 1)
384 			free(cur->inode);
385 		if (cur->symlink)
386 			free(cur->symlink);
387 		free(cur->path);
388 		free(cur->name);
389 		free(cur);
390 	}
391 }
392 
393 /*
394  * apply_specfile --
395  *	read in the mtree(8) specfile, and apply it to the tree
396  *	at dir,parent. parameters in parent on equivalent types
397  *	will be changed to those found in specfile, and missing
398  *	entries will be added.
399  */
400 void
401 apply_specfile(const char *specfile, const char *dir, fsnode *parent, int speconly)
402 {
403 	struct timeval	 start;
404 	FILE	*fp;
405 	NODE	*root;
406 
407 	assert(specfile != NULL);
408 	assert(parent != NULL);
409 
410 	if (debug & DEBUG_APPLY_SPECFILE)
411 		printf("%s: %s, %s %p\n", __func__, specfile, dir, parent);
412 
413 				/* read in the specfile */
414 	if ((fp = fopen(specfile, "r")) == NULL)
415 		err(EXIT_FAILURE, "Can't open `%s'", specfile);
416 	TIMER_START(start);
417 	root = spec(fp);
418 	TIMER_RESULTS(start, "spec");
419 	if (fclose(fp) == EOF)
420 		err(EXIT_FAILURE, "Can't close `%s'", specfile);
421 
422 				/* perform some sanity checks */
423 	if (root == NULL)
424 		errx(EXIT_FAILURE,
425 		    "Specfile `%s' did not contain a tree", specfile);
426 	assert(strcmp(root->name, ".") == 0);
427 	assert(root->type == F_DIR);
428 
429 				/* merge in the changes */
430 	apply_specdir(dir, root, parent, speconly);
431 
432 	free_nodes(root);
433 	if (missing)
434 		errx(EXIT_FAILURE, "Add %zu missing entries in `%s'",
435 		    missing, specfile);
436 }
437 
438 static void
439 apply_specdir(const char *dir, NODE *specnode, fsnode *dirnode, int speconly)
440 {
441 	char	 path[MAXPATHLEN + 1];
442 	NODE	*curnode;
443 	fsnode	*curfsnode;
444 
445 	assert(specnode != NULL);
446 	assert(dirnode != NULL);
447 
448 	if (debug & DEBUG_APPLY_SPECFILE)
449 		printf("%s: %s %p %p\n", __func__, dir, specnode, dirnode);
450 
451 	if (specnode->type != F_DIR)
452 		errx(EXIT_FAILURE, "Specfile node `%s/%s' is not a directory",
453 		    dir, specnode->name);
454 	if (dirnode->type != S_IFDIR)
455 		errx(EXIT_FAILURE, "Directory node `%s/%s' is not a directory",
456 		    dir, dirnode->name);
457 
458 	apply_specentry(dir, specnode, dirnode);
459 
460 	/* Remove any filesystem nodes not found in specfile */
461 	/* XXX inefficient.  This is O^2 in each dir and it would
462 	 * have been better never to have walked this part of the tree
463 	 * to begin with
464 	 */
465 	if (speconly) {
466 		fsnode *next;
467 		assert(dirnode->name[0] == '.' && dirnode->name[1] == '\0');
468 		for (curfsnode = dirnode->next; curfsnode != NULL; curfsnode = next) {
469 			next = curfsnode->next;
470 			for (curnode = specnode->child; curnode != NULL;
471 			     curnode = curnode->next) {
472 				if (strcmp(curnode->name, curfsnode->name) == 0)
473 					break;
474 			}
475 			if (curnode == NULL) {
476 				if (speconly > 1) {
477 					warnx("missing specfile entry for %s/%s",
478 					    dir, curfsnode->name);
479 					missing++;
480 				}
481 				if (debug & DEBUG_APPLY_SPECONLY) {
482 					printf("%s: trimming %s/%s %p\n",
483 					    __func__, dir, curfsnode->name,
484 					    curfsnode);
485 				}
486 				free_fsnodes(curfsnode);
487 			}
488 		}
489 	}
490 
491 			/* now walk specnode->child matching up with dirnode */
492 	for (curnode = specnode->child; curnode != NULL;
493 	    curnode = curnode->next) {
494 		if (debug & DEBUG_APPLY_SPECENTRY)
495 			printf("%s:  spec %s\n", __func__, curnode->name);
496 		for (curfsnode = dirnode->next; curfsnode != NULL;
497 		    curfsnode = curfsnode->next) {
498 #if 0	/* too verbose for now */
499 			if (debug & DEBUG_APPLY_SPECENTRY)
500 				printf("%s: dirent %s\n", __func__,
501 				    curfsnode->name);
502 #endif
503 			if (strcmp(curnode->name, curfsnode->name) == 0)
504 				break;
505 		}
506 		if ((size_t)snprintf(path, sizeof(path), "%s/%s",
507 		    dir, curnode->name) >= sizeof(path))
508 			errx(EXIT_FAILURE, "Pathname too long.");
509 		if (curfsnode == NULL) {	/* need new entry */
510 			struct stat	stbuf;
511 
512 					    /*
513 					     * don't add optional spec entries
514 					     * that lack an existing fs entry
515 					     */
516 			if ((curnode->flags & F_OPT) &&
517 			    lstat(path, &stbuf) == -1)
518 					continue;
519 
520 					/* check that enough info is provided */
521 #define NODETEST(t, m)							\
522 			if (!(t))					\
523 				errx(EXIT_FAILURE,			\
524 				    "`%s': %s not provided", path, m)
525 			NODETEST(curnode->flags & F_TYPE, "type");
526 			NODETEST(curnode->flags & F_MODE, "mode");
527 				/* XXX: require F_TIME ? */
528 			NODETEST(curnode->flags & F_GID ||
529 			    curnode->flags & F_GNAME, "group");
530 			NODETEST(curnode->flags & F_UID ||
531 			    curnode->flags & F_UNAME, "user");
532 			if (curnode->type == F_BLOCK || curnode->type == F_CHAR)
533 				NODETEST(curnode->flags & F_DEV,
534 				    "device number");
535 #undef NODETEST
536 
537 			if (debug & DEBUG_APPLY_SPECFILE)
538 				printf("%s: adding %s\n", __func__, curnode->name);
539 					/* build minimal fsnode */
540 			memset(&stbuf, 0, sizeof(stbuf));
541 			stbuf.st_mode = nodetoino(curnode->type);
542 			stbuf.st_nlink = 1;
543 			stbuf.st_mtime = stbuf.st_atime =
544 			    stbuf.st_ctime = start_time.tv_sec;
545 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
546 			stbuf.st_mtimensec = stbuf.st_atimensec =
547 			    stbuf.st_ctimensec = start_time.tv_nsec;
548 #endif
549 			curfsnode = create_fsnode(".", ".", curnode->name,
550 			    &stbuf);
551 			curfsnode->parent = dirnode->parent;
552 			curfsnode->first = dirnode;
553 			curfsnode->next = dirnode->next;
554 			dirnode->next = curfsnode;
555 			if (curfsnode->type == S_IFDIR) {
556 					/* for dirs, make "." entry as well */
557 				curfsnode->child = create_fsnode(".", ".", ".",
558 				    &stbuf);
559 				curfsnode->child->parent = curfsnode;
560 				curfsnode->child->first = curfsnode->child;
561 			}
562 			if (curfsnode->type == S_IFLNK) {
563 				assert(curnode->slink != NULL);
564 					/* for symlinks, copy the target */
565 				curfsnode->symlink = estrdup(curnode->slink);
566 			}
567 		}
568 		apply_specentry(dir, curnode, curfsnode);
569 		if (curnode->type == F_DIR) {
570 			if (curfsnode->type != S_IFDIR)
571 				errx(EXIT_FAILURE,
572 				    "`%s' is not a directory", path);
573 			assert(curfsnode->child != NULL);
574 			apply_specdir(path, curnode, curfsnode->child, speconly);
575 		}
576 	}
577 }
578 
579 static void
580 apply_specentry(const char *dir, NODE *specnode, fsnode *dirnode)
581 {
582 
583 	assert(specnode != NULL);
584 	assert(dirnode != NULL);
585 
586 	if (nodetoino(specnode->type) != dirnode->type)
587 		errx(EXIT_FAILURE,
588 		    "`%s/%s' type mismatch: specfile %s, tree %s",
589 		    dir, specnode->name, inode_type(nodetoino(specnode->type)),
590 		    inode_type(dirnode->type));
591 
592 	if (debug & DEBUG_APPLY_SPECENTRY)
593 		printf("%s: %s/%s\n", dir, __func__, dirnode->name);
594 
595 #define ASEPRINT(t, b, o, n) \
596 		if (debug & DEBUG_APPLY_SPECENTRY) \
597 			printf("\t\t\tchanging %s from " b " to " b "\n", \
598 			    t, o, n)
599 
600 	if (specnode->flags & (F_GID | F_GNAME)) {
601 		ASEPRINT("gid", "%d",
602 		    dirnode->inode->st.st_gid, specnode->st_gid);
603 		dirnode->inode->st.st_gid = specnode->st_gid;
604 	}
605 	if (specnode->flags & F_MODE) {
606 		ASEPRINT("mode", "%#o",
607 		    dirnode->inode->st.st_mode & ALLPERMS, specnode->st_mode);
608 		dirnode->inode->st.st_mode &= ~ALLPERMS;
609 		dirnode->inode->st.st_mode |= (specnode->st_mode & ALLPERMS);
610 	}
611 		/* XXX: ignoring F_NLINK for now */
612 	if (specnode->flags & F_SIZE) {
613 		ASEPRINT("size", "%jd",
614 		    (intmax_t)dirnode->inode->st.st_size,
615 		    (intmax_t)specnode->st_size);
616 		dirnode->inode->st.st_size = specnode->st_size;
617 	}
618 	if (specnode->flags & F_SLINK) {
619 		assert(dirnode->symlink != NULL);
620 		assert(specnode->slink != NULL);
621 		ASEPRINT("symlink", "%s", dirnode->symlink, specnode->slink);
622 		free(dirnode->symlink);
623 		dirnode->symlink = estrdup(specnode->slink);
624 	}
625 	if (specnode->flags & F_TIME) {
626 		ASEPRINT("time", "%ld",
627 		    (long)dirnode->inode->st.st_mtime,
628 		    (long)specnode->st_mtimespec.tv_sec);
629 		dirnode->inode->st.st_mtime =		specnode->st_mtimespec.tv_sec;
630 		dirnode->inode->st.st_atime =		specnode->st_mtimespec.tv_sec;
631 		dirnode->inode->st.st_ctime =		start_time.tv_sec;
632 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
633 		dirnode->inode->st.st_mtimensec =	specnode->st_mtimespec.tv_nsec;
634 		dirnode->inode->st.st_atimensec =	specnode->st_mtimespec.tv_nsec;
635 		dirnode->inode->st.st_ctimensec =	start_time.tv_nsec;
636 #endif
637 	}
638 	if (specnode->flags & (F_UID | F_UNAME)) {
639 		ASEPRINT("uid", "%d",
640 		    dirnode->inode->st.st_uid, specnode->st_uid);
641 		dirnode->inode->st.st_uid = specnode->st_uid;
642 	}
643 #if HAVE_STRUCT_STAT_ST_FLAGS
644 	if (specnode->flags & F_FLAGS) {
645 		ASEPRINT("flags", "%#lX",
646 		    (unsigned long)dirnode->inode->st.st_flags,
647 		    (unsigned long)specnode->st_flags);
648 		dirnode->inode->st.st_flags = (unsigned int)specnode->st_flags;
649 	}
650 #endif
651 	if (specnode->flags & F_DEV) {
652 		ASEPRINT("rdev", "%#jx",
653 		    (uintmax_t)dirnode->inode->st.st_rdev,
654 		    (uintmax_t)specnode->st_rdev);
655 		dirnode->inode->st.st_rdev = specnode->st_rdev;
656 	}
657 #undef ASEPRINT
658 
659 	dirnode->flags |= FSNODE_F_HASSPEC;
660 }
661 
662 
663 /*
664  * dump_fsnodes --
665  *	dump the fsnodes from `cur'
666  */
667 void
668 dump_fsnodes(fsnode *root)
669 {
670 	fsnode	*cur;
671 	char	path[MAXPATHLEN + 1];
672 
673 	printf("%s: %s %p\n", __func__, root->path, root);
674 	for (cur = root; cur != NULL; cur = cur->next) {
675 		if (snprintf(path, sizeof(path), "%s/%s", cur->path,
676 		    cur->name) >= (int)sizeof(path))
677 			errx(EXIT_FAILURE, "Pathname too long.");
678 
679 		if (debug & DEBUG_DUMP_FSNODES_VERBOSE)
680 			printf("%s: cur=%8p parent=%8p first=%8p ", __func__,
681 			    cur, cur->parent, cur->first);
682 		printf("%7s: %s", inode_type(cur->type), path);
683 		if (S_ISLNK(cur->type)) {
684 			assert(cur->symlink != NULL);
685 			printf(" -> %s", cur->symlink);
686 		} else {
687 			assert(cur->symlink == NULL);
688 		}
689 		if (cur->inode->nlink > 1)
690 			printf(", nlinks=%d", cur->inode->nlink);
691 		putchar('\n');
692 
693 		if (cur->child) {
694 			assert(cur->type == S_IFDIR);
695 			dump_fsnodes(cur->child);
696 		}
697 	}
698 	printf("%s: finished %s/%s\n", __func__, root->path, root->name);
699 }
700 
701 
702 /*
703  * inode_type --
704  *	for a given inode type `mode', return a descriptive string.
705  *	for most cases, uses inotype() from mtree/misc.c
706  */
707 const char *
708 inode_type(mode_t mode)
709 {
710 
711 	if (S_ISLNK(mode))
712 		return ("symlink");	/* inotype() returns "link"...  */
713 	return (inotype(mode));
714 }
715 
716 
717 /*
718  * link_check --
719  *	return pointer to fsinode matching `entry's st_ino & st_dev if it exists,
720  *	otherwise add `entry' to table and return NULL
721  */
722 /* This was borrowed from du.c and tweaked to keep an fsnode
723  * pointer instead. -- dbj@netbsd.org
724  */
725 static fsinode *
726 link_check(fsinode *entry)
727 {
728 	static struct entry {
729 		fsinode *data;
730 	} *htable;
731 	static size_t htshift;  /* log(allocated size) */
732 	static size_t htmask;   /* allocated size - 1 */
733 	static size_t htused;   /* 2*number of insertions */
734 	size_t h, h2;
735 	uint64_t tmp;
736 	/* this constant is (1<<64)/((1+sqrt(5))/2)
737 	 * aka (word size)/(golden ratio)
738 	 */
739 	const uint64_t HTCONST = 11400714819323198485ULL;
740 	const size_t HTBITS = 64;
741 
742 	/* Never store zero in hashtable */
743 	assert(entry);
744 
745 	/* Extend hash table if necessary, keep load under 0.5 */
746 	if (htused<<1 >= htmask) {
747 		struct entry *ohtable;
748 
749 		if (!htable)
750 			htshift = 10;   /* starting hashtable size */
751 		else
752 			htshift++;   /* exponential hashtable growth */
753 
754 		htmask  = (1 << htshift) - 1;
755 		htused = 0;
756 
757 		ohtable = htable;
758 		htable = ecalloc(htmask+1, sizeof(*htable));
759 		/* populate newly allocated hashtable */
760 		if (ohtable) {
761 			for (size_t i = 0; i <= htmask>>1; i++)
762 				if (ohtable[i].data)
763 					link_check(ohtable[i].data);
764 			free(ohtable);
765 		}
766 	}
767 
768 	/* multiplicative hashing */
769 	tmp = entry->st.st_dev;
770 	tmp <<= HTBITS>>1;
771 	tmp |=  entry->st.st_ino;
772 	tmp *= HTCONST;
773 	h  = tmp >> (HTBITS - htshift);
774 	h2 = 1 | ( tmp >> (HTBITS - (htshift<<1) - 1)); /* must be odd */
775 
776 	/* open address hashtable search with double hash probing */
777 	while (htable[h].data) {
778 		if ((htable[h].data->st.st_ino == entry->st.st_ino) &&
779 		    (htable[h].data->st.st_dev == entry->st.st_dev)) {
780 			return htable[h].data;
781 		}
782 		h = (h + h2) & htmask;
783 	}
784 
785 	/* Insert the current entry into hashtable */
786 	htable[h].data = entry;
787 	htused++;
788 	return NULL;
789 }
790