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