spec.c revision 1.59
1/*	$NetBSD: spec.c,v 1.59 2004/12/01 23:27:36 lukem Exp $	*/
2
3/*-
4 * Copyright (c) 1989, 1993
5 *	The Regents of the University of California.  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 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32/*-
33 * Copyright (c) 2001-2004 The NetBSD Foundation, Inc.
34 * All rights reserved.
35 *
36 * This code is derived from software contributed to The NetBSD Foundation
37 * by Luke Mewburn of Wasabi Systems.
38 *
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 *    notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 *    notice, this list of conditions and the following disclaimer in the
46 *    documentation and/or other materials provided with the distribution.
47 * 3. All advertising materials mentioning features or use of this software
48 *    must display the following acknowledgement:
49 *        This product includes software developed by the NetBSD
50 *        Foundation, Inc. and its contributors.
51 * 4. Neither the name of The NetBSD Foundation nor the names of its
52 *    contributors may be used to endorse or promote products derived
53 *    from this software without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
56 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
57 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
58 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
59 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
60 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
61 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
62 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
63 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
65 * POSSIBILITY OF SUCH DAMAGE.
66 */
67
68#if HAVE_NBTOOL_CONFIG_H
69#include "nbtool_config.h"
70#endif
71
72#include <sys/cdefs.h>
73#if defined(__RCSID) && !defined(lint)
74#if 0
75static char sccsid[] = "@(#)spec.c	8.2 (Berkeley) 4/28/95";
76#else
77__RCSID("$NetBSD: spec.c,v 1.59 2004/12/01 23:27:36 lukem Exp $");
78#endif
79#endif /* not lint */
80
81#include <sys/param.h>
82#include <sys/stat.h>
83
84#include <ctype.h>
85#include <errno.h>
86#include <grp.h>
87#include <pwd.h>
88#include <stdio.h>
89#include <stdlib.h>
90#include <string.h>
91#include <unistd.h>
92#include <vis.h>
93#include <util.h>
94
95#include "extern.h"
96#include "pack_dev.h"
97
98size_t	mtree_lineno;			/* Current spec line number */
99int	mtree_Mflag;			/* Merge duplicate entries */
100int	mtree_Wflag;			/* Don't "whack" permissions */
101
102static	dev_t	parsedev(char *);
103static	void	replacenode(NODE *, NODE *);
104static	void	set(char *, NODE *);
105static	void	unset(char *, NODE *);
106
107#define REPLACEPTR(x,v)	do { if ((x)) free((x)); (x) = (v); } while (0)
108
109NODE *
110spec(FILE *fp)
111{
112	NODE *centry, *last, *pathparent, *cur;
113	char *p, *e, *next;
114	NODE ginfo, *root;
115	char *buf, *tname, *ntname;
116	size_t tnamelen, plen;
117
118	root = NULL;
119	centry = last = NULL;
120	tname = NULL;
121	tnamelen = 0;
122	memset(&ginfo, 0, sizeof(ginfo));
123	for (mtree_lineno = 0;
124	    (buf = fparseln(fp, NULL, &mtree_lineno, NULL,
125		FPARSELN_UNESCCOMM | FPARSELN_UNESCCONT | FPARSELN_UNESCESC));
126	    free(buf)) {
127		/* Skip leading whitespace. */
128		for (p = buf; *p && isspace((unsigned char)*p); ++p)
129			continue;
130
131		/* If nothing but whitespace, continue. */
132		if (!*p)
133			continue;
134
135#ifdef DEBUG
136		fprintf(stderr, "line %lu: {%s}\n",
137		    (u_long)mtree_lineno, p);
138#endif
139		/* Grab file name, "$", "set", or "unset". */
140		next = buf;
141		while ((p = strsep(&next, " \t")) != NULL && *p == '\0')
142			continue;
143		if (p == NULL)
144			mtree_err("missing field");
145
146		if (p[0] == '/') {
147			if (strcmp(p + 1, "set") == 0)
148				set(next, &ginfo);
149			else if (strcmp(p + 1, "unset") == 0)
150				unset(next, &ginfo);
151			else
152				mtree_err("invalid specification `%s'", p);
153			continue;
154		}
155
156		if (strcmp(p, "..") == 0) {
157			/* Don't go up, if haven't gone down. */
158			if (root == NULL)
159				goto noparent;
160			if (last->type != F_DIR || last->flags & F_DONE) {
161				if (last == root)
162					goto noparent;
163				last = last->parent;
164			}
165			last->flags |= F_DONE;
166			continue;
167
168noparent:		mtree_err("no parent node");
169		}
170
171		plen = strlen(p) + 1;
172		if (plen > tnamelen) {
173			if ((ntname = realloc(tname, plen)) == NULL)
174				mtree_err("realloc: %s", strerror(errno));
175			tname = ntname;
176			tnamelen = plen;
177		}
178		if (strunvis(tname, p) == -1)
179			mtree_err("strunvis failed on `%s'", p);
180		p = tname;
181
182		pathparent = NULL;
183		if (strchr(p, '/') != NULL) {
184			cur = root;
185			for (; (e = strchr(p, '/')) != NULL; p = e+1) {
186				if (p == e)
187					continue;	/* handle // */
188				*e = '\0';
189				if (strcmp(p, ".") != 0) {
190					while (cur &&
191					    strcmp(cur->name, p) != 0) {
192						cur = cur->next;
193					}
194				}
195				if (cur == NULL || cur->type != F_DIR) {
196					mtree_err("%s: %s", tname,
197					    strerror(ENOENT));
198				}
199				*e = '/';
200				pathparent = cur;
201				cur = cur->child;
202			}
203			if (*p == '\0')
204				mtree_err("%s: empty leaf element", tname);
205		}
206
207		if ((centry = calloc(1, sizeof(NODE) + strlen(p))) == NULL)
208			mtree_err("%s", strerror(errno));
209		*centry = ginfo;
210		centry->lineno = mtree_lineno;
211		strcpy(centry->name, p);
212#define	MAGIC	"?*["
213		if (strpbrk(p, MAGIC))
214			centry->flags |= F_MAGIC;
215		set(next, centry);
216
217		if (root == NULL) {
218				/*
219				 * empty tree
220				 */
221			if (strcmp(centry->name, ".") != 0 ||
222			    centry->type != F_DIR)
223				mtree_err(
224				    "root node must be the directory `.'");
225			last = root = centry;
226			root->parent = root;
227		} else if (pathparent != NULL) {
228				/*
229				 * full path entry
230				 */
231			centry->parent = pathparent;
232			cur = pathparent->child;
233			if (cur == NULL) {
234				pathparent->child = centry;
235				last = centry;
236			} else {
237				for (; cur != NULL; cur = cur->next) {
238					if (strcmp(cur->name, centry->name)
239					    == 0) {
240						/* existing entry; replace */
241						replacenode(cur, centry);
242						break;
243					}
244					if (cur->next == NULL) {
245						/* last entry; add new */
246						cur->next = centry;
247						centry->prev = cur;
248						break;
249					}
250				}
251				last = cur;
252				while (last->next != NULL)
253					last = last->next;
254			}
255		} else if (strcmp(centry->name, ".") == 0) {
256				/*
257				 * duplicate "." entry; always replace
258				 */
259			replacenode(root, centry);
260		} else if (last->type == F_DIR && !(last->flags & F_DONE)) {
261				/*
262				 * new relative child
263				 * (no duplicate check)
264				 */
265			centry->parent = last;
266			last = last->child = centry;
267		} else {
268				/*
269				 * relative entry, up one directory
270				 * (no duplicate check)
271				 */
272			centry->parent = last->parent;
273			centry->prev = last;
274			last = last->next = centry;
275		}
276	}
277	return (root);
278}
279
280void
281free_nodes(NODE *root)
282{
283	NODE	*cur, *next;
284
285	if (root == NULL)
286		return;
287
288	next = NULL;
289	for (cur = root; cur != NULL; cur = next) {
290		next = cur->next;
291		free_nodes(cur->child);
292		REPLACEPTR(cur->slink, NULL);
293		REPLACEPTR(cur->md5digest, NULL);
294		REPLACEPTR(cur->rmd160digest, NULL);
295		REPLACEPTR(cur->sha1digest, NULL);
296		REPLACEPTR(cur->tags, NULL);
297		REPLACEPTR(cur, NULL);
298	}
299}
300
301/*
302 * dump_nodes --
303 *	dump the NODEs from `cur', based in the directory `dir'.
304 *	if pathlast is none zero, print the path last, otherwise print
305 *	it first.
306 */
307void
308dump_nodes(const char *dir, NODE *root, int pathlast)
309{
310	NODE	*cur;
311	char	path[MAXPATHLEN];
312	const char *name;
313
314	for (cur = root; cur != NULL; cur = cur->next) {
315		if (cur->type != F_DIR && !matchtags(cur))
316			continue;
317
318		if (snprintf(path, sizeof(path), "%s%s%s",
319		    dir, *dir ? "/" : "", cur->name)
320		    >= sizeof(path))
321			mtree_err("Pathname too long.");
322
323		if (!pathlast)
324			printf("%s ", vispath(path));
325
326#define MATCHFLAG(f)	((keys & (f)) && (cur->flags & (f)))
327		if (MATCHFLAG(F_TYPE))
328			printf("type=%s ", nodetype(cur->type));
329		if (MATCHFLAG(F_UID | F_UNAME)) {
330			if (keys & F_UNAME &&
331			    (name = user_from_uid(cur->st_uid, 1)) != NULL)
332				printf("uname=%s ", name);
333			else
334				printf("uid=%u ", cur->st_uid);
335		}
336		if (MATCHFLAG(F_GID | F_GNAME)) {
337			if (keys & F_GNAME &&
338			    (name = group_from_gid(cur->st_gid, 1)) != NULL)
339				printf("gname=%s ", name);
340			else
341				printf("gid=%u ", cur->st_gid);
342		}
343		if (MATCHFLAG(F_MODE))
344			printf("mode=%#o ", cur->st_mode);
345		if (MATCHFLAG(F_DEV) &&
346		    (cur->type == F_BLOCK || cur->type == F_CHAR))
347			printf("device=%#x ", cur->st_rdev);
348		if (MATCHFLAG(F_NLINK))
349			printf("nlink=%d ", cur->st_nlink);
350		if (MATCHFLAG(F_SLINK))
351			printf("link=%s ", vispath(cur->slink));
352		if (MATCHFLAG(F_SIZE))
353			printf("size=%lld ", (long long)cur->st_size);
354		if (MATCHFLAG(F_TIME))
355			printf("time=%ld.%ld ", (long)cur->st_mtimespec.tv_sec,
356			    cur->st_mtimespec.tv_nsec);
357		if (MATCHFLAG(F_CKSUM))
358			printf("cksum=%lu ", cur->cksum);
359		if (MATCHFLAG(F_MD5))
360			printf("md5=%s ", cur->md5digest);
361		if (MATCHFLAG(F_RMD160))
362			printf("rmd160=%s ", cur->rmd160digest);
363		if (MATCHFLAG(F_SHA1))
364			printf("sha1=%s ", cur->sha1digest);
365		if (MATCHFLAG(F_FLAGS))
366			printf("flags=%s ",
367			    flags_to_string(cur->st_flags, "none"));
368		if (MATCHFLAG(F_IGN))
369			printf("ignore ");
370		if (MATCHFLAG(F_OPT))
371			printf("optional ");
372		if (MATCHFLAG(F_TAGS))
373			printf("tags=%s ", cur->tags);
374		puts(pathlast ? vispath(path) : "");
375
376		if (cur->child)
377			dump_nodes(path, cur->child, pathlast);
378	}
379}
380
381/*
382 * vispath --
383 *	strsvis(3) encodes path, which must not be longer than MAXPATHLEN
384 *	characters long, and returns a pointer to a static buffer containing
385 *	the result.
386 */
387char *
388vispath(const char *path)
389{
390	const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
391	static char pathbuf[4*MAXPATHLEN + 1];
392
393	strsvis(pathbuf, path, VIS_CSTYLE, extra);
394	return(pathbuf);
395}
396
397
398static dev_t
399parsedev(char *arg)
400{
401#define MAX_PACK_ARGS	3
402	u_long	numbers[MAX_PACK_ARGS];
403	char	*p, *ep, *dev;
404	int	argc;
405	pack_t	*pack;
406	dev_t	result;
407	const char *error = NULL;
408
409	if ((dev = strchr(arg, ',')) != NULL) {
410		*dev++='\0';
411		if ((pack = pack_find(arg)) == NULL)
412			mtree_err("unknown format `%s'", arg);
413		argc = 0;
414		while ((p = strsep(&dev, ",")) != NULL) {
415			if (*p == '\0')
416				mtree_err("missing number");
417			numbers[argc++] = strtoul(p, &ep, 0);
418			if (*ep != '\0')
419				mtree_err("invalid number `%s'",
420				    p);
421			if (argc > MAX_PACK_ARGS)
422				mtree_err("too many arguments");
423		}
424		if (argc < 2)
425			mtree_err("not enough arguments");
426		result = (*pack)(argc, numbers, &error);
427		if (error != NULL)
428			mtree_err(error);
429	} else {
430		result = (dev_t)strtoul(arg, &ep, 0);
431		if (*ep != '\0')
432			mtree_err("invalid device `%s'", arg);
433	}
434	return (result);
435}
436
437static void
438replacenode(NODE *cur, NODE *new)
439{
440
441#define REPLACE(x)	cur->x = new->x
442#define REPLACESTR(x)	REPLACEPTR(cur->x,new->x)
443
444	if (cur->type != new->type) {
445		if (mtree_Mflag) {
446				/*
447				 * merge entries with different types; we
448				 * don't want children retained in this case.
449				 */
450			REPLACE(type);
451			free_nodes(cur->child);
452			cur->child = NULL;
453		} else {
454			mtree_err(
455			    "existing entry for `%s', type `%s'"
456			    " does not match type `%s'",
457			    cur->name, nodetype(cur->type),
458			    nodetype(new->type));
459		}
460	}
461
462	REPLACE(st_size);
463	REPLACE(st_mtimespec);
464	REPLACESTR(slink);
465	if (cur->slink != NULL) {
466		if ((cur->slink = strdup(new->slink)) == NULL)
467			mtree_err("memory allocation error");
468		if (strunvis(cur->slink, new->slink) == -1)
469			mtree_err("strunvis failed on `%s'", new->slink);
470		free(new->slink);
471	}
472	REPLACE(st_uid);
473	REPLACE(st_gid);
474	REPLACE(st_mode);
475	REPLACE(st_rdev);
476	REPLACE(st_flags);
477	REPLACE(st_nlink);
478	REPLACE(cksum);
479	REPLACESTR(md5digest);
480	REPLACESTR(rmd160digest);
481	REPLACESTR(sha1digest);
482	REPLACESTR(tags);
483	REPLACE(lineno);
484	REPLACE(flags);
485	free(new);
486}
487
488static void
489set(char *t, NODE *ip)
490{
491	int	type, value, len;
492	gid_t	gid;
493	uid_t	uid;
494	char	*kw, *val, *md, *ep;
495	void	*m;
496
497	val = NULL;
498	while ((kw = strsep(&t, "= \t")) != NULL) {
499		if (*kw == '\0')
500			continue;
501		if (strcmp(kw, "all") == 0)
502			mtree_err("invalid keyword `all'");
503		ip->flags |= type = parsekey(kw, &value);
504		if (value) {
505			while ((val = strsep(&t, " \t")) != NULL &&
506			    *val == '\0')
507				continue;
508			if (val == NULL)
509				mtree_err("missing value");
510		}
511		switch(type) {
512		case F_CKSUM:
513			ip->cksum = strtoul(val, &ep, 10);
514			if (*ep)
515				mtree_err("invalid checksum `%s'", val);
516			break;
517		case F_DEV:
518			ip->st_rdev = parsedev(val);
519			break;
520		case F_FLAGS:
521			if (strcmp("none", val) == 0)
522				ip->st_flags = 0;
523			else if (string_to_flags(&val, &ip->st_flags, NULL)
524			    != 0)
525				mtree_err("invalid flag `%s'", val);
526			break;
527		case F_GID:
528			ip->st_gid = (gid_t)strtoul(val, &ep, 10);
529			if (*ep)
530				mtree_err("invalid gid `%s'", val);
531			break;
532		case F_GNAME:
533			if (mtree_Wflag)	/* don't parse if whacking */
534				break;
535			if (gid_from_group(val, &gid) == -1)
536				mtree_err("unknown group `%s'", val);
537			ip->st_gid = gid;
538			break;
539		case F_IGN:
540			/* just set flag bit */
541			break;
542		case F_MD5:
543			if (val[0]=='0' && val[1]=='x')
544				md=&val[2];
545			else
546				md=val;
547			if ((ip->md5digest = strdup(md)) == NULL)
548				mtree_err("memory allocation error");
549			break;
550		case F_MODE:
551			if ((m = setmode(val)) == NULL)
552				mtree_err("invalid file mode `%s'", val);
553			ip->st_mode = getmode(m, 0);
554			free(m);
555			break;
556		case F_NLINK:
557			ip->st_nlink = (nlink_t)strtoul(val, &ep, 10);
558			if (*ep)
559				mtree_err("invalid link count `%s'", val);
560			break;
561		case F_OPT:
562			/* just set flag bit */
563			break;
564		case F_RMD160:
565			if (val[0]=='0' && val[1]=='x')
566				md=&val[2];
567			else
568				md=val;
569			if ((ip->rmd160digest = strdup(md)) == NULL)
570				mtree_err("memory allocation error");
571			break;
572		case F_SHA1:
573			if (val[0]=='0' && val[1]=='x')
574				md=&val[2];
575			else
576				md=val;
577			if ((ip->sha1digest = strdup(md)) == NULL)
578				mtree_err("memory allocation error");
579			break;
580		case F_SIZE:
581			ip->st_size = (off_t)strtoll(val, &ep, 10);
582			if (*ep)
583				mtree_err("invalid size `%s'", val);
584			break;
585		case F_SLINK:
586			if ((ip->slink = strdup(val)) == NULL)
587				mtree_err("memory allocation error");
588			if (strunvis(ip->slink, val) == -1)
589				mtree_err("strunvis failed on `%s'", val);
590			break;
591		case F_TAGS:
592			len = strlen(val) + 3;	/* "," + str + ",\0" */
593			if ((ip->tags = malloc(len)) == NULL)
594				mtree_err("memory allocation error");
595			snprintf(ip->tags, len, ",%s,", val);
596			break;
597		case F_TIME:
598			ip->st_mtimespec.tv_sec =
599			    (time_t)strtoul(val, &ep, 10);
600			if (*ep != '.')
601				mtree_err("invalid time `%s'", val);
602			val = ep + 1;
603			ip->st_mtimespec.tv_nsec = strtoul(val, &ep, 10);
604			if (*ep)
605				mtree_err("invalid time `%s'", val);
606			break;
607		case F_TYPE:
608			ip->type = parsetype(val);
609			break;
610		case F_UID:
611			ip->st_uid = (uid_t)strtoul(val, &ep, 10);
612			if (*ep)
613				mtree_err("invalid uid `%s'", val);
614			break;
615		case F_UNAME:
616			if (mtree_Wflag)	/* don't parse if whacking */
617				break;
618			if (uid_from_user(val, &uid) == -1)
619				mtree_err("unknown user `%s'", val);
620			ip->st_uid = uid;
621			break;
622		default:
623			mtree_err(
624			    "set(): unsupported key type 0x%x (INTERNAL ERROR)",
625			    type);
626			/* NOTREACHED */
627		}
628	}
629}
630
631static void
632unset(char *t, NODE *ip)
633{
634	char *p;
635
636	while ((p = strsep(&t, " \t")) != NULL) {
637		if (*p == '\0')
638			continue;
639		ip->flags &= ~parsekey(p, NULL);
640	}
641}
642