dirs.c revision 144097
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 144097 2005-03-25 06:57:50Z 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	printf("Looking for %s\n", pathname);
282
283	strcpy(buffer, pathname);
284	path = buffer;
285	ino = ROOTINO;
286	while (*path == '/')
287		path++;
288	dp = NULL;
289	while ((name = strsep(&path, "/")) != NULL && *name != '\0') {
290		if ((dp = searchdir(ino, name)) == NULL)
291			return (NULL);
292		ino = dp->d_ino;
293	}
294	return (dp);
295}
296
297/*
298 * Lookup the requested name in directory inum.
299 * Return its inode number if found, zero if it does not exist.
300 */
301static struct direct *
302searchdir(ino_t	inum, char *name)
303{
304	struct direct *dp;
305	struct inotab *itp;
306	int len;
307
308	itp = inotablookup(inum);
309	if (itp == NULL)
310		return (NULL);
311	rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
312	len = strlen(name);
313	do {
314		dp = rst_readdir(dirp);
315		if (dp == NULL)
316			return (NULL);
317	} while (dp->d_namlen != len || strncmp(dp->d_name, name, len) != 0);
318	return (dp);
319}
320
321/*
322 * Put the directory entries in the directory file
323 */
324static void
325putdir(char *buf, long size)
326{
327	struct direct *dp;
328	long loc, i;
329
330	for (loc = 0; loc < size; ) {
331		dp = (struct direct *)(buf + loc);
332		if (Bcvt)
333			swabst((u_char *)"ls", (u_char *) dp);
334		i = DIRBLKSIZ - (loc & (DIRBLKSIZ - 1));
335		if ((dp->d_reclen & 0x3) != 0 ||
336		    dp->d_reclen > i ||
337		    dp->d_reclen < DIRSIZ(0, dp)
338#if NAME_MAX < 255
339		    || dp->d_namlen > NAME_MAX
340#endif
341		    ) {
342			vprintf(stdout, "Mangled directory: ");
343			if ((dp->d_reclen & 0x3) != 0)
344				vprintf(stdout,
345				   "reclen not multiple of 4 ");
346			if (dp->d_reclen < DIRSIZ(0, dp))
347				vprintf(stdout,
348				   "reclen less than DIRSIZ (%d < %d) ",
349				   dp->d_reclen, DIRSIZ(0, dp));
350#if NAME_MAX < 255
351			if (dp->d_namlen > NAME_MAX)
352				vprintf(stdout,
353				   "reclen name too big (%d > %d) ",
354				   dp->d_namlen, NAME_MAX);
355#endif
356			vprintf(stdout, "\n");
357			loc += i;
358			continue;
359		}
360		loc += dp->d_reclen;
361		if (dp->d_ino != 0) {
362			putent(dp);
363		}
364	}
365}
366
367/*
368 * These variables are "local" to the following two functions.
369 */
370char dirbuf[DIRBLKSIZ];
371long dirloc = 0;
372long prev = 0;
373
374/*
375 * add a new directory entry to a file.
376 */
377static void
378putent(struct direct *dp)
379{
380	dp->d_reclen = DIRSIZ(0, dp);
381	if (dirloc + dp->d_reclen > DIRBLKSIZ) {
382		((struct direct *)(dirbuf + prev))->d_reclen =
383		    DIRBLKSIZ - prev;
384		(void) fwrite(dirbuf, 1, DIRBLKSIZ, df);
385		dirloc = 0;
386	}
387	memmove(dirbuf + dirloc, dp, (long)dp->d_reclen);
388	prev = dirloc;
389	dirloc += dp->d_reclen;
390}
391
392/*
393 * flush out a directory that is finished.
394 */
395static void
396flushent(void)
397{
398	((struct direct *)(dirbuf + prev))->d_reclen = DIRBLKSIZ - prev;
399	(void) fwrite(dirbuf, (int)dirloc, 1, df);
400	seekpt = ftell(df);
401	dirloc = 0;
402}
403
404/*
405 * Seek to an entry in a directory.
406 * Only values returned by rst_telldir should be passed to rst_seekdir.
407 * This routine handles many directories in a single file.
408 * It takes the base of the directory in the file, plus
409 * the desired seek offset into it.
410 */
411static void
412rst_seekdir(RST_DIR *dirp, long loc, long base)
413{
414
415	if (loc == rst_telldir(dirp))
416		return;
417	loc -= base;
418	if (loc < 0)
419		fprintf(stderr, "bad seek pointer to rst_seekdir %ld\n", loc);
420	(void) lseek(dirp->dd_fd, base + (loc & ~(DIRBLKSIZ - 1)), SEEK_SET);
421	dirp->dd_loc = loc & (DIRBLKSIZ - 1);
422	if (dirp->dd_loc != 0)
423		dirp->dd_size = read(dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ);
424}
425
426/*
427 * get next entry in a directory.
428 */
429struct direct *
430rst_readdir(RST_DIR *dirp)
431{
432	struct direct *dp;
433
434	for (;;) {
435		if (dirp->dd_loc == 0) {
436			dirp->dd_size = read(dirp->dd_fd, dirp->dd_buf,
437			    DIRBLKSIZ);
438			if (dirp->dd_size <= 0) {
439				dprintf(stderr, "error reading directory\n");
440				return (NULL);
441			}
442		}
443		if (dirp->dd_loc >= dirp->dd_size) {
444			dirp->dd_loc = 0;
445			continue;
446		}
447		dp = (struct direct *)(dirp->dd_buf + dirp->dd_loc);
448		if (dp->d_reclen == 0 ||
449		    dp->d_reclen > DIRBLKSIZ + 1 - dirp->dd_loc) {
450			dprintf(stderr, "corrupted directory: bad reclen %d\n",
451				dp->d_reclen);
452			return (NULL);
453		}
454		dirp->dd_loc += dp->d_reclen;
455		if (dp->d_ino == 0 && strcmp(dp->d_name, "/") == 0)
456			return (NULL);
457		if (dp->d_ino >= maxino) {
458			dprintf(stderr, "corrupted directory: bad inum %d\n",
459				dp->d_ino);
460			continue;
461		}
462		return (dp);
463	}
464}
465
466/*
467 * Simulate the opening of a directory
468 */
469void *
470rst_opendir(const char *name)
471{
472	struct inotab *itp;
473	RST_DIR *dirp;
474	ino_t ino;
475
476	if ((ino = dirlookup(name)) > 0 &&
477	    (itp = inotablookup(ino)) != NULL) {
478		dirp = opendirfile(dirfile);
479		rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
480		return (dirp);
481	}
482	return (NULL);
483}
484
485/*
486 * In our case, there is nothing to do when closing a directory.
487 */
488void
489rst_closedir(void *arg)
490{
491	RST_DIR *dirp;
492
493	dirp = arg;
494	(void)close(dirp->dd_fd);
495	free(dirp);
496	return;
497}
498
499/*
500 * Simulate finding the current offset in the directory.
501 */
502static long
503rst_telldir(RST_DIR *dirp)
504{
505	return ((long)lseek(dirp->dd_fd,
506	    (off_t)0, SEEK_CUR) - dirp->dd_size + dirp->dd_loc);
507}
508
509/*
510 * Open a directory file.
511 */
512static RST_DIR *
513opendirfile(const char *name)
514{
515	RST_DIR *dirp;
516	int fd;
517
518	if ((fd = open(name, O_RDONLY)) == -1)
519		return (NULL);
520	if ((dirp = malloc(sizeof(RST_DIR))) == NULL) {
521		(void)close(fd);
522		return (NULL);
523	}
524	dirp->dd_fd = fd;
525	dirp->dd_loc = 0;
526	return (dirp);
527}
528
529/*
530 * Set the mode, owner, and times for all new or changed directories
531 */
532void
533setdirmodes(int flags)
534{
535	FILE *mf;
536	struct modeinfo node;
537	struct entry *ep;
538	char *cp;
539	const char *tmpdir;
540
541	vprintf(stdout, "Set directory mode, owner, and times.\n");
542	if ((tmpdir = getenv("TMPDIR")) == NULL || tmpdir[0] == '\0')
543		tmpdir = _PATH_TMP;
544	if (command == 'r' || command == 'R')
545		(void) sprintf(modefile, "%s/rstmode%d", tmpdir, dumpdate);
546	if (modefile[0] == '#') {
547		panic("modefile not defined\n");
548		fprintf(stderr, "directory mode, owner, and times not set\n");
549		return;
550	}
551	mf = fopen(modefile, "r");
552	if (mf == NULL) {
553		fprintf(stderr, "fopen: %s\n", strerror(errno));
554		fprintf(stderr, "cannot open mode file %s\n", modefile);
555		fprintf(stderr, "directory mode, owner, and times not set\n");
556		return;
557	}
558	clearerr(mf);
559	for (;;) {
560		(void) fread((char *)&node, 1, sizeof(struct modeinfo), mf);
561		if (feof(mf))
562			break;
563		ep = lookupino(node.ino);
564		if (command == 'i' || command == 'x') {
565			if (ep == NULL)
566				continue;
567			if ((flags & FORCE) == 0 && ep->e_flags & EXISTED) {
568				ep->e_flags &= ~NEW;
569				continue;
570			}
571			if (node.ino == ROOTINO &&
572		   	    reply("set owner/mode for '.'") == FAIL)
573				continue;
574		}
575		if (ep == NULL) {
576			panic("cannot find directory inode %d\n", node.ino);
577		} else {
578			cp = myname(ep);
579			if (!Nflag) {
580				(void) chown(cp, node.uid, node.gid);
581				(void) chmod(cp, node.mode);
582				utimes(cp, node.ctimep);
583				utimes(cp, node.mtimep);
584				(void) chflags(cp, node.flags);
585			}
586			ep->e_flags &= ~NEW;
587		}
588	}
589	if (ferror(mf))
590		panic("error setting directory modes\n");
591	(void) fclose(mf);
592}
593
594/*
595 * Generate a literal copy of a directory.
596 */
597int
598genliteraldir(char *name, ino_t ino)
599{
600	struct inotab *itp;
601	int ofile, dp, i, size;
602	char buf[BUFSIZ];
603
604	itp = inotablookup(ino);
605	if (itp == NULL)
606		panic("Cannot find directory inode %d named %s\n", ino, name);
607	if ((ofile = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
608		fprintf(stderr, "%s: ", name);
609		(void) fflush(stderr);
610		fprintf(stderr, "cannot create file: %s\n", strerror(errno));
611		return (FAIL);
612	}
613	rst_seekdir(dirp, itp->t_seekpt, itp->t_seekpt);
614	dp = dup(dirp->dd_fd);
615	for (i = itp->t_size; i > 0; i -= BUFSIZ) {
616		size = i < BUFSIZ ? i : BUFSIZ;
617		if (read(dp, buf, (int) size) == -1) {
618			fprintf(stderr,
619				"write error extracting inode %d, name %s\n",
620				curfile.ino, curfile.name);
621			fprintf(stderr, "read: %s\n", strerror(errno));
622			done(1);
623		}
624		if (!Nflag && write(ofile, buf, (int) size) == -1) {
625			fprintf(stderr,
626				"write error extracting inode %d, name %s\n",
627				curfile.ino, curfile.name);
628			fprintf(stderr, "write: %s\n", strerror(errno));
629			done(1);
630		}
631	}
632	(void) close(dp);
633	(void) close(ofile);
634	return (GOOD);
635}
636
637/*
638 * Determine the type of an inode
639 */
640int
641inodetype(ino_t ino)
642{
643	struct inotab *itp;
644
645	itp = inotablookup(ino);
646	if (itp == NULL)
647		return (LEAF);
648	return (NODE);
649}
650
651/*
652 * Allocate and initialize a directory inode entry.
653 * If requested, save its pertinent mode, owner, and time info.
654 */
655static struct inotab *
656allocinotab(struct context *ctxp, long seekpt)
657{
658	struct inotab	*itp;
659	struct modeinfo node;
660
661	itp = calloc(1, sizeof(struct inotab));
662	if (itp == NULL)
663		panic("no memory directory table\n");
664	itp->t_next = inotab[INOHASH(ctxp->ino)];
665	inotab[INOHASH(ctxp->ino)] = itp;
666	itp->t_ino = ctxp->ino;
667	itp->t_seekpt = seekpt;
668	if (mf == NULL)
669		return (itp);
670	node.ino = ctxp->ino;
671	node.mtimep[0].tv_sec = ctxp->atime_sec;
672	node.mtimep[0].tv_usec = ctxp->atime_nsec / 1000;
673	node.mtimep[1].tv_sec = ctxp->mtime_sec;
674	node.mtimep[1].tv_usec = ctxp->mtime_nsec / 1000;
675	node.ctimep[0].tv_sec = ctxp->atime_sec;
676	node.ctimep[0].tv_usec = ctxp->atime_nsec / 1000;
677	node.ctimep[1].tv_sec = ctxp->birthtime_sec;
678	node.ctimep[1].tv_usec = ctxp->birthtime_nsec / 1000;
679	node.mode = ctxp->mode;
680	node.flags = ctxp->file_flags;
681	node.uid = ctxp->uid;
682	node.gid = ctxp->gid;
683	(void) fwrite((char *)&node, 1, sizeof(struct modeinfo), mf);
684	return (itp);
685}
686
687/*
688 * Look up an inode in the table of directories
689 */
690static struct inotab *
691inotablookup(ino_t ino)
692{
693	struct inotab *itp;
694
695	for (itp = inotab[INOHASH(ino)]; itp != NULL; itp = itp->t_next)
696		if (itp->t_ino == ino)
697			return (itp);
698	return (NULL);
699}
700
701/*
702 * Clean up and exit
703 */
704void
705done(int exitcode)
706{
707
708	closemt();
709	if (modefile[0] != '#')
710		(void) unlink(modefile);
711	if (dirfile[0] != '#')
712		(void) unlink(dirfile);
713	exit(exitcode);
714}
715