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