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