* de-__P()
[dragonfly.git] / bin / pax / file_subs.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  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  * @(#)file_subs.c      8.1 (Berkeley) 5/31/93
38  * $FreeBSD: src/bin/pax/file_subs.c,v 1.12.2.1 2001/08/01 05:03:11 obrien Exp $
39  * $DragonFly: src/bin/pax/file_subs.c,v 1.3 2003/09/21 04:24:17 drhodus Exp $
40  */
41
42 #include <sys/types.h>
43 #include <sys/time.h>
44 #include <sys/stat.h>
45 #include <unistd.h>
46 #include <fcntl.h>
47 #include <string.h>
48 #include <stdio.h>
49 #include <errno.h>
50 #include <sys/uio.h>
51 #include <stdlib.h>
52 #include "pax.h"
53 #include "options.h"
54 #include "extern.h"
55
56 static int
57 mk_link (register char *,register struct stat *,register char *, int);
58
59 /*
60  * routines that deal with file operations such as: creating, removing;
61  * and setting access modes, uid/gid and times of files
62  */
63
64 #define FILEBITS                (S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
65 #define SETBITS                 (S_ISUID | S_ISGID)
66 #define ABITS                   (FILEBITS | SETBITS)
67
68 /*
69  * file_creat()
70  *      Create and open a file.
71  * Return:
72  *      file descriptor or -1 for failure
73  */
74
75 #ifdef __STDC__
76 int
77 file_creat(register ARCHD *arcn)
78 #else
79 int
80 file_creat(arcn)
81         register ARCHD *arcn;
82 #endif
83 {
84         int fd = -1;
85         mode_t file_mode;
86         int oerrno;
87
88         /*
89          * assume file doesn't exist, so just try to create it, most times this
90          * works. We have to take special handling when the file does exist. To
91          * detect this, we use O_EXCL. For example when trying to create a
92          * file and a character device or fifo exists with the same name, we
93          * can accidently open the device by mistake (or block waiting to open)
94          * If we find that the open has failed, then figure spend the effort to
95          * figure out why. This strategy was found to have better average
96          * performance in common use than checking the file (and the path)
97          * first with lstat.
98          */
99         file_mode = arcn->sb.st_mode & FILEBITS;
100         if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
101             file_mode)) >= 0)
102                 return(fd);
103
104         /*
105          * the file seems to exist. First we try to get rid of it (found to be
106          * the second most common failure when traced). If this fails, only
107          * then we go to the expense to check and create the path to the file
108          */
109         if (unlnk_exist(arcn->name, arcn->type) != 0)
110                 return(-1);
111
112         for (;;) {
113                 /*
114                  * try to open it again, if this fails, check all the nodes in
115                  * the path and give it a final try. if chk_path() finds that
116                  * it cannot fix anything, we will skip the last attempt
117                  */
118                 if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
119                     file_mode)) >= 0)
120                         break;
121                 oerrno = errno;
122                 if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
123                         syswarn(1, oerrno, "Unable to create %s", arcn->name);
124                         return(-1);
125                 }
126         }
127         return(fd);
128 }
129
130 /*
131  * file_close()
132  *      Close file descriptor to a file just created by pax. Sets modes,
133  *      ownership and times as required.
134  * Return:
135  *      0 for success, -1 for failure
136  */
137
138 #ifdef __STDC__
139 void
140 file_close(register ARCHD *arcn, int fd)
141 #else
142 void
143 file_close(arcn, fd)
144         register ARCHD *arcn;
145         int fd;
146 #endif
147 {
148         int res = 0;
149
150         if (fd < 0)
151                 return;
152         if (close(fd) < 0)
153                 syswarn(0, errno, "Unable to close file descriptor on %s",
154                     arcn->name);
155
156         /*
157          * set owner/groups first as this may strip off mode bits we want
158          * then set file permission modes. Then set file access and
159          * modification times.
160          */
161         if (pids)
162                 res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
163
164         /*
165          * IMPORTANT SECURITY NOTE:
166          * if not preserving mode or we cannot set uid/gid, then PROHIBIT
167          * set uid/gid bits
168          */
169         if (!pmode || res)
170                 arcn->sb.st_mode &= ~(SETBITS);
171         if (pmode)
172                 set_pmode(arcn->name, arcn->sb.st_mode);
173         if (patime || pmtime)
174                 set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
175 }
176
177 /*
178  * lnk_creat()
179  *      Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
180  *      must exist;
181  * Return:
182  *      0 if ok, -1 otherwise
183  */
184
185 #ifdef __STDC__
186 int
187 lnk_creat(register ARCHD *arcn)
188 #else
189 int
190 lnk_creat(arcn)
191         register ARCHD *arcn;
192 #endif
193 {
194         struct stat sb;
195
196         /*
197          * we may be running as root, so we have to be sure that link target
198          * is not a directory, so we lstat and check
199          */
200         if (lstat(arcn->ln_name, &sb) < 0) {
201                 syswarn(1,errno,"Unable to link to %s from %s", arcn->ln_name,
202                     arcn->name);
203                 return(-1);
204         }
205
206         if (S_ISDIR(sb.st_mode)) {
207                 paxwarn(1, "A hard link to the directory %s is not allowed",
208                     arcn->ln_name);
209                 return(-1);
210         }
211
212         return(mk_link(arcn->ln_name, &sb, arcn->name, 0));
213 }
214
215 /*
216  * cross_lnk()
217  *      Create a hard link to arcn->org_name from arcn->name. Only used in copy
218  *      with the -l flag. No warning or error if this does not succeed (we will
219  *      then just create the file)
220  * Return:
221  *      1 if copy() should try to create this file node
222  *      0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
223  */
224
225 #ifdef __STDC__
226 int
227 cross_lnk(register ARCHD *arcn)
228 #else
229 int
230 cross_lnk(arcn)
231         register ARCHD *arcn;
232 #endif
233 {
234         /*
235          * try to make a link to original file (-l flag in copy mode). make sure
236          * we do not try to link to directories in case we are running as root
237          * (and it might succeed).
238          */
239         if (arcn->type == PAX_DIR)
240                 return(1);
241         return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
242 }
243
244 /*
245  * chk_same()
246  *      In copy mode if we are not trying to make hard links between the src
247  *      and destinations, make sure we are not going to overwrite ourselves by
248  *      accident. This slows things down a little, but we have to protect all
249  *      those people who make typing errors.
250  * Return:
251  *      1 the target does not exist, go ahead and copy
252  *      0 skip it file exists (-k) or may be the same as source file
253  */
254
255 #ifdef __STDC__
256 int
257 chk_same(register ARCHD *arcn)
258 #else
259 int
260 chk_same(arcn)
261         register ARCHD *arcn;
262 #endif
263 {
264         struct stat sb;
265
266         /*
267          * if file does not exist, return. if file exists and -k, skip it
268          * quietly
269          */
270         if (lstat(arcn->name, &sb) < 0)
271                 return(1);
272         if (kflag)
273                 return(0);
274
275         /*
276          * better make sure the user does not have src == dest by mistake
277          */
278         if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
279                 paxwarn(1, "Unable to copy %s, file would overwrite itself",
280                     arcn->name);
281                 return(0);
282         }
283         return(1);
284 }
285
286 /*
287  * mk_link()
288  *      try to make a hard link between two files. if ign set, we do not
289  *      complain.
290  * Return:
291  *      0 if successful (or we are done with this file but no error, such as
292  *      finding the from file exists and the user has set -k).
293  *      1 when ign was set to indicates we could not make the link but we
294  *      should try to copy/extract the file as that might work (and is an
295  *      allowed option). -1 an error occurred.
296  */
297
298 #ifdef __STDC__
299 static int
300 mk_link(register char *to, register struct stat *to_sb, register char *from,
301         int ign)
302 #else
303 static int
304 mk_link(to, to_sb, from, ign)
305         register char *to;
306         register struct stat *to_sb;
307         register char *from;
308         int ign;
309 #endif
310 {
311         struct stat sb;
312         int oerrno;
313
314         /*
315          * if from file exists, it has to be unlinked to make the link. If the
316          * file exists and -k is set, skip it quietly
317          */
318         if (lstat(from, &sb) == 0) {
319                 if (kflag)
320                         return(0);
321
322                 /*
323                  * make sure it is not the same file, protect the user
324                  */
325                 if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
326                         paxwarn(1, "Unable to link file %s to itself", to);
327                         return(-1);;
328                 }
329
330                 /*
331                  * try to get rid of the file, based on the type
332                  */
333                 if (S_ISDIR(sb.st_mode)) {
334                         if (rmdir(from) < 0) {
335                                 syswarn(1, errno, "Unable to remove %s", from);
336                                 return(-1);
337                         }
338                 } else if (unlink(from) < 0) {
339                         if (!ign) {
340                                 syswarn(1, errno, "Unable to remove %s", from);
341                                 return(-1);
342                         }
343                         return(1);
344                 }
345         }
346
347         /*
348          * from file is gone (or did not exist), try to make the hard link.
349          * if it fails, check the path and try it again (if chk_path() says to
350          * try again)
351          */
352         for (;;) {
353                 if (link(to, from) == 0)
354                         break;
355                 oerrno = errno;
356                 if (!nodirs && chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
357                         continue;
358                 if (!ign) {
359                         syswarn(1, oerrno, "Could not link to %s from %s", to,
360                             from);
361                         return(-1);
362                 }
363                 return(1);
364         }
365
366         /*
367          * all right the link was made
368          */
369         return(0);
370 }
371
372 /*
373  * node_creat()
374  *      create an entry in the file system (other than a file or hard link).
375  *      If successful, sets uid/gid modes and times as required.
376  * Return:
377  *      0 if ok, -1 otherwise
378  */
379
380 #ifdef __STDC__
381 int
382 node_creat(register ARCHD *arcn)
383 #else
384 int
385 node_creat(arcn)
386         register ARCHD *arcn;
387 #endif
388 {
389         register int res;
390         register int ign = 0;
391         register int oerrno;
392         register int pass = 0;
393         mode_t file_mode;
394         struct stat sb;
395
396         /*
397          * create node based on type, if that fails try to unlink the node and
398          * try again. finally check the path and try again. As noted in the
399          * file and link creation routines, this method seems to exhibit the
400          * best performance in general use workloads.
401          */
402         file_mode = arcn->sb.st_mode & FILEBITS;
403
404         for (;;) {
405                 switch(arcn->type) {
406                 case PAX_DIR:
407                         res = mkdir(arcn->name, file_mode);
408                         if (ign)
409                                 res = 0;
410                         break;
411                 case PAX_CHR:
412                         file_mode |= S_IFCHR;
413                         res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
414                         break;
415                 case PAX_BLK:
416                         file_mode |= S_IFBLK;
417                         res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
418                         break;
419                 case PAX_FIF:
420                         res = mkfifo(arcn->name, file_mode);
421                         break;
422                 case PAX_SCK:
423                         /*
424                          * Skip sockets, operation has no meaning under BSD
425                          */
426                         paxwarn(0,
427                             "%s skipped. Sockets cannot be copied or extracted",
428                             arcn->name);
429                         return(-1);
430                 case PAX_SLK:
431                         res = symlink(arcn->ln_name, arcn->name);
432                         break;
433                 case PAX_CTG:
434                 case PAX_HLK:
435                 case PAX_HRG:
436                 case PAX_REG:
437                 default:
438                         /*
439                          * we should never get here
440                          */
441                         paxwarn(0, "%s has an unknown file type, skipping",
442                                 arcn->name);
443                         return(-1);
444                 }
445
446                 /*
447                  * if we were able to create the node break out of the loop,
448                  * otherwise try to unlink the node and try again. if that
449                  * fails check the full path and try a final time.
450                  */
451                 if (res == 0)
452                         break;
453
454                 /*
455                  * we failed to make the node
456                  */
457                 oerrno = errno;
458                 if ((ign = unlnk_exist(arcn->name, arcn->type)) < 0)
459                         return(-1);
460
461                 if (++pass <= 1)
462                         continue;
463
464                 if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
465                         syswarn(1, oerrno, "Could not create: %s", arcn->name);
466                         return(-1);
467                 }
468         }
469
470         /*
471          * we were able to create the node. set uid/gid, modes and times
472          */
473         if (pids)
474                 res = ((arcn->type == PAX_SLK) ?
475                     set_lids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid) :
476                     set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid));
477         else
478                 res = 0;
479
480         /*
481          * symlinks are done now.
482          */
483         if (arcn->type == PAX_SLK)
484                 return(0);
485
486         /*
487          * IMPORTANT SECURITY NOTE:
488          * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
489          * set uid/gid bits
490          */
491         if (!pmode || res)
492                 arcn->sb.st_mode &= ~(SETBITS);
493         if (pmode)
494                 set_pmode(arcn->name, arcn->sb.st_mode);
495
496         if (arcn->type == PAX_DIR && strcmp(NM_CPIO, argv0) != 0) {
497                 /*
498                  * Dirs must be processed again at end of extract to set times
499                  * and modes to agree with those stored in the archive. However
500                  * to allow extract to continue, we may have to also set owner
501                  * rights. This allows nodes in the archive that are children
502                  * of this directory to be extracted without failure. Both time
503                  * and modes will be fixed after the entire archive is read and
504                  * before pax exits.
505                  */
506                 if (access(arcn->name, R_OK | W_OK | X_OK) < 0) {
507                         if (lstat(arcn->name, &sb) < 0) {
508                                 syswarn(0, errno,"Could not access %s (stat)",
509                                     arcn->name);
510                                 set_pmode(arcn->name,file_mode | S_IRWXU);
511                         } else {
512                                 /*
513                                  * We have to add rights to the dir, so we make
514                                  * sure to restore the mode. The mode must be
515                                  * restored AS CREATED and not as stored if
516                                  * pmode is not set.
517                                  */
518                                 set_pmode(arcn->name,
519                                     ((sb.st_mode & FILEBITS) | S_IRWXU));
520                                 if (!pmode)
521                                         arcn->sb.st_mode = sb.st_mode;
522                         }
523
524                         /*
525                          * we have to force the mode to what was set here,
526                          * since we changed it from the default as created.
527                          */
528                         add_dir(arcn->name, arcn->nlen, &(arcn->sb), 1);
529                 } else if (pmode || patime || pmtime)
530                         add_dir(arcn->name, arcn->nlen, &(arcn->sb), 0);
531         }
532
533         if (patime || pmtime)
534                 set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
535         return(0);
536 }
537
538 /*
539  * unlnk_exist()
540  *      Remove node from file system with the specified name. We pass the type
541  *      of the node that is going to replace it. When we try to create a
542  *      directory and find that it already exists, we allow processing to
543  *      continue as proper modes etc will always be set for it later on.
544  * Return:
545  *      0 is ok to proceed, no file with the specified name exists
546  *      -1 we were unable to remove the node, or we should not remove it (-k)
547  *      1 we found a directory and we were going to create a directory.
548  */
549
550 #ifdef __STDC__
551 int
552 unlnk_exist(register char *name, register int type)
553 #else
554 int
555 unlnk_exist(name, type)
556         register char *name;
557         register int type;
558 #endif
559 {
560         struct stat sb;
561
562         /*
563          * the file does not exist, or -k we are done
564          */
565         if (lstat(name, &sb) < 0)
566                 return(0);
567         if (kflag)
568                 return(-1);
569
570         if (S_ISDIR(sb.st_mode)) {
571                 /*
572                  * try to remove a directory, if it fails and we were going to
573                  * create a directory anyway, tell the caller (return a 1)
574                  */
575                 if (rmdir(name) < 0) {
576                         if (type == PAX_DIR)
577                                 return(1);
578                         syswarn(1,errno,"Unable to remove directory %s", name);
579                         return(-1);
580                 }
581                 return(0);
582         }
583
584         /*
585          * try to get rid of all non-directory type nodes
586          */
587         if (unlink(name) < 0) {
588                 syswarn(1, errno, "Could not unlink %s", name);
589                 return(-1);
590         }
591         return(0);
592 }
593
594 /*
595  * chk_path()
596  *      We were trying to create some kind of node in the file system and it
597  *      failed. chk_path() makes sure the path up to the node exists and is
598  *      writeable. When we have to create a directory that is missing along the
599  *      path somewhere, the directory we create will be set to the same
600  *      uid/gid as the file has (when uid and gid are being preserved).
601  *      NOTE: this routine is a real performance loss. It is only used as a
602  *      last resort when trying to create entries in the file system.
603  * Return:
604  *      -1 when it could find nothing it is allowed to fix.
605  *      0 otherwise
606  */
607
608 #ifdef __STDC__
609 int
610 chk_path( register char *name, uid_t st_uid, gid_t st_gid)
611 #else
612 int
613 chk_path(name, st_uid, st_gid)
614         register char *name;
615         uid_t st_uid;
616         gid_t st_gid;
617 #endif
618 {
619         register char *spt = name;
620         struct stat sb;
621         int retval = -1;
622
623         /*
624          * watch out for paths with nodes stored directly in / (e.g. /bozo)
625          */
626         if (*spt == '/')
627                 ++spt;
628
629         for(;;) {
630                 /*
631                  * work foward from the first / and check each part of the path
632                  */
633                 spt = strchr(spt, '/');
634                 if (spt == NULL)
635                         break;
636                 *spt = '\0';
637
638                 /*
639                  * if it exists we assume it is a directory, it is not within
640                  * the spec (at least it seems to read that way) to alter the
641                  * file system for nodes NOT EXPLICITLY stored on the archive.
642                  * If that assumption is changed, you would test the node here
643                  * and figure out how to get rid of it (probably like some
644                  * recursive unlink()) or fix up the directory permissions if
645                  * required (do an access()).
646                  */
647                 if (lstat(name, &sb) == 0) {
648                         *(spt++) = '/';
649                         continue;
650                 }
651
652                 /*
653                  * the path fails at this point, see if we can create the
654                  * needed directory and continue on
655                  */
656                 if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
657                         *spt = '/';
658                         retval = -1;
659                         break;
660                 }
661
662                 /*
663                  * we were able to create the directory. We will tell the
664                  * caller that we found something to fix, and it is ok to try
665                  * and create the node again.
666                  */
667                 retval = 0;
668                 if (pids)
669                         (void)set_ids(name, st_uid, st_gid);
670
671                 /*
672                  * make sure the user doen't have some strange umask that
673                  * causes this newly created directory to be unusable. We fix
674                  * the modes and restore them back to the creation default at
675                  * the end of pax
676                  */
677                 if ((access(name, R_OK | W_OK | X_OK) < 0) &&
678                     (lstat(name, &sb) == 0)) {
679                         set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
680                         add_dir(name, spt - name, &sb, 1);
681                 }
682                 *(spt++) = '/';
683                 continue;
684         }
685         return(retval);
686 }
687
688 /*
689  * set_ftime()
690  *      Set the access time and modification time for a named file. If frc is
691  *      non-zero we force these times to be set even if the user did not
692  *      request access and/or modification time preservation (this is also
693  *      used by -t to reset access times).
694  *      When ign is zero, only those times the user has asked for are set, the
695  *      other ones are left alone. We do not assume the un-documented feature
696  *      of many utimes() implementations that consider a 0 time value as a do
697  *      not set request.
698  */
699
700 #ifdef __STDC__
701 void
702 set_ftime(char *fnm, time_t mtime, time_t atime, int frc)
703 #else
704 void
705 set_ftime(fnm, mtime, atime, frc)
706         char *fnm;
707         time_t mtime;
708         time_t atime;
709         int frc;
710 #endif
711 {
712         static struct timeval tv[2] = {{0L, 0L}, {0L, 0L}};
713         struct stat sb;
714
715         tv[0].tv_sec = (long)atime;
716         tv[1].tv_sec = (long)mtime;
717         if (!frc && (!patime || !pmtime)) {
718                 /*
719                  * if we are not forcing, only set those times the user wants
720                  * set. We get the current values of the times if we need them.
721                  */
722                 if (lstat(fnm, &sb) == 0) {
723                         if (!patime)
724                                 tv[0].tv_sec = (long)sb.st_atime;
725                         if (!pmtime)
726                                 tv[1].tv_sec = (long)sb.st_mtime;
727                 } else
728                         syswarn(0,errno,"Unable to obtain file stats %s", fnm);
729         }
730
731         /*
732          * set the times
733          */
734         if (utimes(fnm, tv) < 0)
735                 syswarn(1, errno, "Access/modification time set failed on: %s",
736                     fnm);
737         return;
738 }
739
740 /*
741  * set_ids()
742  *      set the uid and gid of a file system node
743  * Return:
744  *      0 when set, -1 on failure
745  */
746
747 #ifdef __STDC__
748 int
749 set_ids(char *fnm, uid_t uid, gid_t gid)
750 #else
751 int
752 set_ids(fnm, uid, gid)
753         char *fnm;
754         uid_t uid;
755         gid_t gid;
756 #endif
757 {
758         if (chown(fnm, uid, gid) < 0) {
759                 /*
760                  * ignore EPERM unless in verbose mode or being run by root.
761                  * if running as pax, POSIX requires a warning.
762                  */
763                 if (strcmp(NM_PAX, argv0) == 0 || errno != EPERM || vflag ||
764                     geteuid() == 0)
765                         syswarn(1, errno, "Unable to set file uid/gid of %s",
766                             fnm);
767                 return(-1);
768         }
769         return(0);
770 }
771
772 /*
773  * set_lids()
774  *      set the uid and gid of a file system node
775  * Return:
776  *      0 when set, -1 on failure
777  */
778
779 #ifdef __STDC__
780 int
781 set_lids(char *fnm, uid_t uid, gid_t gid)
782 #else
783 int
784 set_lids(fnm, uid, gid)
785         char *fnm;
786         uid_t uid;
787         gid_t gid;
788 #endif
789 {
790         if (lchown(fnm, uid, gid) < 0) {
791                 /*
792                  * ignore EPERM unless in verbose mode or being run by root.
793                  * if running as pax, POSIX requires a warning.
794                  */
795                 if (strcmp(NM_PAX, argv0) == 0 || errno != EPERM || vflag ||
796                     geteuid() == 0)
797                         syswarn(1, errno, "Unable to set file uid/gid of %s",
798                             fnm);
799                 return(-1);
800         }
801         return(0);
802 }
803
804 /*
805  * set_pmode()
806  *      Set file access mode
807  */
808
809 #ifdef __STDC__
810 void
811 set_pmode(char *fnm, mode_t mode)
812 #else
813 void
814 set_pmode(fnm, mode)
815         char *fnm;
816         mode_t mode;
817 #endif
818 {
819         mode &= ABITS;
820         if (chmod(fnm, mode) < 0)
821                 syswarn(1, errno, "Could not set permissions on %s", fnm);
822         return;
823 }
824
825 /*
826  * file_write()
827  *      Write/copy a file (during copy or archive extract). This routine knows
828  *      how to copy files with lseek holes in it. (Which are read as file
829  *      blocks containing all 0's but do not have any file blocks associated
830  *      with the data). Typical examples of these are files created by dbm
831  *      variants (.pag files). While the file size of these files are huge, the
832  *      actual storage is quite small (the files are sparse). The problem is
833  *      the holes read as all zeros so are probably stored on the archive that
834  *      way (there is no way to determine if the file block is really a hole,
835  *      we only know that a file block of all zero's can be a hole).
836  *      At this writing, no major archive format knows how to archive files
837  *      with holes. However, on extraction (or during copy, -rw) we have to
838  *      deal with these files. Without detecting the holes, the files can
839  *      consume a lot of file space if just written to disk. This replacement
840  *      for write when passed the basic allocation size of a file system block,
841  *      uses lseek whenever it detects the input data is all 0 within that
842  *      file block. In more detail, the strategy is as follows:
843  *      While the input is all zero keep doing an lseek. Keep track of when we
844  *      pass over file block boundries. Only write when we hit a non zero
845  *      input. once we have written a file block, we continue to write it to
846  *      the end (we stop looking at the input). When we reach the start of the
847  *      next file block, start checking for zero blocks again. Working on file
848  *      block boundries significantly reduces the overhead when copying files
849  *      that are NOT very sparse. This overhead (when compared to a write) is
850  *      almost below the measurement resolution on many systems. Without it,
851  *      files with holes cannot be safely copied. It does has a side effect as
852  *      it can put holes into files that did not have them before, but that is
853  *      not a problem since the file contents are unchanged (in fact it saves
854  *      file space). (Except on paging files for diskless clients. But since we
855  *      cannot determine one of those file from here, we ignore them). If this
856  *      ever ends up on a system where CTG files are supported and the holes
857  *      are not desired, just do a conditional test in those routines that
858  *      call file_write() and have it call write() instead. BEFORE CLOSING THE
859  *      FILE, make sure to call file_flush() when the last write finishes with
860  *      an empty block. A lot of file systems will not create an lseek hole at
861  *      the end. In this case we drop a single 0 at the end to force the
862  *      trailing 0's in the file.
863  *      ---Parameters---
864  *      rem: how many bytes left in this file system block
865  *      isempt: have we written to the file block yet (is it empty)
866  *      sz: basic file block allocation size
867  *      cnt: number of bytes on this write
868  *      str: buffer to write
869  * Return:
870  *      number of bytes written, -1 on write (or lseek) error.
871  */
872
873 #ifdef __STDC__
874 int
875 file_write(int fd, char *str, register int cnt, int *rem, int *isempt, int sz,
876         char *name)
877 #else
878 int
879 file_write(fd, str, cnt, rem, isempt, sz, name)
880         int fd;
881         char *str;
882         register int cnt;
883         int *rem;
884         int *isempt;
885         int sz;
886         char *name;
887 #endif
888 {
889         register char *pt;
890         register char *end;
891         register int wcnt;
892         register char *st = str;
893
894         /*
895          * while we have data to process
896          */
897         while (cnt) {
898                 if (!*rem) {
899                         /*
900                          * We are now at the start of file system block again
901                          * (or what we think one is...). start looking for
902                          * empty blocks again
903                          */
904                         *isempt = 1;
905                         *rem = sz;
906                 }
907
908                 /*
909                  * only examine up to the end of the current file block or
910                  * remaining characters to write, whatever is smaller
911                  */
912                 wcnt = MIN(cnt, *rem);
913                 cnt -= wcnt;
914                 *rem -= wcnt;
915                 if (*isempt) {
916                         /*
917                          * have not written to this block yet, so we keep
918                          * looking for zero's
919                          */
920                         pt = st;
921                         end = st + wcnt;
922
923                         /*
924                          * look for a zero filled buffer
925                          */
926                         while ((pt < end) && (*pt == '\0'))
927                                 ++pt;
928
929                         if (pt == end) {
930                                 /*
931                                  * skip, buf is empty so far
932                                  */
933                                 if (lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
934                                         syswarn(1,errno,"File seek on %s",
935                                             name);
936                                         return(-1);
937                                 }
938                                 st = pt;
939                                 continue;
940                         }
941                         /*
942                          * drat, the buf is not zero filled
943                          */
944                         *isempt = 0;
945                 }
946
947                 /*
948                  * have non-zero data in this file system block, have to write
949                  */
950                 if (write(fd, st, wcnt) != wcnt) {
951                         syswarn(1, errno, "Failed write to file %s", name);
952                         return(-1);
953                 }
954                 st += wcnt;
955         }
956         return(st - str);
957 }
958
959 /*
960  * file_flush()
961  *      when the last file block in a file is zero, many file systems will not
962  *      let us create a hole at the end. To get the last block with zeros, we
963  *      write the last BYTE with a zero (back up one byte and write a zero).
964  */
965
966 #ifdef __STDC__
967 void
968 file_flush(int fd, char *fname, int isempt)
969 #else
970 void
971 file_flush(fd, fname, isempt)
972         int fd;
973         char *fname;
974         int isempt;
975 #endif
976 {
977         static char blnk[] = "\0";
978
979         /*
980          * silly test, but make sure we are only called when the last block is
981          * filled with all zeros.
982          */
983         if (!isempt)
984                 return;
985
986         /*
987          * move back one byte and write a zero
988          */
989         if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
990                 syswarn(1, errno, "Failed seek on file %s", fname);
991                 return;
992         }
993
994         if (write(fd, blnk, 1) < 0)
995                 syswarn(1, errno, "Failed write to file %s", fname);
996         return;
997 }
998
999 /*
1000  * rdfile_close()
1001  *      close a file we have beed reading (to copy or archive). If we have to
1002  *      reset access time (tflag) do so (the times are stored in arcn).
1003  */
1004
1005 #ifdef __STDC__
1006 void
1007 rdfile_close(register ARCHD *arcn, register int *fd)
1008 #else
1009 void
1010 rdfile_close(arcn, fd)
1011         register ARCHD *arcn;
1012         register int *fd;
1013 #endif
1014 {
1015         /*
1016          * make sure the file is open
1017          */
1018         if (*fd < 0)
1019                 return;
1020
1021         (void)close(*fd);
1022         *fd = -1;
1023         if (!tflag)
1024                 return;
1025
1026         /*
1027          * user wants last access time reset
1028          */
1029         set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1);
1030         return;
1031 }
1032
1033 /*
1034  * set_crc()
1035  *      read a file to calculate its crc. This is a real drag. Archive formats
1036  *      that have this, end up reading the file twice (we have to write the
1037  *      header WITH the crc before writing the file contents. Oh well...
1038  * Return:
1039  *      0 if was able to calculate the crc, -1 otherwise
1040  */
1041
1042 #ifdef __STDC__
1043 int
1044 set_crc(register ARCHD *arcn, register int fd)
1045 #else
1046 int
1047 set_crc(arcn, fd)
1048         register ARCHD *arcn;
1049         register int fd;
1050 #endif
1051 {
1052         register int i;
1053         register int res;
1054         off_t cpcnt = 0L;
1055         u_long size;
1056         unsigned long crc = 0L;
1057         char tbuf[FILEBLK];
1058         struct stat sb;
1059
1060         if (fd < 0) {
1061                 /*
1062                  * hmm, no fd, should never happen. well no crc then.
1063                  */
1064                 arcn->crc = 0L;
1065                 return(0);
1066         }
1067
1068         if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
1069                 size = (u_long)sizeof(tbuf);
1070
1071         /*
1072          * read all the bytes we think that there are in the file. If the user
1073          * is trying to archive an active file, forget this file.
1074          */
1075         for(;;) {
1076                 if ((res = read(fd, tbuf, size)) <= 0)
1077                         break;
1078                 cpcnt += res;
1079                 for (i = 0; i < res; ++i)
1080                         crc += (tbuf[i] & 0xff);
1081         }
1082
1083         /*
1084          * safety check. we want to avoid archiving files that are active as
1085          * they can create inconsistant archive copies.
1086          */
1087         if (cpcnt != arcn->sb.st_size)
1088                 paxwarn(1, "File changed size %s", arcn->org_name);
1089         else if (fstat(fd, &sb) < 0)
1090                 syswarn(1, errno, "Failed stat on %s", arcn->org_name);
1091         else if (arcn->sb.st_mtime != sb.st_mtime)
1092                 paxwarn(1, "File %s was modified during read", arcn->org_name);
1093         else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
1094                 syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
1095         else {
1096                 arcn->crc = crc;
1097                 return(0);
1098         }
1099         return(-1);
1100 }