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