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