Debian Codegraph @

pax.c

raw symbols SCIP
1 /* $OpenBSD: pax.c,v 1.52 2018/09/13 12:33:43 millert Exp $ */
2 /* $NetBSD: pax.c,v 1.5 1996/03/26 23:54:20 mrg Exp $ */
3
4 /*-
5 * Copyright (c) 2012, 2015, 2016, 2017
6 * mirabilos <[email protected]>
7 * Copyright (c) 1992 Keith Muller.
8 * Copyright (c) 1992, 1993
9 * The Regents of the University of California. All rights reserved.
10 *
11 * This code is derived from software contributed to Berkeley by
12 * Keith Muller of the University of California, San Diego.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39 #include <sys/types.h>
40 #if HAVE_BOTH_TIME_H
41 #include <sys/time.h>
42 #include <time.h>
43 #elif HAVE_SYS_TIME_H
44 #include <sys/time.h>
45 #elif HAVE_TIME_H
46 #include <time.h>
47 #endif
48 #if HAVE_SYS_RESOURCE_H
49 #include <sys/resource.h>
50 #endif
51 #include <sys/stat.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #if HAVE_GRP_H
56 #include <grp.h>
57 #endif
58 #if HAVE_PATHS_H
59 #include <paths.h>
60 #endif
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #if HAVE_STRINGS_H
67 #include <strings.h>
68 #endif
69 #include <unistd.h>
70
71 #include "pax.h"
72 #include "extern.h"
73
74 __RCSID("$MirOS: src/bin/pax/pax.c,v 1.29 2018/12/13 07:09:11 tg Exp $");
75
76 static int gen_init(void);
77
78 /*
79 * PAX main routines, general globals and some simple start up routines
80 */
81
82 /*
83 * Variables that can be accessed by any routine within pax
84 */
85 signed char act = ERROR; /* read/write/append/copy */
86 const FSUB *frmt = NULL; /* archive format type */
87 signed char cflag; /* match all EXCEPT pattern/file */
88 signed char cwdfd; /* starting cwd */
89 signed char dflag; /* directory member match only */
90 signed char iflag; /* interactive file/archive rename */
91 signed char kflag; /* do not overwrite existing files */
92 signed char lflag; /* use hard links when possible */
93 signed char nflag; /* select first archive member match */
94 signed char tflag; /* restore access time after read */
95 signed char uflag; /* ignore older modification time files */
96 signed char Vflag = 0; /* print a dot for each file processed */
97 signed char vflag; /* produce verbose output */
98 signed char Dflag; /* same as uflag except inode change time */
99 signed char Hflag; /* follow command line symlinks (write only) */
100 signed char Lflag; /* follow symlinks when writing */
101 signed char Xflag; /* archive files with same device id only */
102 signed char Yflag; /* same as Dflag except after name mode */
103 signed char Zflag; /* same as uflag except after name mode */
104 signed char zeroflag; /* use \0 as pathname terminator */
105 signed char vfpart = 0; /* is partial verbose output in progress */
106 signed char patime = 1; /* preserve file access time */
107 signed char pmtime = 1; /* preserve file modification times */
108 signed char nodirs; /* do not create directories as needed */
109 signed char pmode; /* preserve file mode bits */
110 signed char pids; /* preserve file uid/gid */
111 signed char rmleadslash = 0; /* remove leading '/' from pathnames */
112 signed char exit_val; /* exit value */
113 signed char docrc; /* check/create file crc */
114 char *dirptr; /* destination dir in a copy */
115 const char *argv0; /* root of argv[0] */
116 enum op_mode op_mode; /* what program are we acting as? */
117 sigset_t s_mask; /* signal mask for cleanup critical sect */
118 FILE *listf; /* fp to print file list to (default stderr) */
119 int listfd = STDERR_FILENO; /* fd matching listf, for sighandler output */
120 char *tempfile; /* tempfile to use for mkstemp(3) */
121 char *tempbase; /* basename of tempfile to use for mkstemp(3) */
122 time_t now; /* time of program start */
123
124 /*
125 * PAX - Portable Archive Interchange
126 *
127 * A utility to read, write, and write lists of the members of archive
128 * files and copy directory hierarchies. A variety of archive formats
129 * are supported (some are described in POSIX 1003.1 10.1):
130 *
131 * ustar - 10.1.1 extended tar interchange format
132 * cpio - 10.1.2 extended cpio interchange format
133 * tar - old BSD 4.3 tar format
134 * binary cpio - old cpio with binary header format
135 * sysVR4 cpio - with and without CRC
136 *
137 * This version is a superset of IEEE Std 1003.2b-d3
138 *
139 * Summary of Extensions to the IEEE Standard:
140 *
141 * 1 READ ENHANCEMENTS
142 * 1.1 Operations which read archives will continue to operate even when
143 * processing archives which may be damaged, truncated, or fail to meet
144 * format specs in several different ways. Damaged sections of archives
145 * are detected and avoided if possible. Attempts will be made to resync
146 * archive read operations even with badly damaged media.
147 * 1.2 Blocksize requirements are not strictly enforced on archive read.
148 * Tapes which have variable sized records can be read without errors.
149 * 1.3 The user can specify via the non-standard option flag -E if error
150 * resync operation should stop on a media error, try a specified number
151 * of times to correct, or try to correct forever.
152 * 1.4 Sparse files (lseek holes) stored on the archive (but stored with blocks
153 * of all zeros will be restored with holes appropriate for the target
154 * filesystem
155 * 1.5 The user is notified whenever something is found during archive
156 * read operations which violates spec (but the read will continue).
157 * 1.6 Multiple archive volumes can be read and may span over different
158 * archive devices
159 * 1.7 Rigidly restores all file attributes exactly as they are stored on the
160 * archive.
161 * 1.8 Modification change time ranges can be specified via multiple -T
162 * options. These allow a user to select files whose modification time
163 * lies within a specific time range.
164 * 1.9 Files can be selected based on owner (user name or uid) via one or more
165 * -U options.
166 * 1.10 Files can be selected based on group (group name or gid) via one o
167 * more -G options.
168 * 1.11 File modification time can be checked against existing file after
169 * name modification (-Z)
170 *
171 * 2 WRITE ENHANCEMENTS
172 * 2.1 Write operation will stop instead of allowing a user to create a flawed
173 * flawed archive (due to any problem).
174 * 2.2 Archives written by pax are forced to strictly conform to both the
175 * archive and pax the specific format specifications.
176 * 2.3 Blocking size and format is rigidly enforced on writes.
177 * 2.4 Formats which may exhibit header overflow problems (they have fields
178 * too small for large filesystems, such as inode number storage), use
179 * routines designed to repair this problem. These techniques still
180 * conform to both pax and format specifications, but no longer truncate
181 * these fields. This removes any restrictions on using these archive
182 * formats on large filesystems.
183 * 2.5 Multiple archive volumes can be written and may span over different
184 * archive devices
185 * 2.6 A archive volume record limit allows the user to specify the number
186 * of bytes stored on an archive volume. When reached the user is
187 * prompted for the next archive volume. This is specified with the
188 * non-standard -B flag. The limit is rounded up to the next blocksize.
189 * 2.7 All archive padding during write use zero filled sections. This makes
190 * it much easier to pull data out of flawed archive during read
191 * operations.
192 * 2.8 Access time reset with the -t applies to all file nodes (including
193 * directories).
194 * 2.9 Symbolic links can be followed with -L (optional in the spec).
195 * 2.10 Modification or inode change time ranges can be specified via
196 * multiple -T options. These allow a user to select files whose
197 * modification or inode change time lies within a specific time range.
198 * 2.11 Files can be selected based on owner (user name or uid) via one or more
199 * -U options.
200 * 2.12 Files can be selected based on group (group name or gid) via one o
201 * more -G options.
202 * 2.13 Symlinks which appear on the command line can be followed (without
203 * following other symlinks; -H flag)
204 *
205 * 3 COPY ENHANCEMENTS
206 * 3.1 Sparse files (lseek holes) can be copied without expanding the holes
207 * into zero filled blocks. The file copy is created with holes which are
208 * appropriate for the target filesystem
209 * 3.2 Access time as well as modification time on copied file trees can be
210 * preserved with the appropriate -p options.
211 * 3.3 Access time reset with the -t applies to all file nodes (including
212 * directories).
213 * 3.4 Symbolic links can be followed with -L (optional in the spec).
214 * 3.5 Modification or inode change time ranges can be specified via
215 * multiple -T options. These allow a user to select files whose
216 * modification or inode change time lies within a specific time range.
217 * 3.6 Files can be selected based on owner (user name or uid) via one or more
218 * -U options.
219 * 3.7 Files can be selected based on group (group name or gid) via one o
220 * more -G options.
221 * 3.8 Symlinks which appear on the command line can be followed (without
222 * following other symlinks; -H flag)
223 * 3.9 File inode change time can be checked against existing file before
224 * name modification (-D)
225 * 3.10 File inode change time can be checked against existing file after
226 * name modification (-Y)
227 * 3.11 File modification time can be checked against existing file after
228 * name modification (-Z)
229 *
230 * 4 GENERAL ENHANCEMENTS
231 * 4.1 Internal structure is designed to isolate format dependent and
232 * independent functions. Formats are selected via a format driver table.
233 * This encourages the addition of new archive formats by only having to
234 * write those routines which id, read and write the archive header.
235 */
236
237 /*
238 * main()
239 * parse options, set up and operate as specified by the user.
240 * any operational flaw will set exit_val to non-zero
241 * Return: 0 if ok, 1 otherwise
242 */
243
244 int
245 main(int argc, char **argv)
246 {
247 const char *tmpdir;
248 size_t tdlen;
249
250 /* may not be a constant, thus initialising early */
251 listf = stderr;
252
253 now = time(NULL);
254
255 /*
256 * Keep a reference to cwd, so we can always come back home.
257 */
258 cwdfd = binopen2(BO_CLEXEC, ".", O_RDONLY);
259 if (cwdfd < 0) {
260 syswarn(1, errno, "Cannot open current working directory.");
261 return(exit_val);
262 }
263
264 /*
265 * Where should we put temporary files?
266 */
267 if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
268 tmpdir = _PATH_TMP;
269 tdlen = strlen(tmpdir);
270 while (tdlen > 0 && tmpdir[tdlen - 1] == '/')
271 tdlen--;
272 tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
273 if (tempfile == NULL) {
274 paxwarn(1, "%s for %s", "Out of memory",
275 "temp file name");
276 return (exit_val);
277 }
278 if (tdlen)
279 memcpy(tempfile, tmpdir, tdlen);
280 tempbase = tempfile + tdlen;
281 *tempbase++ = '/';
282
283 #if HAVE_SETPGENT
284 /*
285 * keep passwd and group files open for faster lookups.
286 */
287 setpassent(1);
288 setgroupent(1);
289 #endif
290
291 /*
292 * parse options, determine operational mode, general init
293 */
294 options(argc, argv);
295 if ((gen_init() < 0) || (tty_init() < 0))
296 return(exit_val);
297
298 #if HAVE_PLEDGE
299 /*
300 * pmode needs to restore setugid bits when extracting or copying,
301 * so can't pledge at all then.
302 */
303 if (pmode == 0 || (act != EXTRACT && act != COPY)) {
304 if (pledge("stdio rpath wpath cpath fattr dpath getpw proc exec tape",
305 NULL) == -1)
306 err(1, "pledge");
307
308 /* Copy mode, or no gzip -- don't need to fork/exec. */
309 if (compress_program == NULL || act == COPY) {
310 if (pledge("stdio rpath wpath cpath fattr dpath getpw tape",
311 NULL) == -1)
312 err(1, "pledge");
313 }
314 }
315 #endif
316
317 /* make list fd independent and line-buffered */
318 if ((listfd = dup(fileno(listf))) < 0 ||
319 !(listf = fdopen(listfd, "wb"))) {
320 syswarn(1, errno, "Cannot open list file descriptor");
321 return (exit_val);
322 }
323 if (fcntl(listfd, F_SETFD, FD_CLOEXEC) == -1)
324 syswarn(0, errno, "%s on list file descriptor",
325 "Failed to set the close-on-exec flag");
326 setlinebuf(listf);
327
328 /*
329 * select a primary operation mode
330 */
331 switch (act) {
332 case EXTRACT:
333 extract();
334 break;
335 case ARCHIVE:
336 archive();
337 break;
338 case APPND:
339 if (compress_program != NULL)
340 errx(1, "cannot compress while appending");
341 append();
342 break;
343 case COPY:
344 copy();
345 break;
346 default:
347 /* for ar_io.c etc. */
348 act = LIST;
349 /* FALLTHROUGH */
350 case LIST:
351 list();
352 break;
353 }
354 return(exit_val);
355 }
356
357 /*
358 * sig_cleanup()
359 * when interrupted we try to do whatever delayed processing we can.
360 * This is not critical, but we really ought to limit our damage when we
361 * are aborted by the user.
362 * Return:
363 * never....
364 */
365
366 void
367 sig_cleanup(int which_sig)
368 {
369 /*
370 * Restore modes and times for any dirs we may have created
371 * or any dirs we may have read. Set vflag and vfpart so the
372 * user will clearly see the message on a line by itself.
373 */
374 vflag = vfpart = 1;
375
376 /* paxwarn() uses stdio; fake it as well as we can */
377 if (which_sig == SIGXCPU)
378 dprintf(STDERR_FILENO, "\nCPU time limit reached, cleaning up.\n");
379 else if (!which_sig)
380 dprintf(STDERR_FILENO, "\nCowardly giving up, trying to clean up.\n");
381 else
382 dprintf(STDERR_FILENO, "\nSignal caught, cleaning up.\n");
383
384 ar_close(1);
385 sltab_process(1);
386 proc_dir(1);
387 if (tflag)
388 atdir_end();
389 _exit(1);
390 }
391
392 /*
393 * setup_sig()
394 * set a signal to be caught, but only if it isn't being ignored already
395 */
396
397 static int
398 setup_sig(int sig, const struct sigaction *n_hand)
399 {
400 struct sigaction o_hand;
401
402 if (sigaction(sig, NULL, &o_hand) < 0)
403 return (-1);
404
405 if (o_hand.sa_handler == SIG_IGN)
406 return (0);
407
408 return (sigaction(sig, n_hand, NULL));
409 }
410
411 /*
412 * gen_init()
413 * general setup routines. Not all are required, but they really help
414 * when dealing with a medium to large sized archives.
415 */
416
417 static int
418 gen_init(void)
419 {
420 struct rlimit reslimit;
421 struct sigaction n_hand;
422
423 /*
424 * Really needed to handle large archives. We can run out of memory for
425 * internal tables really fast when we have a whole lot of files...
426 */
427 if (getrlimit(RLIMIT_DATA , &reslimit) == 0){
428 reslimit.rlim_cur = reslimit.rlim_max;
429 (void)setrlimit(RLIMIT_DATA , &reslimit);
430 }
431
432 /*
433 * should file size limits be waived? if the os limits us, this is
434 * needed if we want to write a large archive
435 */
436 if (getrlimit(RLIMIT_FSIZE , &reslimit) == 0){
437 reslimit.rlim_cur = reslimit.rlim_max;
438 (void)setrlimit(RLIMIT_FSIZE , &reslimit);
439 }
440
441 /*
442 * increase the size the stack can grow to
443 */
444 if (getrlimit(RLIMIT_STACK , &reslimit) == 0){
445 reslimit.rlim_cur = reslimit.rlim_max;
446 (void)setrlimit(RLIMIT_STACK , &reslimit);
447 }
448
449 /*
450 * not really needed, but doesn't hurt
451 */
452 #ifdef RLIMIT_RSS
453 if (getrlimit(RLIMIT_RSS , &reslimit) == 0){
454 reslimit.rlim_cur = reslimit.rlim_max;
455 (void)setrlimit(RLIMIT_RSS , &reslimit);
456 }
457 #endif
458
459 /*
460 * signal handling to reset stored directory times and modes. Since
461 * we deal with broken pipes via failed writes we ignore it. We also
462 * deal with any file size limit through failed writes. CPU time
463 * limits are caught and a cleanup is forced.
464 */
465 if ((sigemptyset(&s_mask) < 0) || (sigaddset(&s_mask, SIGTERM) < 0) ||
466 (sigaddset(&s_mask,SIGINT) < 0)||(sigaddset(&s_mask,SIGHUP) < 0) ||
467 (sigaddset(&s_mask,SIGPIPE) < 0)||(sigaddset(&s_mask,SIGQUIT)<0) ||
468 (sigaddset(&s_mask,SIGXCPU) < 0)||(sigaddset(&s_mask,SIGXFSZ)<0)) {
469 paxwarn(1, "Unable to set up signal mask");
470 return(-1);
471 }
472
473 /* snag the fd to be used from the signal handler */
474 listfd = fileno(listf);
475
476 memset(&n_hand, 0, sizeof n_hand);
477 n_hand.sa_mask = s_mask;
478 n_hand.sa_flags = 0;
479 n_hand.sa_handler = sig_cleanup;
480
481 if (setup_sig(SIGHUP, &n_hand) ||
482 setup_sig(SIGTERM, &n_hand) ||
483 setup_sig(SIGINT, &n_hand) ||
484 setup_sig(SIGQUIT, &n_hand) ||
485 setup_sig(SIGXCPU, &n_hand))
486 goto out;
487
488 n_hand.sa_handler = SIG_IGN;
489 if ((sigaction(SIGPIPE, &n_hand, NULL) < 0) ||
490 (sigaction(SIGXFSZ, &n_hand, NULL) < 0))
491 goto out;
492 return (0);
493
494 out:
495 syswarn(1, errno, "Unable to set up signal handler");
496 return (-1);
497 }