dirs.c revision 144597
1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#ifndef lint
36#if 0
37static char sccsid[] = "@(#)dirs.c	8.7 (Berkeley) 5/1/95";
38#endif
39static const char rcsid[] =
40  "$FreeBSD: head/sbin/restore/dirs.c 144597 2005-04-03 16:35:58Z imp $";
41#endif /* not lint */
42
43#include <sys/param.h>
44#include <sys/file.h>
45#include <sys/stat.h>
46#include <sys/time.h>
47
48#include <ufs/ufs/dinode.h>
49#include <ufs/ufs/dir.h>
50#include <protocols/dumprestore.h>
51
52#include <err.h>
53#include <errno.h>
54#include <limits.h>
55#include <paths.h>
56#include <stdio.h>
57#include <stdlib.h>
58#include <string.h>
59#include <unistd.h>
60
61#include "restore.h"
62#include "extern.h"
63
64/*
65 * Symbol table of directories read from tape.
66 */
67#define HASHSIZE	1000
68#define INOHASH(val) (val % HASHSIZE)
69struct inotab {
70	struct	inotab *t_next;
71	ino_t	t_ino;
72	int32_t	t_seekpt;
73	int32_t	t_size;
74};
75static struct inotab *inotab[HASHSIZE];
76
77/*
78 * Information retained about directories.
79 */
80struct modeinfo {
81	ino_t ino;
82	struct timeval ctimep[2];
83	struct timeval mtimep[2];
84	mode_t mode;
85	uid_t uid;
86	gid_t gid;
87	int flags;
88};
89
90/*
91 * Definitions for library routines operating on directories.
92 */
93#undef DIRBLKSIZ
94#define DIRBLKSIZ 1024
95struct rstdirdesc {
96	int	dd_fd;
97	int32_t	dd_loc;
98	int32_t	dd_size;
99	char	dd_buf[DIRBLKSIZ];
100};
101
102/*
103 * Global variables for this file.
104 */
105static long	seekpt;
106static FILE	*df, *mf;
107static RST_DIR	*dirp;
108static char	dirfile[MAXPATHLEN] = "#";	/* No file */
109static char	modefile[MAXPATHLEN] = "#";	/* No file */
110static char	dot[2] = ".";			/* So it can be modified */
111
112static struct inotab	*allocinotab(struct context *, long);
113static void		 flushent(void);
114static struct inotab	*inotablookup(ino_t);
115static RST_DIR		*opendirfile(const char *);
116static void		 putdir(char *, long);
117static void		 putent(struct direct *);
118static void		 rst_seekdir(RST_DIR *, long, long);
119static long		 rst_telldir(RST_DIR *);
120static struct direct	*searchdir(ino_t, char *);
121
122/*
123 *	Extract directory contents, building up a directory structure
124 *	on disk for extraction by name.
125 *	If genmode is requested, save mode, owner, and times for all
126 *	directories on the tape.
127 */
128void
129extractdirs(int genmode)
130{
131	struct inotab *itp;
132	struct direct nulldir;
133	int i, fd;
134	const char *tmpdir;
135
136	vprintf(stdout, "Extract directories from tape\n");
137	if ((tmpdir = getenv("TMPDIR")) == NULL || tmpdir[0] == '\0')
138		tmpdir = _PATH_TMP;
139	(void) sprintf(dirfile, "%s/rstdir%d", tmpdir, dumpdate);
140	if (command != 'r' && command != 'R') {
141		(void *) strcat(dirfile, "-XXXXXX");
142		fd = mkstemp(dirfile);
143	} else
144		fd = open(dirfile, O_RDWR|O_CREAT|O_EXCL, 0666);
145	if (fd == -1 || (df = fdopen(fd, "w")) == NULL) {
146		if (fd != -1)
147			close(fd);
148		warn("%s - cannot create directory temporary\nfopen", dirfile);
149		done(1);
150	}
151	if (genmode != 0) {
152		(void) sprintf(modefile, "%s/rstmode%d", tmpdir, dumpdate);
153		if (command != 'r' && command != 'R') {
154			(void *) strcat(modefile, "-XXXXXX");
155			fd = mkstemp(modefile);
156		} else
157			fd = open(modefile, O_RDWR|O_CREAT|O_EXCL, 0666);
158		if (fd == -1 || (mf = fdopen(fd, "w")) == NULL) {
159			if (fd != -1)
160				close(fd);
161			warn("%s - cannot create modefile\nfopen", modefile);
162			done(1);
163		}
164	}
165	nulldir.d_ino = 0;
166	nulldir.d_type = DT_DIR;
167	nulldir.d_namlen = 1;
168	(void) strcpy(nulldir.d_name, "/");
169	nulldir.d_reclen = DIRSIZ(0, &nulldir);
170	for (;;) {
171		curfile.name = "<directory file - name unknown>";
172		curfile.action = USING;
173		if (curfile.mode == 0 || (curfile.mode & IFMT) != IFDIR) {
174			(void) fclose(df);
175			dirp = opendirfile(dirfile);
176			if (dirp == NULL)
177				fprintf(stderr, "opendirfile: %s\n",
178				    strerror(errno));
179			if (mf != NULL)
180				(void) fclose(mf);
181			i = dirlookup(dot);
182			if (i == 0)
183				panic("Root directory is not on tape\n");
184			return;
185		}
186		itp = allocinotab(&curfile, seekpt);
187		getfile(putdir, xtrnull);
188		putent(&nulldir);
189		flushent();
190		itp->t_size = seekpt - itp->t_seekpt;
191	}
192}
193
194/*
195 * skip over all the directories on the tape
196 */
197void
198skipdirs(void)
199{
200
201	while (curfile.ino && (curfile.mode & IFMT) == IFDIR) {
202		skipfile();
203	}
204}
205
206/*
207 *	Recursively find names and inumbers of all files in subtree
208 *	pname and pass them off to be processed.
209 */
210void
211treescan(char *pname, ino_t ino, long (*todo)(char *, ino_t, int))
212{
213	struct inotab *itp;
214	struct direct *dp;
215	int namelen;
216	long bpt;
217	char locname[MAXPATHLEN + 1];
218
219	itp = inotablookup(ino);
220	if (itp == NULL) {
221		/*
222		 * Pname is name of a simple file or an unchanged directory.
223		 */
224		(void) (*todo)(pname, ino, LEAF);
225		return;
226	}
227	/*
228	 * Pname is a dumped directory name.
229	 */
230	if ((*todo)(pname, ino, NODE) == FAIL)
231		return;
232	/*
233	 * begin search through the directory
234	 * skipping over "." and ".."
235	 */
236	(void) strncpy(locname, pname, sizeof(locname) - 1);
237	locname[sizeof(locname) - 1] = '\0';
238	(void) strncat(locname, "/", sizeof(locname) - strlen(locname));
239	namelen = strlen(locname);
240	rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
241	dp = rst_readdir(dirp); /* "." */
242	if (dp != NULL && strcmp(dp->d_name, ".") == 0)
243		dp = rst_readdir(dirp); /* ".." */
244	else
245		fprintf(stderr, "Warning: `.' missing from directory %s\n",
246			pname);
247	if (dp != NULL && strcmp(dp->d_name, "..") == 0)
248		dp = rst_readdir(dirp); /* first real entry */
249	else
250		fprintf(stderr, "Warning: `..' missing from directory %s\n",
251			pname);
252	bpt = rst_telldir(dirp);
253	/*
254	 * a zero inode signals end of directory
255	 */
256	while (dp != NULL) {
257		locname[namelen] = '\0';
258		if (namelen + dp->d_namlen >= sizeof(locname)) {
259			fprintf(stderr, "%s%s: name exceeds %d char\n",
260				locname, dp->d_name, sizeof(locname) - 1);
261		} else {
262			(void) strncat(locname, dp->d_name, (int)dp->d_namlen);
263			treescan(locname, dp->d_ino, todo);
264			rst_seekdir(dirp, bpt, itp->t_seekpt);
265		}
266		dp = rst_readdir(dirp);
267		bpt = rst_telldir(dirp);
268	}
269}
270
271/*
272 * Lookup a pathname which is always assumed to start from the ROOTINO.
273 */
274struct direct *
275pathsearch(const char *pathname)
276{
277	ino_t ino;
278	struct direct *dp;
279	char *path, *name, buffer[MAXPATHLEN];
280
281	strcpy(buffer, pathname);
282	path = buffer;
283	ino = ROOTINO;
284	while (*path == '/')
285		path++;
286	dp = NULL;
287	while ((name = strsep(&path, "/")) != NULL && *name != '\0') {
288		if ((dp = searchdir(ino, name)) == NULL)
289			return (NULL);
290		ino = dp->d_ino;
291	}
292	return (dp);
293}
294
295/*
296 * Lookup the requested name in directory inum.
297 * Return its inode number if found, zero if it does not exist.
298 */
299static struct direct *
300searchdir(ino_t	inum, char *name)
301{
302	struct direct *dp;
303	struct inotab *itp;
304	int len;
305
306	itp = inotablookup(inum);
307	if (itp == NULL)
308		return (NULL);
309	rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
310	len = strlen(name);
311	do {
312		dp = rst_readdir(dirp);
313		if (dp == NULL)
314			return (NULL);
315	} while (dp->d_namlen != len || strncmp(dp->d_name, name, len) != 0);
316	return (dp);
317}
318
319/*
320 * Put the directory entries in the directory file
321 */
322static void
323putdir(char *buf, long size)
324{
325	struct direct *dp;
326	long loc, i;
327
328	for (loc = 0; loc < size; ) {
329		dp = (struct direct *)(buf + loc);
330		if (Bcvt)
331			swabst((u_char *)"ls", (u_char *) dp);
332		if (oldinofmt && dp->d_ino != 0) {
333#if BYTE_ORDER == BIG_ENDIAN
334			if (Bcvt)
335				dp->d_namlen = dp->d_type;
336#else
337			if (!Bcvt && dp->d_namlen == 0)
338				dp->d_namlen = dp->d_type;
339#endif
340			dp->d_type = DT_UNKNOWN;
341		}
342		i = DIRBLKSIZ - (loc & (DIRBLKSIZ - 1));
343		if ((dp->d_reclen & 0x3) != 0 ||
344		    dp->d_reclen > i ||
345		    dp->d_reclen < DIRSIZ(0, dp)
346#if NAME_MAX < 255
347		    || dp->d_namlen > NAME_MAX
348#endif
349		    ) {
350			vprintf(stdout, "Mangled directory: ");
351			if ((dp->d_reclen & 0x3) != 0)
352				vprintf(stdout,
353				   "reclen not multiple of 4 ");
354			if (dp->d_reclen < DIRSIZ(0, dp))
355				vprintf(stdout,
356				   "reclen less than DIRSIZ (%d < %d) ",
357				   dp->d_reclen, DIRSIZ(0, dp));
358#if NAME_MAX < 255
359			if (dp->d_namlen > NAME_MAX)
360				vprintf(stdout,
361				   "reclen name too big (%d > %d) ",
362				   dp->d_namlen, NAME_MAX);
363#endif
364			vprintf(stdout, "\n");
365			loc += i;
366			continue;
367		}
368		loc += dp->d_reclen;
369		if (dp->d_ino != 0) {
370			putent(dp);
371		}
372	}
373}
374
375/*
376 * These variables are "local" to the following two functions.
377 */
378char dirbuf[DIRBLKSIZ];
379long dirloc = 0;
380long prev = 0;
381
382/*
383 * add a new directory entry to a file.
384 */
385static void
386putent(struct direct *dp)
387{
388	dp->d_reclen = DIRSIZ(0, dp);
389	if (dirloc + dp->d_reclen > DIRBLKSIZ) {
390		((struct direct *)(dirbuf + prev))->d_reclen =
391		    DIRBLKSIZ - prev;
392		(void) fwrite(dirbuf, 1, DIRBLKSIZ, df);
393		dirloc = 0;
394	}
395	memmove(dirbuf + dirloc, dp, (long)dp->d_reclen);
396	prev = dirloc;
397	dirloc += dp->d_reclen;
398}
399
400/*
401 * flush out a directory that is finished.
402 */
403static void
404flushent(void)
405{
406	((struct direct *)(dirbuf + prev))->d_reclen = DIRBLKSIZ - prev;
407	(void) fwrite(dirbuf, (int)dirloc, 1, df);
408	seekpt = ftell(df);
409	dirloc = 0;
410}
411
412/*
413 * Seek to an entry in a directory.
414 * Only values returned by rst_telldir should be passed to rst_seekdir.
415 * This routine handles many directories in a single file.
416 * It takes the base of the directory in the file, plus
417 * the desired seek offset into it.
418 */
419static void
420rst_seekdir(RST_DIR *dirp, long loc, long base)
421{
422
423	if (loc == rst_telldir(dirp))
424		return;
425	loc -= base;
426	if (loc < 0)
427		fprintf(stderr, "bad seek pointer to rst_seekdir %ld\n", loc);
428	(void) lseek(dirp->dd_fd, base + (loc & ~(DIRBLKSIZ - 1)), SEEK_SET);
429	dirp->dd_loc = loc & (DIRBLKSIZ - 1);
430	if (dirp->dd_loc != 0)
431		dirp->dd_size = read(dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ);
432}
433
434/*
435 * get next entry in a directory.
436 */
437struct direct *
438rst_readdir(RST_DIR *dirp)
439{
440	struct direct *dp;
441
442	for (;;) {
443		if (dirp->dd_loc == 0) {
444			dirp->dd_size = read(dirp->dd_fd, dirp->dd_buf,
445			    DIRBLKSIZ);
446			if (dirp->dd_size <= 0) {
447				dprintf(stderr, "error reading directory\n");
448				return (NULL);
449			}
450		}
451		if (dirp->dd_loc >= dirp->dd_size) {
452			dirp->dd_loc = 0;
453			continue;
454		}
455		dp = (struct direct *)(dirp->dd_buf + dirp->dd_loc);
456		if (dp->d_reclen == 0 ||
457		    dp->d_reclen > DIRBLKSIZ + 1 - dirp->dd_loc) {
458			dprintf(stderr, "corrupted directory: bad reclen %d\n",
459				dp->d_reclen);
460			return (NULL);
461		}
462		dirp->dd_loc += dp->d_reclen;
463		if (dp->d_ino == 0 && strcmp(dp->d_name, "/") == 0)
464			return (NULL);
465		if (dp->d_ino >= maxino) {
466			dprintf(stderr, "corrupted directory: bad inum %d\n",
467				dp->d_ino);
468			continue;
469		}
470		return (dp);
471	}
472}
473
474/*
475 * Simulate the opening of a directory
476 */
477void *
478rst_opendir(const char *name)
479{
480	struct inotab *itp;
481	RST_DIR *dirp;
482	ino_t ino;
483
484	if ((ino = dirlookup(name)) > 0 &&
485	    (itp = inotablookup(ino)) != NULL) {
486		dirp = opendirfile(dirfile);
487		rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
488		return (dirp);
489	}
490	return (NULL);
491}
492
493/*
494 * In our case, there is nothing to do when closing a directory.
495 */
496void
497rst_closedir(void *arg)
498{
499	RST_DIR *dirp;
500
501	dirp = arg;
502	(void)close(dirp->dd_fd);
503	free(dirp);
504	return;
505}
506
507/*
508 * Simulate finding the current offset in the directory.
509 */
510static long
511rst_telldir(RST_DIR *dirp)
512{
513	return ((long)lseek(dirp->dd_fd,
514	    (off_t)0, SEEK_CUR) - dirp->dd_size + dirp->dd_loc);
515}
516
517/*
518 * Open a directory file.
519 */
520static RST_DIR *
521opendirfile(const char *name)
522{
523	RST_DIR *dirp;
524	int fd;
525
526	if ((fd = open(name, O_RDONLY)) == -1)
527		return (NULL);
528	if ((dirp = malloc(sizeof(RST_DIR))) == NULL) {
529		(void)close(fd);
530		return (NULL);
531	}
532	dirp->dd_fd = fd;
533	dirp->dd_loc = 0;
534	return (dirp);
535}
536
537/*
538 * Set the mode, owner, and times for all new or changed directories
539 */
540void
541setdirmodes(int flags)
542{
543	FILE *mf;
544	struct modeinfo node;
545	struct entry *ep;
546	char *cp;
547	const char *tmpdir;
548
549	vprintf(stdout, "Set directory mode, owner, and times.\n");
550	if ((tmpdir = getenv("TMPDIR")) == NULL || tmpdir[0] == '\0')
551		tmpdir = _PATH_TMP;
552	if (command == 'r' || command == 'R')
553		(void) sprintf(modefile, "%s/rstmode%d", tmpdir, dumpdate);
554	if (modefile[0] == '#') {
555		panic("modefile not defined\n");
556		fprintf(stderr, "directory mode, owner, and times not set\n");
557		return;
558	}
559	mf = fopen(modefile, "r");
560	if (mf == NULL) {
561		fprintf(stderr, "fopen: %s\n", strerror(errno));
562		fprintf(stderr, "cannot open mode file %s\n", modefile);
563		fprintf(stderr, "directory mode, owner, and times not set\n");
564		return;
565	}
566	clearerr(mf);
567	for (;;) {
568		(void) fread((char *)&node, 1, sizeof(struct modeinfo), mf);
569		if (feof(mf))
570			break;
571		ep = lookupino(node.ino);
572		if (command == 'i' || command == 'x') {
573			if (ep == NULL)
574				continue;
575			if ((flags & FORCE) == 0 && ep->e_flags & EXISTED) {
576				ep->e_flags &= ~NEW;
577				continue;
578			}
579			if (node.ino == ROOTINO &&
580		   	    reply("set owner/mode for '.'") == FAIL)
581				continue;
582		}
583		if (ep == NULL) {
584			panic("cannot find directory inode %d\n", node.ino);
585		} else {
586			cp = myname(ep);
587			if (!Nflag) {
588				(void) chown(cp, node.uid, node.gid);
589				(void) chmod(cp, node.mode);
590				utimes(cp, node.ctimep);
591				utimes(cp, node.mtimep);
592				(void) chflags(cp, node.flags);
593			}
594			ep->e_flags &= ~NEW;
595		}
596	}
597	if (ferror(mf))
598		panic("error setting directory modes\n");
599	(void) fclose(mf);
600}
601
602/*
603 * Generate a literal copy of a directory.
604 */
605int
606genliteraldir(char *name, ino_t ino)
607{
608	struct inotab *itp;
609	int ofile, dp, i, size;
610	char buf[BUFSIZ];
611
612	itp = inotablookup(ino);
613	if (itp == NULL)
614		panic("Cannot find directory inode %d named %s\n", ino, name);
615	if ((ofile = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
616		fprintf(stderr, "%s: ", name);
617		(void) fflush(stderr);
618		fprintf(stderr, "cannot create file: %s\n", strerror(errno));
619		return (FAIL);
620	}
621	rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
622	dp = dup(dirp->dd_fd);
623	for (i = itp->t_size; i > 0; i -= BUFSIZ) {
624		size = i < BUFSIZ ? i : BUFSIZ;
625		if (read(dp, buf, (int) size) == -1) {
626			fprintf(stderr,
627				"write error extracting inode %d, name %s\n",
628				curfile.ino, curfile.name);
629			fprintf(stderr, "read: %s\n", strerror(errno));
630			done(1);
631		}
632		if (!Nflag && write(ofile, buf, (int) size) == -1) {
633			fprintf(stderr,
634				"write error extracting inode %d, name %s\n",
635				curfile.ino, curfile.name);
636			fprintf(stderr, "write: %s\n", strerror(errno));
637			done(1);
638		}
639	}
640	(void) close(dp);
641	(void) close(ofile);
642	return (GOOD);
643}
644
645/*
646 * Determine the type of an inode
647 */
648int
649inodetype(ino_t ino)
650{
651	struct inotab *itp;
652
653	itp = inotablookup(ino);
654	if (itp == NULL)
655		return (LEAF);
656	return (NODE);
657}
658
659/*
660 * Allocate and initialize a directory inode entry.
661 * If requested, save its pertinent mode, owner, and time info.
662 */
663static struct inotab *
664allocinotab(struct context *ctxp, long seekpt)
665{
666	struct inotab	*itp;
667	struct modeinfo node;
668
669	itp = calloc(1, sizeof(struct inotab));
670	if (itp == NULL)
671		panic("no memory directory table\n");
672	itp->t_next = inotab[INOHASH(ctxp->ino)];
673	inotab[INOHASH(ctxp->ino)] = itp;
674	itp->t_ino = ctxp->ino;
675	itp->t_seekpt = seekpt;
676	if (mf == NULL)
677		return (itp);
678	node.ino = ctxp->ino;
679	node.mtimep[0].tv_sec = ctxp->atime_sec;
680	node.mtimep[0].tv_usec = ctxp->atime_nsec / 1000;
681	node.mtimep[1].tv_sec = ctxp->mtime_sec;
682	node.mtimep[1].tv_usec = ctxp->mtime_nsec / 1000;
683	node.ctimep[0].tv_sec = ctxp->atime_sec;
684	node.ctimep[0].tv_usec = ctxp->atime_nsec / 1000;
685	node.ctimep[1].tv_sec = ctxp->birthtime_sec;
686	node.ctimep[1].tv_usec = ctxp->birthtime_nsec / 1000;
687	node.mode = ctxp->mode;
688	node.flags = ctxp->file_flags;
689	node.uid = ctxp->uid;
690	node.gid = ctxp->gid;
691	(void) fwrite((char *)&node, 1, sizeof(struct modeinfo), mf);
692	return (itp);
693}
694
695/*
696 * Look up an inode in the table of directories
697 */
698static struct inotab *
699inotablookup(ino_t ino)
700{
701	struct inotab *itp;
702
703	for (itp = inotab[INOHASH(ino)]; itp != NULL; itp = itp->t_next)
704		if (itp->t_ino == ino)
705			return (itp);
706	return (NULL);
707}
708
709/*
710 * Clean up and exit
711 */
712void
713done(int exitcode)
714{
715
716	closemt();
717	if (modefile[0] != '#')
718		(void) unlink(modefile);
719	if (dirfile[0] != '#')
720		(void) unlink(dirfile);
721	exit(exitcode);
722}
723