1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)pat_rep.c 8.2 (Berkeley) 4/18/94";
39 #endif
40 #endif /* not lint */
41 #include <sys/cdefs.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <stdlib.h>
47 #include <regex.h>
48 #include "pax.h"
49 #include "pat_rep.h"
50 #include "extern.h"
51
52 /*
53 * routines to handle pattern matching, name modification (regular expression
54 * substitution and interactive renames), and destination name modification for
55 * copy (-rw). Both file name and link names are adjusted as required in these
56 * routines.
57 */
58
59 #define MAXSUBEXP 10 /* max subexpressions, DO NOT CHANGE */
60 static PATTERN *pathead = NULL; /* file pattern match list head */
61 static PATTERN *pattail = NULL; /* file pattern match list tail */
62 static REPLACE *rephead = NULL; /* replacement string list head */
63 static REPLACE *reptail = NULL; /* replacement string list tail */
64
65 static int rep_name(char *, int *, int);
66 static int tty_rename(ARCHD *);
67 static int fix_path(char *, int *, char *, int);
68 static int fn_match(char *, char *, char **);
69 static char * range_match(char *, int);
70 static int resub(regex_t *, regmatch_t *, char *, char *, char *, char *);
71
72 /*
73 * rep_add()
74 * parses the -s replacement string; compiles the regular expression
75 * and stores the compiled value and it's replacement string together in
76 * replacement string list. Input to this function is of the form:
77 * /old/new/pg
78 * The first char in the string specifies the delimiter used by this
79 * replacement string. "Old" is a regular expression in "ed" format which
80 * is compiled by regcomp() and is applied to filenames. "new" is the
81 * substitution string; p and g are options flags for printing and global
82 * replacement (over the single filename)
83 * Return:
84 * 0 if a proper replacement string and regular expression was added to
85 * the list of replacement patterns; -1 otherwise.
86 */
87
88 int
rep_add(char * str)89 rep_add(char *str)
90 {
91 char *pt1;
92 char *pt2;
93 REPLACE *rep;
94 int res;
95 char rebuf[BUFSIZ];
96
97 /*
98 * throw out the bad parameters
99 */
100 if ((str == NULL) || (*str == '\0')) {
101 paxwarn(1, "Empty replacement string");
102 return(-1);
103 }
104
105 /*
106 * first character in the string specifies what the delimiter is for
107 * this expression
108 */
109 if ((pt1 = strchr(str+1, *str)) == NULL) {
110 paxwarn(1, "Invalid replacement string %s", str);
111 return(-1);
112 }
113
114 /*
115 * allocate space for the node that handles this replacement pattern
116 * and split out the regular expression and try to compile it
117 */
118 if ((rep = (REPLACE *)malloc(sizeof(REPLACE))) == NULL) {
119 paxwarn(1, "Unable to allocate memory for replacement string");
120 return(-1);
121 }
122
123 *pt1 = '\0';
124 if ((res = regcomp(&(rep->rcmp), str+1, 0)) != 0) {
125 regerror(res, &(rep->rcmp), rebuf, sizeof(rebuf));
126 paxwarn(1, "%s while compiling regular expression %s", rebuf, str);
127 free(rep);
128 return(-1);
129 }
130
131 /*
132 * put the delimiter back in case we need an error message and
133 * locate the delimiter at the end of the replacement string
134 * we then point the node at the new substitution string
135 */
136 *pt1++ = *str;
137 if ((pt2 = strchr(pt1, *str)) == NULL) {
138 regfree(&rep->rcmp);
139 free(rep);
140 paxwarn(1, "Invalid replacement string %s", str);
141 return(-1);
142 }
143
144 *pt2 = '\0';
145 rep->nstr = pt1;
146 pt1 = pt2++;
147 rep->flgs = 0;
148
149 /*
150 * set the options if any
151 */
152 while (*pt2 != '\0') {
153 switch(*pt2) {
154 case 'g':
155 case 'G':
156 rep->flgs |= GLOB;
157 break;
158 case 'p':
159 case 'P':
160 rep->flgs |= PRNT;
161 break;
162 default:
163 regfree(&rep->rcmp);
164 free(rep);
165 *pt1 = *str;
166 paxwarn(1, "Invalid replacement string option %s", str);
167 return(-1);
168 }
169 ++pt2;
170 }
171
172 /*
173 * all done, link it in at the end
174 */
175 rep->fow = NULL;
176 if (rephead == NULL) {
177 reptail = rephead = rep;
178 return(0);
179 }
180 reptail->fow = rep;
181 reptail = rep;
182 return(0);
183 }
184
185 /*
186 * pat_add()
187 * add a pattern match to the pattern match list. Pattern matches are used
188 * to select which archive members are extracted. (They appear as
189 * arguments to pax in the list and read modes). If no patterns are
190 * supplied to pax, all members in the archive will be selected (and the
191 * pattern match list is empty).
192 * Return:
193 * 0 if the pattern was added to the list, -1 otherwise
194 */
195
196 int
pat_add(char * str,char * chdnam)197 pat_add(char *str, char *chdnam)
198 {
199 PATTERN *pt;
200
201 /*
202 * throw out the junk
203 */
204 if ((str == NULL) || (*str == '\0')) {
205 paxwarn(1, "Empty pattern string");
206 return(-1);
207 }
208
209 /*
210 * allocate space for the pattern and store the pattern. the pattern is
211 * part of argv so do not bother to copy it, just point at it. Add the
212 * node to the end of the pattern list
213 */
214 if ((pt = (PATTERN *)malloc(sizeof(PATTERN))) == NULL) {
215 paxwarn(1, "Unable to allocate memory for pattern string");
216 return(-1);
217 }
218
219 pt->pstr = str;
220 pt->pend = NULL;
221 pt->plen = strlen(str);
222 pt->fow = NULL;
223 pt->flgs = 0;
224 pt->chdname = chdnam;
225
226 if (pathead == NULL) {
227 pattail = pathead = pt;
228 return(0);
229 }
230 pattail->fow = pt;
231 pattail = pt;
232 return(0);
233 }
234
235 /*
236 * pat_chk()
237 * complain if any the user supplied pattern did not result in a match to
238 * a selected archive member.
239 */
240
241 void
pat_chk(void)242 pat_chk(void)
243 {
244 PATTERN *pt;
245 int wban = 0;
246
247 /*
248 * walk down the list checking the flags to make sure MTCH was set,
249 * if not complain
250 */
251 for (pt = pathead; pt != NULL; pt = pt->fow) {
252 if (pt->flgs & MTCH)
253 continue;
254 if (!wban) {
255 paxwarn(1, "WARNING! These patterns were not matched:");
256 ++wban;
257 }
258 (void)fprintf(stderr, "%s\n", pt->pstr);
259 }
260 }
261
262 /*
263 * pat_sel()
264 * the archive member which matches a pattern was selected. Mark the
265 * pattern as having selected an archive member. arcn->pat points at the
266 * pattern that was matched. arcn->pat is set in pat_match()
267 *
268 * NOTE: When the -c option is used, we are called when there was no match
269 * by pat_match() (that means we did match before the inverted sense of
270 * the logic). Now this seems really strange at first, but with -c we
271 * need to keep track of those patterns that cause an archive member to NOT
272 * be selected (it found an archive member with a specified pattern)
273 * Return:
274 * 0 if the pattern pointed at by arcn->pat was tagged as creating a
275 * match, -1 otherwise.
276 */
277
278 int
pat_sel(ARCHD * arcn)279 pat_sel(ARCHD *arcn)
280 {
281 PATTERN *pt;
282 PATTERN **ppt;
283 int len;
284
285 /*
286 * if no patterns just return
287 */
288 if ((pathead == NULL) || ((pt = arcn->pat) == NULL))
289 return(0);
290
291 /*
292 * when we are NOT limited to a single match per pattern mark the
293 * pattern and return
294 */
295 if (!nflag) {
296 pt->flgs |= MTCH;
297 return(0);
298 }
299
300 /*
301 * we reach this point only when we allow a single selected match per
302 * pattern, if the pattern matches a directory and we do not have -d
303 * (dflag) we are done with this pattern. We may also be handed a file
304 * in the subtree of a directory. in that case when we are operating
305 * with -d, this pattern was already selected and we are done
306 */
307 if (pt->flgs & DIR_MTCH)
308 return(0);
309
310 if (!dflag && ((pt->pend != NULL) || (arcn->type == PAX_DIR))) {
311 /*
312 * ok we matched a directory and we are allowing
313 * subtree matches but because of the -n only its children will
314 * match. This is tagged as a DIR_MTCH type.
315 * WATCH IT, the code assumes that pt->pend points
316 * into arcn->name and arcn->name has not been modified.
317 * If not we will have a big mess. Yup this is another kludge
318 */
319
320 /*
321 * if this was a prefix match, remove trailing part of path
322 * so we can copy it. Future matches will be exact prefix match
323 */
324 if (pt->pend != NULL)
325 *pt->pend = '\0';
326
327 if ((pt->pstr = strdup(arcn->name)) == NULL) {
328 paxwarn(1, "Pattern select out of memory");
329 if (pt->pend != NULL)
330 *pt->pend = '/';
331 pt->pend = NULL;
332 return(-1);
333 }
334
335 /*
336 * put the trailing / back in the source string
337 */
338 if (pt->pend != NULL) {
339 *pt->pend = '/';
340 pt->pend = NULL;
341 }
342 pt->plen = strlen(pt->pstr);
343
344 /*
345 * strip off any trailing /, this should really never happen
346 */
347 len = pt->plen - 1;
348 if (*(pt->pstr + len) == '/') {
349 *(pt->pstr + len) = '\0';
350 pt->plen = len;
351 }
352 pt->flgs = DIR_MTCH | MTCH;
353 arcn->pat = pt;
354 return(0);
355 }
356
357 /*
358 * we are then done with this pattern, so we delete it from the list
359 * because it can never be used for another match.
360 * Seems kind of strange to do for a -c, but the pax spec is really
361 * vague on the interaction of -c -n and -d. We assume that when -c
362 * and the pattern rejects a member (i.e. it matched it) it is done.
363 * In effect we place the order of the flags as having -c last.
364 */
365 pt = pathead;
366 ppt = &pathead;
367 while ((pt != NULL) && (pt != arcn->pat)) {
368 ppt = &(pt->fow);
369 pt = pt->fow;
370 }
371
372 if (pt == NULL) {
373 /*
374 * should never happen....
375 */
376 paxwarn(1, "Pattern list inconsistent");
377 return(-1);
378 }
379 *ppt = pt->fow;
380 free(pt);
381 arcn->pat = NULL;
382 return(0);
383 }
384
385 /*
386 * pat_match()
387 * see if this archive member matches any supplied pattern, if a match
388 * is found, arcn->pat is set to point at the potential pattern. Later if
389 * this archive member is "selected" we process and mark the pattern as
390 * one which matched a selected archive member (see pat_sel())
391 * Return:
392 * 0 if this archive member should be processed, 1 if it should be
393 * skipped and -1 if we are done with all patterns (and pax should quit
394 * looking for more members)
395 */
396
397 int
pat_match(ARCHD * arcn)398 pat_match(ARCHD *arcn)
399 {
400 PATTERN *pt;
401
402 arcn->pat = NULL;
403
404 /*
405 * if there are no more patterns and we have -n (and not -c) we are
406 * done. otherwise with no patterns to match, matches all
407 */
408 if (pathead == NULL) {
409 if (nflag && !cflag)
410 return(-1);
411 return(0);
412 }
413
414 /*
415 * have to search down the list one at a time looking for a match.
416 */
417 pt = pathead;
418 while (pt != NULL) {
419 /*
420 * check for a file name match unless we have DIR_MTCH set in
421 * this pattern then we want a prefix match
422 */
423 if (pt->flgs & DIR_MTCH) {
424 /*
425 * this pattern was matched before to a directory
426 * as we must have -n set for this (but not -d). We can
427 * only match CHILDREN of that directory so we must use
428 * an exact prefix match (no wildcards).
429 */
430 if ((arcn->name[pt->plen] == '/') &&
431 (strncmp(pt->pstr, arcn->name, pt->plen) == 0))
432 break;
433 } else if (fn_match(pt->pstr, arcn->name, &pt->pend) == 0)
434 break;
435 pt = pt->fow;
436 }
437
438 /*
439 * return the result, remember that cflag (-c) inverts the sense of a
440 * match
441 */
442 if (pt == NULL)
443 return(cflag ? 0 : 1);
444
445 /*
446 * We had a match, now when we invert the sense (-c) we reject this
447 * member. However we have to tag the pattern a being successful, (in a
448 * match, not in selecting an archive member) so we call pat_sel() here.
449 */
450 arcn->pat = pt;
451 if (!cflag)
452 return(0);
453
454 if (pat_sel(arcn) < 0)
455 return(-1);
456 arcn->pat = NULL;
457 return(1);
458 }
459
460 /*
461 * fn_match()
462 * Return:
463 * 0 if this archive member should be processed, 1 if it should be
464 * skipped and -1 if we are done with all patterns (and pax should quit
465 * looking for more members)
466 * Note: *pend may be changed to show where the prefix ends.
467 */
468
469 static int
fn_match(char * pattern,char * string,char ** pend)470 fn_match(char *pattern, char *string, char **pend)
471 {
472 char c;
473 char test;
474
475 *pend = NULL;
476 for (;;) {
477 switch (c = *pattern++) {
478 case '\0':
479 /*
480 * Ok we found an exact match
481 */
482 if (*string == '\0')
483 return(0);
484
485 /*
486 * Check if it is a prefix match
487 */
488 if ((dflag == 1) || (*string != '/'))
489 return(-1);
490
491 /*
492 * It is a prefix match, remember where the trailing
493 * / is located
494 */
495 *pend = string;
496 return(0);
497 case '?':
498 if ((test = *string++) == '\0')
499 return (-1);
500 break;
501 case '*':
502 c = *pattern;
503 /*
504 * Collapse multiple *'s.
505 */
506 while (c == '*')
507 c = *++pattern;
508
509 /*
510 * Optimized hack for pattern with a * at the end
511 */
512 if (c == '\0')
513 return (0);
514
515 /*
516 * General case, use recursion.
517 */
518 while ((test = *string) != '\0') {
519 if (!fn_match(pattern, string, pend))
520 return (0);
521 ++string;
522 }
523 return (-1);
524 case '[':
525 /*
526 * range match
527 */
528 if (((test = *string++) == '\0') ||
529 ((pattern = range_match(pattern, test)) == NULL))
530 return (-1);
531 break;
532 case '\\':
533 default:
534 if (c != *string++)
535 return (-1);
536 break;
537 }
538 }
539 /* NOTREACHED */
540 }
541
542 static char *
range_match(char * pattern,int test)543 range_match(char *pattern, int test)
544 {
545 char c;
546 char c2;
547 int negate;
548 int ok = 0;
549
550 if ((negate = (*pattern == '!')) != 0)
551 ++pattern;
552
553 while ((c = *pattern++) != ']') {
554 /*
555 * Illegal pattern
556 */
557 if (c == '\0')
558 return (NULL);
559
560 if ((*pattern == '-') && ((c2 = pattern[1]) != '\0') &&
561 (c2 != ']')) {
562 if ((c <= test) && (test <= c2))
563 ok = 1;
564 pattern += 2;
565 } else if (c == test)
566 ok = 1;
567 }
568 return (ok == negate ? NULL : pattern);
569 }
570
571 /*
572 * mod_name()
573 * modify a selected file name. first attempt to apply replacement string
574 * expressions, then apply interactive file rename. We apply replacement
575 * string expressions to both filenames and file links (if we didn't the
576 * links would point to the wrong place, and we could never be able to
577 * move an archive that has a file link in it). When we rename files
578 * interactively, we store that mapping (old name to user input name) so
579 * if we spot any file links to the old file name in the future, we will
580 * know exactly how to fix the file link.
581 * Return:
582 * 0 continue to process file, 1 skip this file, -1 pax is finished
583 */
584
585 int
mod_name(ARCHD * arcn)586 mod_name(ARCHD *arcn)
587 {
588 int res = 0;
589
590 /*
591 * Strip off leading '/' if appropriate.
592 * Currently, this option is only set for the tar format.
593 */
594 if (rmleadslash && arcn->name[0] == '/') {
595 if (arcn->name[1] == '\0') {
596 arcn->name[0] = '.';
597 } else {
598 (void)memmove(arcn->name, &arcn->name[1],
599 strlen(arcn->name));
600 arcn->nlen--;
601 }
602 if (rmleadslash < 2) {
603 rmleadslash = 2;
604 paxwarn(0, "Removing leading / from absolute path names in the archive");
605 }
606 }
607 if (rmleadslash && arcn->ln_name[0] == '/' &&
608 (arcn->type == PAX_HLK || arcn->type == PAX_HRG)) {
609 if (arcn->ln_name[1] == '\0') {
610 arcn->ln_name[0] = '.';
611 } else {
612 (void)memmove(arcn->ln_name, &arcn->ln_name[1],
613 strlen(arcn->ln_name));
614 arcn->ln_nlen--;
615 }
616 if (rmleadslash < 2) {
617 rmleadslash = 2;
618 paxwarn(0, "Removing leading / from absolute path names in the archive");
619 }
620 }
621
622 /*
623 * IMPORTANT: We have a problem. what do we do with symlinks?
624 * Modifying a hard link name makes sense, as we know the file it
625 * points at should have been seen already in the archive (and if it
626 * wasn't seen because of a read error or a bad archive, we lose
627 * anyway). But there are no such requirements for symlinks. On one
628 * hand the symlink that refers to a file in the archive will have to
629 * be modified to so it will still work at its new location in the
630 * file system. On the other hand a symlink that points elsewhere (and
631 * should continue to do so) should not be modified. There is clearly
632 * no perfect solution here. So we handle them like hardlinks. Clearly
633 * a replacement made by the interactive rename mapping is very likely
634 * to be correct since it applies to a single file and is an exact
635 * match. The regular expression replacements are a little harder to
636 * justify though. We claim that the symlink name is only likely
637 * to be replaced when it points within the file tree being moved and
638 * in that case it should be modified. what we really need to do is to
639 * call an oracle here. :)
640 */
641 if (rephead != NULL) {
642 /*
643 * we have replacement strings, modify the name and the link
644 * name if any.
645 */
646 if ((res = rep_name(arcn->name, &(arcn->nlen), 1)) != 0)
647 return(res);
648
649 if (((arcn->type == PAX_SLK) || (arcn->type == PAX_HLK) ||
650 (arcn->type == PAX_HRG)) &&
651 ((res = rep_name(arcn->ln_name, &(arcn->ln_nlen), 0)) != 0))
652 return(res);
653 }
654
655 if (iflag) {
656 /*
657 * perform interactive file rename, then map the link if any
658 */
659 if ((res = tty_rename(arcn)) != 0)
660 return(res);
661 if ((arcn->type == PAX_SLK) || (arcn->type == PAX_HLK) ||
662 (arcn->type == PAX_HRG))
663 sub_name(arcn->ln_name, &(arcn->ln_nlen), sizeof(arcn->ln_name));
664 }
665 return(res);
666 }
667
668 /*
669 * tty_rename()
670 * Prompt the user for a replacement file name. A "." keeps the old name,
671 * a empty line skips the file, and an EOF on reading the tty, will cause
672 * pax to stop processing and exit. Otherwise the file name input, replaces
673 * the old one.
674 * Return:
675 * 0 process this file, 1 skip this file, -1 we need to exit pax
676 */
677
678 static int
tty_rename(ARCHD * arcn)679 tty_rename(ARCHD *arcn)
680 {
681 char tmpname[PAXPATHLEN+2];
682 int res;
683
684 /*
685 * prompt user for the replacement name for a file, keep trying until
686 * we get some reasonable input. Archives may have more than one file
687 * on them with the same name (from updates etc). We print verbose info
688 * on the file so the user knows what is up.
689 */
690 tty_prnt("\nATTENTION: %s interactive file rename operation.\n", argv0);
691
692 for (;;) {
693 ls_tty(arcn);
694 tty_prnt("Input new name, or a \".\" to keep the old name, ");
695 tty_prnt("or a \"return\" to skip this file.\n");
696 tty_prnt("Input > ");
697 if (tty_read(tmpname, sizeof(tmpname)) < 0)
698 return(-1);
699 if (strcmp(tmpname, "..") == 0) {
700 tty_prnt("Try again, illegal file name: ..\n");
701 continue;
702 }
703 if (strlen(tmpname) > PAXPATHLEN) {
704 tty_prnt("Try again, file name too long\n");
705 continue;
706 }
707 break;
708 }
709
710 /*
711 * empty file name, skips this file. a "." leaves it alone
712 */
713 if (tmpname[0] == '\0') {
714 tty_prnt("Skipping file.\n");
715 return(1);
716 }
717 if ((tmpname[0] == '.') && (tmpname[1] == '\0')) {
718 tty_prnt("Processing continues, name unchanged.\n");
719 return(0);
720 }
721
722 /*
723 * ok the name changed. We may run into links that point at this
724 * file later. we have to remember where the user sent the file
725 * in order to repair any links.
726 */
727 tty_prnt("Processing continues, name changed to: %s\n", tmpname);
728 res = add_name(arcn->name, arcn->nlen, tmpname);
729 arcn->nlen = l_strncpy(arcn->name, tmpname, sizeof(arcn->name) - 1);
730 arcn->name[arcn->nlen] = '\0';
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
set_dest(ARCHD * arcn,char * dest_dir,int dir_len)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
fix_path(char * or_name,int * or_len,char * dir_name,int dir_len)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 paxwarn(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
rep_name(char * name,int * nlen,int prnt)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 regmatch_t pm[MAXSUBEXP];
845 char nname[PAXPATHLEN+1]; /* final result of all replacements */
846 char buf1[PAXPATHLEN+1]; /* where we work on the name */
847
848 /*
849 * copy the name into buf1, where we will work on it. We need to keep
850 * the orig string around so we can print out the result of the final
851 * replacement. We build up the final result in nname. inpt points at
852 * the string we apply the regular expression to. prnt is used to
853 * suppress printing when we handle replacements on the link field
854 * (the user already saw that substitution go by)
855 */
856 pt = rephead;
857 (void)strlcpy(buf1, name, sizeof(buf1));
858 inpt = buf1;
859 outpt = nname;
860 endpt = outpt + PAXPATHLEN;
861
862 /*
863 * try each replacement string in order
864 */
865 while (pt != NULL) {
866 do {
867 /*
868 * check for a successful substitution, if not go to
869 * the next pattern, or cleanup if we were global
870 */
871 if (regexec(&(pt->rcmp), inpt, MAXSUBEXP, pm, 0) != 0)
872 break;
873
874 /*
875 * ok we found one. We have three parts, the prefix
876 * which did not match, the section that did and the
877 * tail (that also did not match). Copy the prefix to
878 * the final output buffer (watching to make sure we
879 * do not create a string too long).
880 */
881 found = 1;
882 rpt = inpt + pm[0].rm_so;
883
884 while ((inpt < rpt) && (outpt < endpt))
885 *outpt++ = *inpt++;
886 if (outpt == endpt)
887 break;
888
889 /*
890 * for the second part (which matched the regular
891 * expression) apply the substitution using the
892 * replacement string and place it the prefix in the
893 * final output. If we have problems, skip it.
894 */
895 if ((res = resub(&(pt->rcmp),pm,inpt,pt->nstr,outpt,endpt))
896 < 0) {
897 if (prnt)
898 paxwarn(1, "Replacement name error %s",
899 name);
900 return(1);
901 }
902 outpt += res;
903
904 /*
905 * we set up to look again starting at the first
906 * character in the tail (of the input string right
907 * after the last character matched by the regular
908 * expression (inpt always points at the first char in
909 * the string to process). If we are not doing a global
910 * substitution, we will use inpt to copy the tail to
911 * the final result. Make sure we do not overrun the
912 * output buffer
913 */
914 inpt += pm[0].rm_eo - pm[0].rm_so;
915
916 if ((outpt == endpt) || (*inpt == '\0'))
917 break;
918
919 /*
920 * if the user wants global we keep trying to
921 * substitute until it fails, then we are done.
922 */
923 } while (pt->flgs & GLOB);
924
925 if (found)
926 break;
927
928 /*
929 * a successful substitution did NOT occur, try the next one
930 */
931 pt = pt->fow;
932 }
933
934 if (found) {
935 /*
936 * we had a substitution, copy the last tail piece (if there is
937 * room) to the final result
938 */
939 while ((outpt < endpt) && (*inpt != '\0'))
940 *outpt++ = *inpt++;
941
942 *outpt = '\0';
943 if ((outpt == endpt) && (*inpt != '\0')) {
944 if (prnt)
945 paxwarn(1,"Replacement name too long %s >> %s",
946 name, nname);
947 return(1);
948 }
949
950 /*
951 * inform the user of the result if wanted
952 */
953 if (prnt && (pt->flgs & PRNT)) {
954 if (*nname == '\0')
955 (void)fprintf(stderr,"%s >> <empty string>\n",
956 name);
957 else
958 (void)fprintf(stderr,"%s >> %s\n", name, nname);
959 }
960
961 /*
962 * if empty inform the caller this file is to be skipped
963 * otherwise copy the new name over the orig name and return
964 */
965 if (*nname == '\0')
966 return(1);
967 *nlen = l_strncpy(name, nname, PAXPATHLEN + 1);
968 name[PAXPATHLEN] = '\0';
969 }
970 return(0);
971 }
972
973
974 /*
975 * resub()
976 * apply the replacement to the matched expression. expand out the old
977 * style ed(1) subexpression expansion.
978 * Return:
979 * -1 if error, or the number of characters added to the destination.
980 */
981
982 static int
resub(regex_t * rp,regmatch_t * pm,char * orig,char * src,char * dest,char * destend)983 resub(regex_t *rp, regmatch_t *pm, char *orig, char *src, char *dest,
984 char *destend)
985 {
986 char *spt;
987 char *dpt;
988 char c;
989 regmatch_t *pmpt;
990 int len;
991 int subexcnt;
992
993 spt = src;
994 dpt = dest;
995 subexcnt = rp->re_nsub;
996 while ((dpt < destend) && ((c = *spt++) != '\0')) {
997 /*
998 * see if we just have an ordinary replacement character
999 * or we refer to a subexpression.
1000 */
1001 if (c == '&') {
1002 pmpt = pm;
1003 } else if ((c == '\\') && (*spt >= '0') && (*spt <= '9')) {
1004 /*
1005 * make sure there is a subexpression as specified
1006 */
1007 if ((len = *spt++ - '0') > subexcnt)
1008 return(-1);
1009 pmpt = pm + len;
1010 } else {
1011 /*
1012 * Ordinary character, just copy it
1013 */
1014 if ((c == '\\') && ((*spt == '\\') || (*spt == '&')))
1015 c = *spt++;
1016 *dpt++ = c;
1017 continue;
1018 }
1019
1020 /*
1021 * continue if the subexpression is bogus
1022 */
1023 if ((pmpt->rm_so < 0) || (pmpt->rm_eo < 0) ||
1024 ((len = pmpt->rm_eo - pmpt->rm_so) <= 0))
1025 continue;
1026
1027 /*
1028 * copy the subexpression to the destination.
1029 * fail if we run out of space or the match string is damaged
1030 */
1031 if (len > (destend - dpt))
1032 len = destend - dpt;
1033 if (l_strncpy(dpt, orig + pmpt->rm_so, len) != len)
1034 return(-1);
1035 dpt += len;
1036 }
1037 return(dpt - dest);
1038 }
1039