1 /** $MirOS: src/usr.bin/xinstall/xinstall.c,v 1.12 2008/04/06 23:33:25 tg Exp $ */
2 /* $OpenBSD: xinstall.c,v 1.42 2004/10/04 05:21:27 jsg Exp $ */
3 /* $NetBSD: xinstall.c,v 1.9 1995/12/20 10:25:17 jonathan Exp $ */
4
5 /*
6 * Copyright (c) 1987, 1993
7 * The Regents of the University of California. All rights reserved.
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. 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
34 #include <sys/param.h>
35 #include <sys/wait.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38
39 #include <ctype.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <getopt.h>
44 #include <grp.h>
45 #include <limits.h>
46 #include <paths.h>
47 #include <pwd.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #undef EX_OK
53 #include <sysexits.h>
54 #include <utime.h>
55
56 #include "pathnames.h"
57
58 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\n\
59 The Regents of the University of California. All rights reserved.\n");
60 __SCCSID("@(#)xinstall.c 8.1 (Berkeley) 7/21/93");
61 __RCSID("$MirOS: src/usr.bin/xinstall/xinstall.c,v 1.12 2008/04/06 23:33:25 tg Exp $");
62
63 #define DIRECTORY 0x01 /* Tell install it's a directory. */
64 #define SETFLAGS 0x02 /* Tell install to set flags. */
65 #ifndef UF_IMMUTABLE
66 #define UF_IMMUTABLE 0
67 #endif
68 #ifndef UF_APPEND
69 #define UF_APPEND 0
70 #endif
71 #ifndef UF_NODUMP
72 #define UF_NODUMP 0
73 #endif
74 #ifndef SF_IMMUTABLE
75 #define SF_IMMUTABLE 0
76 #endif
77 #ifndef SF_APPEND
78 #define SF_APPEND 0
79 #endif
80 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
81 #define BACKUP_SUFFIX ".old"
82 #if !defined(S_BLKSIZE) && defined(S_BLOCK_SIZE)
83 #define S_BLKSIZE S_BLOCK_SIZE
84 #endif
85 #ifndef EFTYPE
86 #ifdef EPROTO
87 #define EFTYPE EPROTO
88 #else
89 #define EFTYPE EINVAL
90 #endif
91 #endif
92
93 #ifdef MAXBSIZE
94 #define IOBUFSZ MAXBSIZE
95 #else
96 #define IOBUFSZ 4096
97 #endif
98
99 struct passwd *pp;
100 struct group *gp;
101 int dobackup, docompare, dodir, dopreserve, dostrip, safecopy;
102 int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
103 char pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
104 char *suffix = BACKUP_SUFFIX;
105 #ifndef __INTERIX
106 uid_t uid;
107 gid_t gid;
108 #endif
109
110 #ifdef NEED_SETMODE_DECL
111 mode_t getmode(const void *, mode_t);
112 void *setmode(const char *);
113 #endif
114
115 void copy(int, char *, int, char *, off_t, int);
116 int compare(int, const char *, size_t, int, const char *, size_t);
117 void install(char *, char *, u_long, u_int);
118 void install_dir(char *);
119 void strip(char *);
120 void usage(void);
121 int create_newfile(char *, struct stat *);
122 int create_tempfile(char *, char *, size_t);
123 int file_write(int, char *, size_t, int *, int *, int);
124 void file_flush(int, int);
125
126 int
main(int argc,char * argv[])127 main(int argc, char *argv[])
128 {
129 struct stat from_sb, to_sb;
130 void *set;
131 #ifdef __APPLE__
132 u_long fset;
133 #else
134 u_int32_t fset;
135 #endif
136 u_int iflags;
137 int ch, no_target;
138 char *flags, *to_name, *group = NULL, *owner = NULL;
139
140 iflags = 0;
141 while ((ch = getopt(argc, argv, "BbCcdf:g:m:o:pSs")) != -1)
142 switch((char)ch) {
143 case 'C':
144 docompare = 1;
145 break;
146 case 'B':
147 suffix = optarg;
148 /* fall through; -B implies -b */
149 case 'b':
150 dobackup = 1;
151 break;
152 case 'c':
153 /* For backwards compatibility. */
154 break;
155 case 'f':
156 #if defined(BSD) || defined(__APPLE__)
157 flags = optarg;
158 if (strtofflags(&flags, &fset, NULL))
159 errx(EX_USAGE, "%s: invalid flag", flags);
160 iflags |= SETFLAGS;
161 #endif
162 break;
163 case 'g':
164 group = optarg;
165 break;
166 case 'm':
167 if (!(set = setmode(optarg)))
168 errx(EX_USAGE, "%s: invalid file mode", optarg);
169 mode = getmode(set, 0);
170 free(set);
171 break;
172 case 'o':
173 owner = optarg;
174 break;
175 case 'p':
176 docompare = dopreserve = 1;
177 break;
178 case 'S':
179 safecopy = 1;
180 break;
181 case 's':
182 dostrip = 1;
183 break;
184 case 'd':
185 dodir = 1;
186 break;
187 case '?':
188 default:
189 usage();
190 }
191 argc -= optind;
192 argv += optind;
193
194 /* some options make no sense when creating directories */
195 if ((safecopy || docompare || dostrip) && dodir)
196 usage();
197
198 /* must have at least two arguments, except when creating directories */
199 if (argc < 2 && !dodir)
200 usage();
201
202 /* need to make a temp copy so we can compare stripped version */
203 if (docompare && dostrip)
204 safecopy = 1;
205
206 #ifndef __INTERIX
207 /* get group and owner id's */
208 if (group && !(gp = getgrnam(group)) && !isdigit(*group))
209 errx(EX_NOUSER, "unknown group %s", group);
210 gid = (group) ? ((gp) ? gp->gr_gid : (gid_t)strtoul(group, NULL, 10)) : (gid_t)-1;
211 if (owner && !(pp = getpwnam(owner)) && !isdigit(*owner))
212 errx(EX_NOUSER, "unknown user %s", owner);
213 uid = (owner) ? ((pp) ? pp->pw_uid : (uid_t)strtoul(owner, NULL, 10)) : (uid_t)-1;
214 #endif
215
216 if (dodir) {
217 for (; *argv != NULL; ++argv)
218 install_dir(*argv);
219 exit(EX_OK);
220 /* NOTREACHED */
221 }
222
223 no_target = stat(to_name = argv[argc - 1], &to_sb);
224 if (!no_target && S_ISDIR(to_sb.st_mode)) {
225 for (; *argv != to_name; ++argv)
226 install(*argv, to_name, fset, iflags | DIRECTORY);
227 exit(EX_OK);
228 /* NOTREACHED */
229 }
230
231 /* can't do file1 file2 directory/file */
232 if (argc != 2)
233 errx(EX_OSERR, "Target: %s", argv[argc-1]);
234
235 if (!no_target) {
236 if (stat(*argv, &from_sb))
237 err(EX_OSERR, "%s", *argv);
238 if (!S_ISREG(to_sb.st_mode))
239 errx(EX_OSERR, "%s: %s", to_name, strerror(EFTYPE));
240 if (to_sb.st_dev == from_sb.st_dev &&
241 to_sb.st_ino == from_sb.st_ino)
242 errx(EX_USAGE, "%s and %s are the same file", *argv, to_name);
243 }
244 install(*argv, to_name, fset, iflags);
245 exit(EX_OK);
246 /* NOTREACHED */
247 }
248
249 /*
250 * install --
251 * build a path name and install the file
252 */
253 void
install(char * from_name,char * to_name,u_long fset,u_int flags)254 install(char *from_name, char *to_name, u_long fset, u_int flags)
255 {
256 struct stat from_sb, to_sb;
257 struct utimbuf utb;
258 int devnull, from_fd, to_fd, serrno, files_match = 0;
259 char *p;
260
261 (void)memset((void *)&from_sb, 0, sizeof(from_sb));
262 (void)memset((void *)&to_sb, 0, sizeof(to_sb));
263
264 /* If try to install NULL file to a directory, fails. */
265 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
266 if (stat(from_name, &from_sb))
267 err(EX_OSERR, "%s", from_name);
268 if (!S_ISREG(from_sb.st_mode))
269 errx(EX_OSERR, "%s: %s", from_name, strerror(EFTYPE));
270 /* Build the target path. */
271 if (flags & DIRECTORY) {
272 (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
273 to_name,
274 (p = strrchr(from_name, '/')) ? ++p : from_name);
275 to_name = pathbuf;
276 }
277 devnull = 0;
278 } else {
279 devnull = 1;
280 }
281
282 if (stat(to_name, &to_sb) == 0) {
283 /* Only compare against regular files. */
284 if (docompare && !S_ISREG(to_sb.st_mode)) {
285 docompare = 0;
286 warnx("%s: %s", to_name, strerror(EFTYPE));
287 }
288 } else if (docompare) {
289 /* File does not exist so silently ignore compare flag. */
290 docompare = 0;
291 }
292
293 if (safecopy) {
294 to_fd = create_tempfile(to_name, tempfile, sizeof(tempfile));
295 if (to_fd < 0)
296 err(EX_OSERR, "%s", tempfile);
297 } else if (docompare && !dostrip) {
298 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
299 err(EX_OSERR, "%s", to_name);
300 } else {
301 if ((to_fd = create_newfile(to_name, &to_sb)) < 0)
302 err(EX_OSERR, "%s", to_name);
303 }
304
305 if (!devnull) {
306 if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
307 serrno = errno;
308 (void)unlink(safecopy ? tempfile : to_name);
309 errx(EX_OSERR, "%s: %s", from_name, strerror(serrno));
310 }
311
312 if (docompare && !safecopy) {
313 files_match = !(compare(from_fd, from_name,
314 (size_t)from_sb.st_size, to_fd,
315 to_name, (size_t)to_sb.st_size));
316
317 /* Truncate "to" file for copy unless we match */
318 if (!files_match) {
319 (void)close(to_fd);
320 if ((to_fd = create_newfile(to_name, &to_sb)) < 0)
321 err(EX_OSERR, "%s", to_name);
322 }
323 }
324 if (!files_match)
325 copy(from_fd, from_name, to_fd,
326 safecopy ? tempfile : to_name, from_sb.st_size,
327 ((off_t)from_sb.st_blocks * S_BLKSIZE < from_sb.st_size));
328 }
329
330 if (dostrip) {
331 strip(safecopy ? tempfile : to_name);
332
333 /*
334 * Re-open our fd on the target, in case we used a strip
335 * that does not work in-place -- like gnu binutils strip.
336 */
337 close(to_fd);
338 if ((to_fd = open(safecopy ? tempfile : to_name, O_RDONLY,
339 0)) < 0)
340 err(EX_OSERR, "stripping %s", to_name);
341 }
342
343 /*
344 * Compare the (possibly stripped) temp file to the target.
345 */
346 if (safecopy && docompare) {
347 int temp_fd = to_fd;
348 struct stat temp_sb;
349
350 /* Re-open to_fd using the real target name. */
351 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
352 err(EX_OSERR, "%s", to_name);
353
354 if (fstat(temp_fd, &temp_sb)) {
355 serrno = errno;
356 (void)unlink(tempfile);
357 errx(EX_OSERR, "%s: %s", tempfile, strerror(serrno));
358 }
359
360 if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
361 to_name, (size_t)to_sb.st_size) == 0) {
362 /*
363 * If target has more than one link we need to
364 * replace it in order to snap the extra links.
365 * Need to preserve target file times, though.
366 */
367 if (to_sb.st_nlink != 1) {
368 utb.actime = to_sb.st_atime;
369 utb.modtime = to_sb.st_mtime;
370 (void)utime(tempfile, &utb);
371 } else {
372 files_match = 1;
373 (void)unlink(tempfile);
374 }
375 (void) close(temp_fd);
376 }
377 }
378
379 /*
380 * Move the new file into place if doing a safe copy
381 * and the files are different (or just not compared).
382 */
383 if (safecopy && !files_match) {
384 #if defined(BSD) || defined(__APPLE__)
385 /* Try to turn off the immutable bits. */
386 if (to_sb.st_flags & (NOCHANGEBITS))
387 (void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
388 #endif
389 if (dobackup) {
390 char backup[MAXPATHLEN];
391 (void)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
392 suffix);
393 /* It is ok for the target file not to exist. */
394 if (rename(to_name, backup) < 0 && errno != ENOENT) {
395 serrno = errno;
396 unlink(tempfile);
397 errx(EX_OSERR, "rename: %s to %s: %s", to_name,
398 backup, strerror(serrno));
399 }
400 }
401 if (rename(tempfile, to_name) < 0 ) {
402 serrno = errno;
403 unlink(tempfile);
404 errx(EX_OSERR, "rename: %s to %s: %s", tempfile,
405 to_name, strerror(serrno));
406 }
407
408 /* Re-open to_fd so we aren't hosed by the rename(2). */
409 (void) close(to_fd);
410 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
411 err(EX_OSERR, "%s", to_name);
412 }
413
414 /*
415 * Preserve the timestamp of the source file if necessary.
416 */
417 if (dopreserve && !files_match) {
418 utb.actime = from_sb.st_atime;
419 utb.modtime = from_sb.st_mtime;
420 (void)utime(to_name, &utb);
421 }
422
423 /*
424 * Set owner, group, mode for target; do the chown first,
425 * chown may lose the setuid bits.
426 */
427 #ifndef __INTERIX
428 if ((gid != (gid_t)-1 || uid != (uid_t)-1) && fchown(to_fd, uid, gid)) {
429 serrno = errno;
430 (void)unlink(to_name);
431 errx(EX_OSERR, "%s: chown/chgrp: %s", to_name, strerror(serrno));
432 }
433 #endif
434 if (fchmod(to_fd, mode)) {
435 serrno = errno;
436 (void)unlink(to_name);
437 errx(EX_OSERR, "%s: chmod: %s", to_name, strerror(serrno));
438 }
439
440 #if defined(BSD) || defined(__APPLE__)
441 /*
442 * If provided a set of flags, set them, otherwise, preserve the
443 * flags, except for the dump flag.
444 */
445 if (fchflags(to_fd,
446 flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
447 if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
448 warnx("%s: chflags: %s", to_name, strerror(errno));
449 }
450 #endif
451
452 (void)close(to_fd);
453 if (!devnull)
454 (void)close(from_fd);
455 }
456
457 /*
458 * copy --
459 * copy from one file to another
460 */
461 void
copy(int from_fd,char * from_name,int to_fd,char * to_name,off_t size,int sparse)462 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size,
463 int sparse)
464 {
465 ssize_t nr, nw;
466 int serrno;
467 char *p, buf[IOBUFSZ];
468
469 /* Rewind file descriptors. */
470 if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
471 err(EX_OSERR, "lseek: %s", from_name);
472 if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
473 err(EX_OSERR, "lseek: %s", to_name);
474
475 /*
476 * Mmap and write if less than 8M (the limit is so we don't totally
477 * trash memory on big files. This is really a minor hack, but it
478 * wins some CPU back. Sparse files need special treatment.
479 */
480 if (!sparse && size <= 8 * 1048576) {
481 volatile size_t siz;
482
483 if ((p = mmap(NULL, (size_t)size, PROT_READ, MAP_PRIVATE,
484 from_fd, (off_t)0)) == MAP_FAILED) {
485 serrno = errno;
486 (void)unlink(to_name);
487 errx(EX_OSERR, "%s: %s", from_name, strerror(serrno));
488 }
489 if (size)
490 madvise(p, size, MADV_SEQUENTIAL);
491 siz = (size_t)size;
492 if ((nw = write(to_fd, p, siz)) != siz) {
493 serrno = errno;
494 (void)unlink(to_name);
495 errx(EX_OSERR, "%s: %s",
496 to_name, strerror(nw > 0 ? EIO : serrno));
497 }
498 (void) munmap(p, (size_t)size);
499 } else {
500 int sz, rem, isem = 1;
501 struct stat sb;
502
503 /*
504 * Pass the blocksize of the file being written to the write
505 * routine. if the size is zero, use the default S_BLKSIZE.
506 */
507 if (fstat(to_fd, &sb) != 0 || sb.st_blksize == 0)
508 sz = S_BLKSIZE;
509 else
510 sz = sb.st_blksize;
511 rem = sz;
512
513 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
514 if (sparse)
515 nw = file_write(to_fd, buf, nr, &rem, &isem, sz);
516 else
517 nw = write(to_fd, buf, nr);
518 if (nw != nr) {
519 serrno = errno;
520 (void)unlink(to_name);
521 errx(EX_OSERR, "%s: %s",
522 to_name, strerror(nw > 0 ? EIO : serrno));
523 }
524 }
525 if (sparse)
526 file_flush(to_fd, isem);
527 if (nr != 0) {
528 serrno = errno;
529 (void)unlink(to_name);
530 errx(EX_OSERR, "%s: %s", from_name, strerror(serrno));
531 }
532 }
533 }
534
535 /*
536 * compare --
537 * compare two files; non-zero means files differ
538 */
539 int
compare(int from_fd,const char * from_name,size_t from_len,int to_fd,const char * to_name,size_t to_len)540 compare(int from_fd, const char *from_name, size_t from_len, int to_fd,
541 const char *to_name, size_t to_len)
542 {
543 caddr_t p1, p2;
544 size_t length, remainder;
545 off_t from_off, to_off;
546 int dfound;
547
548 if (from_len != to_len)
549 return(1);
550
551 /*
552 * Compare the two files being careful not to mmap
553 * more than 8M at a time.
554 */
555 from_off = to_off = (off_t)0;
556 remainder = from_len;
557 do {
558 length = MIN(remainder, 8 * 1048576);
559 remainder -= length;
560
561 if ((p1 = mmap(NULL, length, PROT_READ, MAP_PRIVATE,
562 from_fd, from_off)) == MAP_FAILED)
563 err(EX_OSERR, "%s", from_name);
564 if ((p2 = mmap(NULL, length, PROT_READ, MAP_PRIVATE,
565 to_fd, to_off)) == MAP_FAILED)
566 err(EX_OSERR, "%s", to_name);
567 if (length) {
568 madvise(p1, length, MADV_SEQUENTIAL);
569 madvise(p2, length, MADV_SEQUENTIAL);
570 }
571
572 dfound = memcmp(p1, p2, length);
573
574 (void) munmap(p1, length);
575 (void) munmap(p2, length);
576
577 from_off += length;
578 to_off += length;
579
580 } while (!dfound && remainder > 0);
581
582 return(dfound);
583 }
584
585 /*
586 * strip --
587 * use strip(1) to strip the target file
588 */
589 void
strip(char * to_name)590 strip(char *to_name)
591 {
592 int serrno, status;
593 char * volatile path_strip;
594
595 if (
596 #if !defined(__INTERIX) && !defined(__GLIBC__)
597 issetugid() ||
598 #endif
599 (path_strip = getenv("STRIP")) == NULL)
600 path_strip = _PATH_STRIP;
601
602 switch (vfork()) {
603 case -1:
604 serrno = errno;
605 (void)unlink(to_name);
606 errx(EX_TEMPFAIL, "forks: %s", strerror(serrno));
607 case 0:
608 execl(path_strip, "strip", to_name, (char *)NULL);
609 warn("%s", path_strip);
610 _exit(EX_OSERR);
611 default:
612 if (wait(&status) == -1 || !WIFEXITED(status))
613 (void)unlink(to_name);
614 }
615 }
616
617 /*
618 * install_dir --
619 * build directory hierarchy
620 */
621 void
install_dir(char * path)622 install_dir(char *path)
623 {
624 char *p;
625 struct stat sb;
626 int ch;
627
628 for (p = path;; ++p)
629 if (!*p || (p != path && *p == '/')) {
630 ch = *p;
631 *p = '\0';
632 if (stat(path, &sb)) {
633 if (errno != ENOENT || mkdir(path, 0777) < 0) {
634 err(EX_OSERR, "%s", path);
635 /* NOTREACHED */
636 }
637 }
638 if (!(*p = ch))
639 break;
640 }
641
642 #ifndef __INTERIX
643 if (((gid != (gid_t)-1 || uid != (uid_t)-1) && chown(path, uid, gid)) ||
644 chmod(path, mode)) {
645 warn("%s", path);
646 }
647 #endif
648 }
649
650 /*
651 * usage --
652 * print a usage message and die
653 */
654 void
usage(void)655 usage(void)
656 {
657 (void)fprintf(stderr, "\
658 usage: install [-bCcdpSs] [-B suffix] [-f flags] [-g group] [-m mode] [-o owner]\n source [...] target [...]\n");
659 exit(EX_USAGE);
660 /* NOTREACHED */
661 }
662
663 /*
664 * create_tempfile --
665 * create a temporary file based on path and open it
666 */
667 int
create_tempfile(char * path,char * temp,size_t tsize)668 create_tempfile(char *path, char *temp, size_t tsize)
669 {
670 char *p;
671
672 (void)strncpy(temp, path, tsize);
673 temp[tsize - 1] = '\0';
674 if ((p = strrchr(temp, '/')))
675 p++;
676 else
677 p = temp;
678 (void)strncpy(p, "INS@XXXXXXXXXX", &temp[tsize - 1] - p);
679 temp[tsize - 1] = '\0';
680
681 return(mkstemp(temp));
682 }
683
684 /*
685 * create_newfile --
686 * create a new file, overwriting an existing one if necessary
687 */
688 int
create_newfile(char * path,struct stat * sbp)689 create_newfile(char *path, struct stat *sbp)
690 {
691 char backup[MAXPATHLEN];
692
693 /*
694 * Unlink now... avoid ETXTBSY errors later. Try and turn
695 * off the append/immutable bits -- if we fail, go ahead,
696 * it might work.
697 */
698 #if defined(BSD) || defined(__APPLE__)
699 if (sbp->st_flags & (NOCHANGEBITS))
700 (void)chflags(path, sbp->st_flags & ~(NOCHANGEBITS));
701 #endif
702
703 if (dobackup) {
704 (void)snprintf(backup, MAXPATHLEN, "%s%s", path, suffix);
705 /* It is ok for the target file not to exist. */
706 if (rename(path, backup) < 0 && errno != ENOENT)
707 err(EX_OSERR, "rename: %s to %s (errno %d)", path, backup, errno);
708 } else
709 (void)unlink(path);
710
711 return(open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR));
712 }
713
714 /*
715 * file_write()
716 * Write/copy a file (during copy or archive extract). This routine knows
717 * how to copy files with lseek holes in it. (Which are read as file
718 * blocks containing all 0's but do not have any file blocks associated
719 * with the data). Typical examples of these are files created by dbm
720 * variants (.pag files). While the file size of these files are huge, the
721 * actual storage is quite small (the files are sparse). The problem is
722 * the holes read as all zeros so are probably stored on the archive that
723 * way (there is no way to determine if the file block is really a hole,
724 * we only know that a file block of all zero's can be a hole).
725 * At this writing, no major archive format knows how to archive files
726 * with holes. However, on extraction (or during copy, -rw) we have to
727 * deal with these files. Without detecting the holes, the files can
728 * consume a lot of file space if just written to disk. This replacement
729 * for write when passed the basic allocation size of a file system block,
730 * uses lseek whenever it detects the input data is all 0 within that
731 * file block. In more detail, the strategy is as follows:
732 * While the input is all zero keep doing an lseek. Keep track of when we
733 * pass over file block boundries. Only write when we hit a non zero
734 * input. once we have written a file block, we continue to write it to
735 * the end (we stop looking at the input). When we reach the start of the
736 * next file block, start checking for zero blocks again. Working on file
737 * block boundries significantly reduces the overhead when copying files
738 * that are NOT very sparse. This overhead (when compared to a write) is
739 * almost below the measurement resolution on many systems. Without it,
740 * files with holes cannot be safely copied. It does has a side effect as
741 * it can put holes into files that did not have them before, but that is
742 * not a problem since the file contents are unchanged (in fact it saves
743 * file space). (Except on paging files for diskless clients. But since we
744 * cannot determine one of those file from here, we ignore them). If this
745 * ever ends up on a system where CTG files are supported and the holes
746 * are not desired, just do a conditional test in those routines that
747 * call file_write() and have it call write() instead. BEFORE CLOSING THE
748 * FILE, make sure to call file_flush() when the last write finishes with
749 * an empty block. A lot of file systems will not create an lseek hole at
750 * the end. In this case we drop a single 0 at the end to force the
751 * trailing 0's in the file.
752 * ---Parameters---
753 * rem: how many bytes left in this file system block
754 * isempt: have we written to the file block yet (is it empty)
755 * sz: basic file block allocation size
756 * cnt: number of bytes on this write
757 * str: buffer to write
758 * Return:
759 * number of bytes written, -1 on write (or lseek) error.
760 */
761
762 int
file_write(int fd,char * str,size_t cnt,int * rem,int * isempt,int sz)763 file_write(int fd, char *str, size_t cnt, int *rem, int *isempt, int sz)
764 {
765 char *pt;
766 char *end;
767 size_t wcnt;
768 char *st = str;
769
770 /*
771 * while we have data to process
772 */
773 while (cnt) {
774 if (!*rem) {
775 /*
776 * We are now at the start of file system block again
777 * (or what we think one is...). start looking for
778 * empty blocks again
779 */
780 *isempt = 1;
781 *rem = sz;
782 }
783
784 /*
785 * only examine up to the end of the current file block or
786 * remaining characters to write, whatever is smaller
787 */
788 wcnt = MIN(cnt, *rem);
789 cnt -= wcnt;
790 *rem -= wcnt;
791 if (*isempt) {
792 /*
793 * have not written to this block yet, so we keep
794 * looking for zero's
795 */
796 pt = st;
797 end = st + wcnt;
798
799 /*
800 * look for a zero filled buffer
801 */
802 while ((pt < end) && (*pt == '\0'))
803 ++pt;
804
805 if (pt == end) {
806 /*
807 * skip, buf is empty so far
808 */
809 if (lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
810 warn("lseek");
811 return(-1);
812 }
813 st = pt;
814 continue;
815 }
816 /*
817 * drat, the buf is not zero filled
818 */
819 *isempt = 0;
820 }
821
822 /*
823 * have non-zero data in this file system block, have to write
824 */
825 if (write(fd, st, wcnt) != wcnt) {
826 warn("write");
827 return(-1);
828 }
829 st += wcnt;
830 }
831 return(st - str);
832 }
833
834 /*
835 * file_flush()
836 * when the last file block in a file is zero, many file systems will not
837 * let us create a hole at the end. To get the last block with zeros, we
838 * write the last BYTE with a zero (back up one byte and write a zero).
839 */
840 void
file_flush(int fd,int isempt)841 file_flush(int fd, int isempt)
842 {
843 static char blnk[] = "\0";
844
845 /*
846 * silly test, but make sure we are only called when the last block is
847 * filled with all zeros.
848 */
849 if (!isempt)
850 return;
851
852 /*
853 * move back one byte and write a zero
854 */
855 if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
856 warn("Failed seek on file");
857 return;
858 }
859
860 if (write(fd, blnk, 1) < 0)
861 warn("Failed write to file");
862 return;
863 }
864