xref: /netbsd-src/bin/pax/pat_rep.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: pat_rep.c,v 1.23 2005/01/23 06:19:03 jmc Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992 Keith Muller.
5  * Copyright (c) 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Keith Muller of the University of California, San Diego.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #if HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
38 #endif
39 
40 #include <sys/cdefs.h>
41 #if !defined(lint)
42 #if 0
43 static char sccsid[] = "@(#)pat_rep.c	8.2 (Berkeley) 4/18/94";
44 #else
45 __RCSID("$NetBSD: pat_rep.c,v 1.23 2005/01/23 06:19:03 jmc Exp $");
46 #endif
47 #endif /* not lint */
48 
49 #include <sys/types.h>
50 #include <sys/time.h>
51 #include <sys/stat.h>
52 #include <sys/param.h>
53 #include <stdio.h>
54 #include <ctype.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <stdlib.h>
58 #ifdef NET2_REGEX
59 #include <regexp.h>
60 #else
61 #include <regex.h>
62 #endif
63 #include "pax.h"
64 #include "pat_rep.h"
65 #include "extern.h"
66 
67 /*
68  * routines to handle pattern matching, name modification (regular expression
69  * substitution and interactive renames), and destination name modification for
70  * copy (-rw). Both file name and link names are adjusted as required in these
71  * routines.
72  */
73 
74 #define MAXSUBEXP	10		/* max subexpressions, DO NOT CHANGE */
75 static PATTERN *pathead = NULL;		/* file pattern match list head */
76 static PATTERN *pattail = NULL;		/* file pattern match list tail */
77 static REPLACE *rephead = NULL;		/* replacement string list head */
78 static REPLACE *reptail = NULL;		/* replacement string list tail */
79 
80 static int rep_name(char *, size_t, int *, int);
81 static int tty_rename(ARCHD *);
82 static int fix_path(char *, int *, char *, int);
83 static int fn_match(char *, char *, char **);
84 static char * range_match(char *, int);
85 static int checkdotdot(const char *);
86 #ifdef NET2_REGEX
87 static int resub(regexp *, char *, char *, char *);
88 #else
89 static int resub(regex_t *, regmatch_t *, char *, char *, char *, char *);
90 #endif
91 
92 /*
93  * rep_add()
94  *	parses the -s replacement string; compiles the regular expression
95  *	and stores the compiled value and it's replacement string together in
96  *	replacement string list. Input to this function is of the form:
97  *		/old/new/pg
98  *	The first char in the string specifies the delimiter used by this
99  *	replacement string. "Old" is a regular expression in "ed" format which
100  *	is compiled by regcomp() and is applied to filenames. "new" is the
101  *	substitution string; p and g are options flags for printing and global
102  *	replacement (over the single filename)
103  * Return:
104  *	0 if a proper replacement string and regular expression was added to
105  *	the list of replacement patterns; -1 otherwise.
106  */
107 
108 int
109 rep_add(char *str)
110 {
111 	char *pt1;
112 	char *pt2;
113 	REPLACE *rep;
114 #ifdef NET2_REGEX
115 	static const char rebuf[] = "Error";
116 #else
117 	int res;
118 	char rebuf[BUFSIZ];
119 #endif
120 
121 	/*
122 	 * throw out the bad parameters
123 	 */
124 	if ((str == NULL) || (*str == '\0')) {
125 		tty_warn(1, "Empty replacement string");
126 		return(-1);
127 	}
128 
129 	/*
130 	 * first character in the string specifies what the delimiter is for
131 	 * this expression.
132 	 */
133 	for (pt1 = str+1; *pt1; pt1++) {
134 		if (*pt1 == '\\') {
135 			pt1++;
136 			continue;
137 		}
138 		if (*pt1 == *str)
139 			break;
140 	}
141 	if (*pt1 == 0) {
142 		tty_warn(1, "Invalid replacement string %s", str);
143 		return(-1);
144 	}
145 
146 	/*
147 	 * allocate space for the node that handles this replacement pattern
148 	 * and split out the regular expression and try to compile it
149 	 */
150 	if ((rep = (REPLACE *)malloc(sizeof(REPLACE))) == NULL) {
151 		tty_warn(1, "Unable to allocate memory for replacement string");
152 		return(-1);
153 	}
154 
155 	*pt1 = '\0';
156 #ifdef NET2_REGEX
157 	if ((rep->rcmp = regcomp(str+1)) == NULL) {
158 #else
159 	if ((res = regcomp(&(rep->rcmp), str+1, 0)) != 0) {
160 		regerror(res, &(rep->rcmp), rebuf, sizeof(rebuf));
161 #endif
162 		tty_warn(1, "%s while compiling regular expression %s", rebuf,
163 		    str);
164 		(void)free((char *)rep);
165 		return(-1);
166 	}
167 
168 	/*
169 	 * put the delimiter back in case we need an error message and
170 	 * locate the delimiter at the end of the replacement string
171 	 * we then point the node at the new substitution string
172 	 */
173 	*pt1++ = *str;
174 	for (pt2 = pt1; *pt2; pt2++) {
175 		if (*pt2 == '\\') {
176 			pt2++;
177 			continue;
178 		}
179 		if (*pt2 == *str)
180 			break;
181 	}
182 	if (*pt2 == 0) {
183 #ifdef NET2_REGEX
184 		(void)free((char *)rep->rcmp);
185 #else
186 		regfree(&(rep->rcmp));
187 #endif
188 		(void)free((char *)rep);
189 		tty_warn(1, "Invalid replacement string %s", str);
190 		return(-1);
191 	}
192 
193 	*pt2 = '\0';
194 
195 	/* Make sure to dup replacement, who knows where it came from! */
196 	if ((rep->nstr = strdup(pt1)) == NULL) {
197 #ifdef NET2_REGEX
198 		(void)free((char *)rep->rcmp);
199 #else
200 		regfree(&(rep->rcmp));
201 #endif
202 		(void)free((char *)rep);
203 		tty_warn(1, "Unable to allocate memory for replacement string");
204 		return(-1);
205 	}
206 
207 	pt1 = pt2++;
208 	rep->flgs = 0;
209 
210 	/*
211 	 * set the options if any
212 	 */
213 	while (*pt2 != '\0') {
214 		switch(*pt2) {
215 		case 'g':
216 		case 'G':
217 			rep->flgs  |= GLOB;
218 			break;
219 		case 'p':
220 		case 'P':
221 			rep->flgs  |= PRNT;
222 			break;
223 		default:
224 #ifdef NET2_REGEX
225 			(void)free((char *)rep->rcmp);
226 #else
227 			regfree(&(rep->rcmp));
228 #endif
229 			(void)free((char *)rep);
230 			*pt1 = *str;
231 			tty_warn(1, "Invalid replacement string option %s",
232 			    str);
233 			return(-1);
234 		}
235 		++pt2;
236 	}
237 
238 	/*
239 	 * all done, link it in at the end
240 	 */
241 	rep->fow = NULL;
242 	if (rephead == NULL) {
243 		reptail = rephead = rep;
244 		return(0);
245 	}
246 	reptail->fow = rep;
247 	reptail = rep;
248 	return(0);
249 }
250 
251 /*
252  * pat_add()
253  *	add a pattern match to the pattern match list. Pattern matches are used
254  *	to select which archive members are extracted. (They appear as
255  *	arguments to pax in the list and read modes). If no patterns are
256  *	supplied to pax, all members in the archive will be selected (and the
257  *	pattern match list is empty).
258  *
259  * Return:
260  *	0 if the pattern was added to the list, -1 otherwise
261  */
262 
263 int
264 pat_add(char *str, char *chdn)
265 {
266 	PATTERN *pt;
267 
268 	/*
269 	 * throw out the junk
270 	 */
271 	if ((str == NULL) || (*str == '\0')) {
272 		tty_warn(1, "Empty pattern string");
273 		return(-1);
274 	}
275 
276 	/*
277 	 * allocate space for the pattern and store the pattern. the pattern is
278 	 * part of argv so do not bother to copy it, just point at it. Add the
279 	 * node to the end of the pattern list
280 	 */
281 	if ((pt = (PATTERN *)malloc(sizeof(PATTERN))) == NULL) {
282 		tty_warn(1, "Unable to allocate memory for pattern string");
283 		return(-1);
284 	}
285 
286 	pt->pstr = str;
287 	pt->pend = NULL;
288 	pt->plen = strlen(str);
289 	pt->fow = NULL;
290 	pt->flgs = 0;
291 	pt->chdname = chdn;
292 	if (pathead == NULL) {
293 		pattail = pathead = pt;
294 		return(0);
295 	}
296 	pattail->fow = pt;
297 	pattail = pt;
298 	return(0);
299 }
300 
301 /*
302  * pat_chk()
303  *	complain if any the user supplied pattern did not result in a match to
304  *	a selected archive member.
305  */
306 
307 void
308 pat_chk(void)
309 {
310 	PATTERN *pt;
311 	int wban = 0;
312 
313 	/*
314 	 * walk down the list checking the flags to make sure MTCH was set,
315 	 * if not complain
316 	 */
317 	for (pt = pathead; pt != NULL; pt = pt->fow) {
318 		if (pt->flgs & MTCH)
319 			continue;
320 		if (!wban) {
321 			tty_warn(1, "WARNING! These patterns were not matched:");
322 			++wban;
323 		}
324 		(void)fprintf(stderr, "%s\n", pt->pstr);
325 	}
326 }
327 
328 /*
329  * pat_sel()
330  *	the archive member which matches a pattern was selected. Mark the
331  *	pattern as having selected an archive member. arcn->pat points at the
332  *	pattern that was matched. arcn->pat is set in pat_match()
333  *
334  *	NOTE: When the -c option is used, we are called when there was no match
335  *	by pat_match() (that means we did match before the inverted sense of
336  *	the logic). Now this seems really strange at first, but with -c we
337  *	need to keep track of those patterns that cause a archive member to NOT
338  *	be selected (it found an archive member with a specified pattern)
339  * Return:
340  *	0 if the pattern pointed at by arcn->pat was tagged as creating a
341  *	match, -1 otherwise.
342  */
343 
344 int
345 pat_sel(ARCHD *arcn)
346 {
347 	PATTERN *pt;
348 	PATTERN **ppt;
349 	int len;
350 
351 	/*
352 	 * if no patterns just return
353 	 */
354 	if ((pathead == NULL) || ((pt = arcn->pat) == NULL))
355 		return(0);
356 
357 	/*
358 	 * when we are NOT limited to a single match per pattern mark the
359 	 * pattern and return
360 	 */
361 	if (!nflag) {
362 		pt->flgs |= MTCH;
363 		return(0);
364 	}
365 
366 	/*
367 	 * we reach this point only when we allow a single selected match per
368 	 * pattern, if the pattern matches a directory and we do not have -d
369 	 * (dflag) we are done with this pattern. We may also be handed a file
370 	 * in the subtree of a directory. in that case when we are operating
371 	 * with -d, this pattern was already selected and we are done
372 	 */
373 	if (pt->flgs & DIR_MTCH)
374 		return(0);
375 
376 	if (!dflag && ((pt->pend != NULL) || (arcn->type == PAX_DIR))) {
377 		/*
378 		 * ok we matched a directory and we are allowing
379 		 * subtree matches but because of the -n only its children will
380 		 * match. This is tagged as a DIR_MTCH type.
381 		 * WATCH IT, the code assumes that pt->pend points
382 		 * into arcn->name and arcn->name has not been modified.
383 		 * If not we will have a big mess. Yup this is another kludge
384 		 */
385 
386 		/*
387 		 * if this was a prefix match, remove trailing part of path
388 		 * so we can copy it. Future matches will be exact prefix match
389 		 */
390 		if (pt->pend != NULL)
391 			*pt->pend = '\0';
392 
393 		if ((pt->pstr = strdup(arcn->name)) == NULL) {
394 			tty_warn(1, "Pattern select out of memory");
395 			if (pt->pend != NULL)
396 				*pt->pend = '/';
397 			pt->pend = NULL;
398 			return(-1);
399 		}
400 
401 		/*
402 		 * put the trailing / back in the source string
403 		 */
404 		if (pt->pend != NULL) {
405 			*pt->pend = '/';
406 			pt->pend = NULL;
407 		}
408 		pt->plen = strlen(pt->pstr);
409 
410 		/*
411 		 * strip off any trailing /, this should really never happen
412 		 */
413 		len = pt->plen - 1;
414 		if (*(pt->pstr + len) == '/') {
415 			*(pt->pstr + len) = '\0';
416 			pt->plen = len;
417 		}
418 		pt->flgs = DIR_MTCH | MTCH;
419 		arcn->pat = pt;
420 		return(0);
421 	}
422 
423 	/*
424 	 * we are then done with this pattern, so we delete it from the list
425 	 * because it can never be used for another match.
426 	 * Seems kind of strange to do for a -c, but the pax spec is really
427 	 * vague on the interaction of -c, -n, and -d. We assume that when -c
428 	 * and the pattern rejects a member (i.e. it matched it) it is done.
429 	 * In effect we place the order of the flags as having -c last.
430 	 */
431 	pt = pathead;
432 	ppt = &pathead;
433 	while ((pt != NULL) && (pt != arcn->pat)) {
434 		ppt = &(pt->fow);
435 		pt = pt->fow;
436 	}
437 
438 	if (pt == NULL) {
439 		/*
440 		 * should never happen....
441 		 */
442 		tty_warn(1, "Pattern list inconsistant");
443 		return(-1);
444 	}
445 	*ppt = pt->fow;
446 	(void)free((char *)pt);
447 	arcn->pat = NULL;
448 	return(0);
449 }
450 
451 /*
452  * pat_match()
453  *	see if this archive member matches any supplied pattern, if a match
454  *	is found, arcn->pat is set to point at the potential pattern. Later if
455  *	this archive member is "selected" we process and mark the pattern as
456  *	one which matched a selected archive member (see pat_sel())
457  * Return:
458  *	0 if this archive member should be processed, 1 if it should be
459  *	skipped and -1 if we are done with all patterns (and pax should quit
460  *	looking for more members)
461  */
462 
463 int
464 pat_match(ARCHD *arcn)
465 {
466 	PATTERN *pt;
467 
468 	arcn->pat = NULL;
469 
470 	/*
471 	 * if there are no more patterns and we have -n (and not -c) we are
472 	 * done. otherwise with no patterns to match, matches all
473 	 */
474 	if (pathead == NULL) {
475 		if (nflag && !cflag)
476 			return(-1);
477 		return(0);
478 	}
479 
480 	/*
481 	 * have to search down the list one at a time looking for a match.
482 	 */
483 	pt = pathead;
484 	while (pt != NULL) {
485 		/*
486 		 * check for a file name match unless we have DIR_MTCH set in
487 		 * this pattern then we want a prefix match
488 		 */
489 		if (pt->flgs & DIR_MTCH) {
490 			/*
491 			 * this pattern was matched before to a directory
492 			 * as we must have -n set for this (but not -d). We can
493 			 * only match CHILDREN of that directory so we must use
494 			 * an exact prefix match (no wildcards).
495 			 */
496 			if ((arcn->name[pt->plen] == '/') &&
497 			    (strncmp(pt->pstr, arcn->name, pt->plen) == 0))
498 				break;
499 		} else if (fn_match(pt->pstr, arcn->name, &pt->pend) == 0)
500 			break;
501 		pt = pt->fow;
502 	}
503 
504 	/*
505 	 * return the result, remember that cflag (-c) inverts the sense of a
506 	 * match
507 	 */
508 	if (pt == NULL)
509 		return(cflag ? 0 : 1);
510 
511 	/*
512 	 * we had a match, now when we invert the sense (-c) we reject this
513 	 * member. However we have to tag the pattern a being successful, (in a
514 	 * match, not in selecting a archive member) so we call pat_sel() here.
515 	 */
516 	arcn->pat = pt;
517 	if (!cflag)
518 		return(0);
519 
520 	if (pat_sel(arcn) < 0)
521 		return(-1);
522 	arcn->pat = NULL;
523 	return(1);
524 }
525 
526 /*
527  * fn_match()
528  * Return:
529  *	0 if this archive member should be processed, 1 if it should be
530  *	skipped and -1 if we are done with all patterns (and pax should quit
531  *	looking for more members)
532  *	Note: *pend may be changed to show where the prefix ends.
533  */
534 
535 static int
536 fn_match(char *pattern, char *string, char **pend)
537 {
538 	char c;
539 	char test;
540 
541 	*pend = NULL;
542 	for (;;) {
543 		switch (c = *pattern++) {
544 		case '\0':
545 			/*
546 			 * Ok we found an exact match
547 			 */
548 			if (*string == '\0')
549 				return(0);
550 
551 			/*
552 			 * Check if it is a prefix match
553 			 */
554 			if ((dflag == 1) || (*string != '/'))
555 				return(-1);
556 
557 			/*
558 			 * It is a prefix match, remember where the trailing
559 			 * / is located
560 			 */
561 			*pend = string;
562 			return(0);
563 		case '?':
564 			if ((test = *string++) == '\0')
565 				return (-1);
566 			break;
567 		case '*':
568 			c = *pattern;
569 			/*
570 			 * Collapse multiple *'s.
571 			 */
572 			while (c == '*')
573 				c = *++pattern;
574 
575 			/*
576 			 * Optimized hack for pattern with a * at the end
577 			 */
578 			if (c == '\0')
579 				return (0);
580 
581 			/*
582 			 * General case, use recursion.
583 			 */
584 			while ((test = *string) != '\0') {
585 				if (!fn_match(pattern, string, pend))
586 					return (0);
587 				++string;
588 			}
589 			return (-1);
590 		case '[':
591 			/*
592 			 * range match
593 			 */
594 			if (((test = *string++) == '\0') ||
595 			    ((pattern = range_match(pattern, test)) == NULL))
596 				return (-1);
597 			break;
598 		case '\\':
599 		default:
600 			if (c != *string++)
601 				return (-1);
602 			break;
603 		}
604 	}
605 	/* NOTREACHED */
606 }
607 
608 static char *
609 range_match(char *pattern, int test)
610 {
611 	char c;
612 	char c2;
613 	int negate;
614 	int ok = 0;
615 
616 	if ((negate = (*pattern == '!')) != 0)
617 		++pattern;
618 
619 	while ((c = *pattern++) != ']') {
620 		/*
621 		 * Illegal pattern
622 		 */
623 		if (c == '\0')
624 			return (NULL);
625 
626 		if ((*pattern == '-') && ((c2 = pattern[1]) != '\0') &&
627 		    (c2 != ']')) {
628 			if ((c <= test) && (test <= c2))
629 				ok = 1;
630 			pattern += 2;
631 		} else if (c == test)
632 			ok = 1;
633 	}
634 	return (ok == negate ? NULL : pattern);
635 }
636 
637 /*
638  * mod_name()
639  *	modify a selected file name. first attempt to apply replacement string
640  *	expressions, then apply interactive file rename. We apply replacement
641  *	string expressions to both filenames and file links (if we didn't the
642  *	links would point to the wrong place, and we could never be able to
643  *	move an archive that has a file link in it). When we rename files
644  *	interactively, we store that mapping (old name to user input name) so
645  *	if we spot any file links to the old file name in the future, we will
646  *	know exactly how to fix the file link.
647  * Return:
648  *	0 continue to  process file, 1 skip this file, -1 pax is finished
649  */
650 
651 int
652 mod_name(ARCHD *arcn)
653 {
654 	int res = 0;
655 
656 	if (secure) {
657 		if (checkdotdot(arcn->name)) {
658 			tty_warn(0, "Ignoring file containing `..' (%s)",
659 				arcn->name);
660 			return 1;
661 		}
662 #ifdef notdef
663 		if (checkdotdot(arcn->ln_name)) {
664 			tty_warn(0, "Ignoring link containing `..' (%s)",
665 				arcn->ln_name);
666 			return 1;
667 		}
668 #endif
669 	}
670 
671 	/*
672 	 * IMPORTANT: We have a problem. what do we do with symlinks?
673 	 * Modifying a hard link name makes sense, as we know the file it
674 	 * points at should have been seen already in the archive (and if it
675 	 * wasn't seen because of a read error or a bad archive, we lose
676 	 * anyway). But there are no such requirements for symlinks. On one
677 	 * hand the symlink that refers to a file in the archive will have to
678 	 * be modified to so it will still work at its new location in the
679 	 * file system. On the other hand a symlink that points elsewhere (and
680 	 * should continue to do so) should not be modified. There is clearly
681 	 * no perfect solution here. So we handle them like hardlinks. Clearly
682 	 * a replacement made by the interactive rename mapping is very likely
683 	 * to be correct since it applies to a single file and is an exact
684 	 * match. The regular expression replacements are a little harder to
685 	 * justify though. We claim that the symlink name is only likely
686 	 * to be replaced when it points within the file tree being moved and
687 	 * in that case it should be modified. what we really need to do is to
688 	 * call an oracle here. :)
689 	 */
690 	if (rephead != NULL) {
691 		/*
692 		 * we have replacement strings, modify the name and the link
693 		 * name if any.
694 		 */
695 		if ((res = rep_name(arcn->name, sizeof(arcn->name),
696 			&(arcn->nlen), 1)) != 0)
697 			return(res);
698 
699 		if (((arcn->type == PAX_SLK) || (arcn->type == PAX_HLK) ||
700 		    (arcn->type == PAX_HRG)) &&
701 		    ((res = rep_name(arcn->ln_name, sizeof(arcn->ln_name),
702 			&(arcn->ln_nlen), 0)) != 0))
703 			return(res);
704 	}
705 
706 	if (iflag) {
707 		/*
708 		 * perform interactive file rename, then map the link if any
709 		 */
710 		if ((res = tty_rename(arcn)) != 0)
711 			return(res);
712 		if ((arcn->type == PAX_SLK) || (arcn->type == PAX_HLK) ||
713 		    (arcn->type == PAX_HRG))
714 			sub_name(arcn->ln_name, &(arcn->ln_nlen), sizeof(arcn->ln_name));
715 	}
716 
717 	/*
718 	 * Strip off leading '/' if appropriate.
719 	 * Currently, this option is only set for the tar format.
720 	 */
721 	if (rmleadslash && arcn->name[0] == '/') {
722 		if (arcn->name[1] == '\0') {
723 			arcn->name[0] = '.';
724 		} else {
725 			(void)memmove(arcn->name, &arcn->name[1],
726 			    strlen(arcn->name));
727 			arcn->nlen--;
728 		}
729 		if (rmleadslash < 2) {
730 			rmleadslash = 2;
731 			tty_warn(0, "Removing leading / from absolute path names in the archive");
732 		}
733 	}
734 	if (rmleadslash && arcn->ln_name[0] == '/' &&
735 	    (arcn->type == PAX_HLK || arcn->type == PAX_HRG)) {
736 		if (arcn->ln_name[1] == '\0') {
737 			arcn->ln_name[0] = '.';
738 		} else {
739 			(void)memmove(arcn->ln_name, &arcn->ln_name[1],
740 			    strlen(arcn->ln_name));
741 			arcn->ln_nlen--;
742 		}
743 		if (rmleadslash < 2) {
744 			rmleadslash = 2;
745 			tty_warn(0, "Removing leading / from absolute path names in the archive");
746 		}
747 	}
748 
749 	return(res);
750 }
751 
752 /*
753  * tty_rename()
754  *	Prompt the user for a replacement file name. A "." keeps the old name,
755  *	a empty line skips the file, and an EOF on reading the tty, will cause
756  *	pax to stop processing and exit. Otherwise the file name input, replaces
757  *	the old one.
758  * Return:
759  *	0 process this file, 1 skip this file, -1 we need to exit pax
760  */
761 
762 static int
763 tty_rename(ARCHD *arcn)
764 {
765 	char tmpname[PAXPATHLEN+2];
766 	int res;
767 
768 	/*
769 	 * prompt user for the replacement name for a file, keep trying until
770 	 * we get some reasonable input. Archives may have more than one file
771 	 * on them with the same name (from updates etc). We print verbose info
772 	 * on the file so the user knows what is up.
773 	 */
774 	tty_prnt("\nATTENTION: %s interactive file rename operation.\n", argv0);
775 
776 	for (;;) {
777 		ls_tty(arcn);
778 		tty_prnt("Input new name, or a \".\" to keep the old name, ");
779 		tty_prnt("or a \"return\" to skip this file.\n");
780 		tty_prnt("Input > ");
781 		if (tty_read(tmpname, sizeof(tmpname)) < 0)
782 			return(-1);
783 		if (strcmp(tmpname, "..") == 0) {
784 			tty_prnt("Try again, illegal file name: ..\n");
785 			continue;
786 		}
787 		if (strlen(tmpname) > PAXPATHLEN) {
788 			tty_prnt("Try again, file name too long\n");
789 			continue;
790 		}
791 		break;
792 	}
793 
794 	/*
795 	 * empty file name, skips this file. a "." leaves it alone
796 	 */
797 	if (tmpname[0] == '\0') {
798 		tty_prnt("Skipping file.\n");
799 		return(1);
800 	}
801 	if ((tmpname[0] == '.') && (tmpname[1] == '\0')) {
802 		tty_prnt("Processing continues, name unchanged.\n");
803 		return(0);
804 	}
805 
806 	/*
807 	 * ok the name changed. We may run into links that point at this
808 	 * file later. we have to remember where the user sent the file
809 	 * in order to repair any links.
810 	 */
811 	tty_prnt("Processing continues, name changed to: %s\n", tmpname);
812 	res = add_name(arcn->name, arcn->nlen, tmpname);
813 	arcn->nlen = strlcpy(arcn->name, tmpname, sizeof(arcn->name));
814 	if (res < 0)
815 		return(-1);
816 	return(0);
817 }
818 
819 /*
820  * set_dest()
821  *	fix up the file name and the link name (if any) so this file will land
822  *	in the destination directory (used during copy() -rw).
823  * Return:
824  *	0 if ok, -1 if failure (name too long)
825  */
826 
827 int
828 set_dest(ARCHD *arcn, char *dest_dir, int dir_len)
829 {
830 	if (fix_path(arcn->name, &(arcn->nlen), dest_dir, dir_len) < 0)
831 		return(-1);
832 
833 	/*
834 	 * It is really hard to deal with symlinks here, we cannot be sure
835 	 * if the name they point was moved (or will be moved). It is best to
836 	 * leave them alone.
837 	 */
838 	if ((arcn->type != PAX_HLK) && (arcn->type != PAX_HRG))
839 		return(0);
840 
841 	if (fix_path(arcn->ln_name, &(arcn->ln_nlen), dest_dir, dir_len) < 0)
842 		return(-1);
843 	return(0);
844 }
845 
846 /*
847  * fix_path
848  *	concatenate dir_name and or_name and store the result in or_name (if
849  *	it fits). This is one ugly function.
850  * Return:
851  *	0 if ok, -1 if the final name is too long
852  */
853 
854 static int
855 fix_path( char *or_name, int *or_len, char *dir_name, int dir_len)
856 {
857 	char *src;
858 	char *dest;
859 	char *start;
860 	int len;
861 
862 	/*
863 	 * we shift the or_name to the right enough to tack in the dir_name
864 	 * at the front. We make sure we have enough space for it all before
865 	 * we start. since dest always ends in a slash, we skip of or_name
866 	 * if it also starts with one.
867 	 */
868 	start = or_name;
869 	src = start + *or_len;
870 	dest = src + dir_len;
871 	if (*start == '/') {
872 		++start;
873 		--dest;
874 	}
875 	if ((len = dest - or_name) > PAXPATHLEN) {
876 		tty_warn(1, "File name %s/%s, too long", dir_name, start);
877 		return(-1);
878 	}
879 	*or_len = len;
880 
881 	/*
882 	 * enough space, shift
883 	 */
884 	while (src >= start)
885 		*dest-- = *src--;
886 	src = dir_name + dir_len - 1;
887 
888 	/*
889 	 * splice in the destination directory name
890 	 */
891 	while (src >= dir_name)
892 		*dest-- = *src--;
893 
894 	*(or_name + len) = '\0';
895 	return(0);
896 }
897 
898 /*
899  * rep_name()
900  *	walk down the list of replacement strings applying each one in order.
901  *	when we find one with a successful substitution, we modify the name
902  *	as specified. if required, we print the results. if the resulting name
903  *	is empty, we will skip this archive member. We use the regexp(3)
904  *	routines (regexp() ought to win a prize as having the most cryptic
905  *	library function manual page).
906  *	--Parameters--
907  *	name is the file name we are going to apply the regular expressions to
908  *	(and may be modified)
909  *	namelen the size of the name buffer.
910  *	nlen is the length of this name (and is modified to hold the length of
911  *	the final string).
912  *	prnt is a flag that says whether to print the final result.
913  * Return:
914  *	0 if substitution was successful, 1 if we are to skip the file (the name
915  *	ended up empty)
916  */
917 
918 static int
919 rep_name(char *name, size_t namelen, int *nlen, int prnt)
920 {
921 	REPLACE *pt;
922 	char *inpt;
923 	char *outpt;
924 	char *endpt;
925 	char *rpt;
926 	int found = 0;
927 	int res;
928 #ifndef NET2_REGEX
929 	regmatch_t pm[MAXSUBEXP];
930 #endif
931 	char nname[PAXPATHLEN+1];	/* final result of all replacements */
932 	char buf1[PAXPATHLEN+1];	/* where we work on the name */
933 
934 	/*
935 	 * copy the name into buf1, where we will work on it. We need to keep
936 	 * the orig string around so we can print out the result of the final
937 	 * replacement. We build up the final result in nname. inpt points at
938 	 * the string we apply the regular expression to. prnt is used to
939 	 * suppress printing when we handle replacements on the link field
940 	 * (the user already saw that substitution go by)
941 	 */
942 	pt = rephead;
943 	(void)strcpy(buf1, name);
944 	inpt = buf1;
945 	outpt = nname;
946 	endpt = outpt + PAXPATHLEN;
947 
948 	/*
949 	 * try each replacement string in order
950 	 */
951 	while (pt != NULL) {
952 		do {
953 			/*
954 			 * check for a successful substitution, if not go to
955 			 * the next pattern, or cleanup if we were global
956 			 */
957 #ifdef NET2_REGEX
958 			if (regexec(pt->rcmp, inpt) == 0)
959 #else
960 			if (regexec(&(pt->rcmp), inpt, MAXSUBEXP, pm, 0) != 0)
961 #endif
962 				break;
963 
964 			/*
965 			 * ok we found one. We have three parts, the prefix
966 			 * which did not match, the section that did and the
967 			 * tail (that also did not match). Copy the prefix to
968 			 * the final output buffer (watching to make sure we
969 			 * do not create a string too long).
970 			 */
971 			found = 1;
972 #ifdef NET2_REGEX
973 			rpt = pt->rcmp->startp[0];
974 #else
975 			rpt = inpt + pm[0].rm_so;
976 #endif
977 
978 			while ((inpt < rpt) && (outpt < endpt))
979 				*outpt++ = *inpt++;
980 			if (outpt == endpt)
981 				break;
982 
983 			/*
984 			 * for the second part (which matched the regular
985 			 * expression) apply the substitution using the
986 			 * replacement string and place it the prefix in the
987 			 * final output. If we have problems, skip it.
988 			 */
989 			if ((res =
990 #ifdef NET2_REGEX
991 			    resub(pt->rcmp,pt->nstr,outpt,endpt)
992 #else
993 			    resub(&(pt->rcmp),pm,pt->nstr,inpt, outpt,endpt)
994 #endif
995 			    ) < 0) {
996 				if (prnt)
997 					tty_warn(1, "Replacement name error %s",
998 					    name);
999 				return(1);
1000 			}
1001 			outpt += res;
1002 
1003 			/*
1004 			 * we set up to look again starting at the first
1005 			 * character in the tail (of the input string right
1006 			 * after the last character matched by the regular
1007 			 * expression (inpt always points at the first char in
1008 			 * the string to process). If we are not doing a global
1009 			 * substitution, we will use inpt to copy the tail to
1010 			 * the final result. Make sure we do not overrun the
1011 			 * output buffer
1012 			 */
1013 #ifdef NET2_REGEX
1014 			inpt = pt->rcmp->endp[0];
1015 #else
1016 			inpt += pm[0].rm_eo - pm[0].rm_so;
1017 #endif
1018 
1019 			if ((outpt == endpt) || (*inpt == '\0'))
1020 				break;
1021 
1022 			/*
1023 			 * if the user wants global we keep trying to
1024 			 * substitute until it fails, then we are done.
1025 			 */
1026 		} while (pt->flgs & GLOB);
1027 
1028 		if (found)
1029 			break;
1030 
1031 		/*
1032 		 * a successful substitution did NOT occur, try the next one
1033 		 */
1034 		pt = pt->fow;
1035 	}
1036 
1037 	if (found) {
1038 		/*
1039 		 * we had a substitution, copy the last tail piece (if there is
1040 		 * room) to the final result
1041 		 */
1042 		while ((outpt < endpt) && (*inpt != '\0'))
1043 			*outpt++ = *inpt++;
1044 
1045 		*outpt = '\0';
1046 		if ((outpt == endpt) && (*inpt != '\0')) {
1047 			if (prnt)
1048 				tty_warn(1,"Replacement name too long %s >> %s",
1049 				    name, nname);
1050 			return(1);
1051 		}
1052 
1053 		/*
1054 		 * inform the user of the result if wanted
1055 		 */
1056 		if (prnt && (pt->flgs & PRNT)) {
1057 			if (*nname == '\0')
1058 				(void)fprintf(stderr,"%s >> <empty string>\n",
1059 				    name);
1060 			else
1061 				(void)fprintf(stderr,"%s >> %s\n", name, nname);
1062 		}
1063 
1064 		/*
1065 		 * if empty inform the caller this file is to be skipped
1066 		 * otherwise copy the new name over the orig name and return
1067 		 */
1068 		if (*nname == '\0')
1069 			return(1);
1070 		*nlen = strlcpy(name, nname, namelen);
1071 	}
1072 	return(0);
1073 }
1074 
1075 
1076 /*
1077  * checkdotdot()
1078  *	Return true if a component of the name contains a reference to ".."
1079  */
1080 static int
1081 checkdotdot(const char *name)
1082 {
1083 	const char *p;
1084 	/* 1. "..{[/],}" */
1085 	if (name[0] == '.' && name[1] == '.' &&
1086 	    (name[2] == '/' || name[2] == '\0'))
1087 		return 1;
1088 
1089 	/* 2. "*[/]..[/]*" */
1090 	if (strstr(name, "/../") != NULL)
1091 		return 1;
1092 
1093 	/* 3. "*[/].." */
1094 	for (p = name; *p; p++)
1095 		continue;
1096 	if (p - name < 3)
1097 		return 0;
1098 	if (p[-1] == '.' && p[-2] == '.' && p[-3] == '/')
1099 		return 1;
1100 
1101 	return 0;
1102 }
1103 
1104 #ifdef NET2_REGEX
1105 /*
1106  * resub()
1107  *	apply the replacement to the matched expression. expand out the old
1108  *	style ed(1) subexpression expansion.
1109  * Return:
1110  *	-1 if error, or the number of characters added to the destination.
1111  */
1112 
1113 static int
1114 resub(regexp *prog, char *src, char *dest, char *destend)
1115 {
1116 	char *spt;
1117 	char *dpt;
1118 	char c;
1119 	int no;
1120 	int len;
1121 
1122 	spt = src;
1123 	dpt = dest;
1124 	while ((dpt < destend) && ((c = *spt++) != '\0')) {
1125 		if (c == '&')
1126 			no = 0;
1127 		else if ((c == '\\') && (*spt >= '0') && (*spt <= '9'))
1128 			no = *spt++ - '0';
1129 		else {
1130 			if ((c == '\\') && ((*spt == '\\') || (*spt == '&')))
1131 				c = *spt++;
1132 			*dpt++ = c;
1133 			continue;
1134 		}
1135 		if ((prog->startp[no] == NULL) || (prog->endp[no] == NULL) ||
1136 		    ((len = prog->endp[no] - prog->startp[no]) <= 0))
1137 			continue;
1138 
1139 		/*
1140 		 * copy the subexpression to the destination.
1141 		 * fail if we run out of space or the match string is damaged
1142 		 */
1143 		if (len > (destend - dpt))
1144 			return (-1);
1145 		strncpy(dpt, prog->startp[no], len);
1146 		dpt += len;
1147 	}
1148 	return(dpt - dest);
1149 }
1150 
1151 #else
1152 
1153 /*
1154  * resub()
1155  *	apply the replacement to the matched expression. expand out the old
1156  *	style ed(1) subexpression expansion.
1157  * Return:
1158  *	-1 if error, or the number of characters added to the destination.
1159  */
1160 
1161 static int
1162 resub(regex_t *rp, regmatch_t *pm, char *src, char *txt, char *dest,
1163 	char *destend)
1164 {
1165 	char *spt;
1166 	char *dpt;
1167 	char c;
1168 	regmatch_t *pmpt;
1169 	int len;
1170 	int subexcnt;
1171 
1172 	spt =  src;
1173 	dpt = dest;
1174 	subexcnt = rp->re_nsub;
1175 	while ((dpt < destend) && ((c = *spt++) != '\0')) {
1176 		/*
1177 		 * see if we just have an ordinary replacement character
1178 		 * or we refer to a subexpression.
1179 		 */
1180 		if (c == '&') {
1181 			pmpt = pm;
1182 		} else if ((c == '\\') && (*spt >= '1') && (*spt <= '9')) {
1183 			/*
1184 			 * make sure there is a subexpression as specified
1185 			 */
1186 			if ((len = *spt++ - '0') > subexcnt)
1187 				return(-1);
1188 			pmpt = pm + len;
1189 		} else {
1190 			/*
1191 			 * Ordinary character, just copy it
1192 			 */
1193 			if ((c == '\\') && ((*spt == '\\') || (*spt == '&')))
1194 				c = *spt++;
1195 			*dpt++ = c;
1196 			continue;
1197 		}
1198 
1199 		/*
1200 		 * continue if the subexpression is bogus
1201 		 */
1202 		if ((pmpt->rm_so < 0) || (pmpt->rm_eo < 0) ||
1203 		    ((len = pmpt->rm_eo - pmpt->rm_so) <= 0))
1204 			continue;
1205 
1206 		/*
1207 		 * copy the subexpression to the destination.
1208 		 * fail if we run out of space or the match string is damaged
1209 		 */
1210 		if (len > (destend - dpt))
1211 			return -1;
1212 		strncpy(dpt, txt + pmpt->rm_so, len);
1213 		dpt += len;
1214 	}
1215 	return(dpt - dest);
1216 }
1217 #endif
1218