1 /* util.c - Several utility routines for cpio.
2    Copyright (C) 1990-1992, 2001, 2004, 2006-2007, 2010-2011, 2014-2015,
3    2017 Free Software Foundation, Inc.
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3, or (at your option)
8    any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public
16    License along with this program; if not, write to the Free
17    Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18    Boston, MA 02110-1301 USA.  */
19 
20 #include <system.h>
21 
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include "cpiohdr.h"
26 #include "dstring.h"
27 #include "extern.h"
28 #include <paxlib.h>
29 #include "filetypes.h"
30 #include <safe-read.h>
31 #include <full-write.h>
32 #include <rmt.h>
33 #include <hash.h>
34 #include <utimens.h>
35 
36 #ifdef HAVE_SYS_IOCTL_H
37 # include <sys/ioctl.h>
38 #endif
39 
40 #ifdef HAVE_SYS_MTIO_H
41 # ifdef HAVE_SYS_IO_TRIOCTL_H
42 #  include <sys/io/trioctl.h>
43 # endif
44 # include <sys/mtio.h>
45 #endif
46 
47 #if !HAVE_DECL_ERRNO
48 extern int errno;
49 #endif
50 
51 /* Write `output_size' bytes of `output_buffer' to file
52    descriptor OUT_DES and reset `output_size' and `out_buff'.  */
53 
54 void
tape_empty_output_buffer(int out_des)55 tape_empty_output_buffer (int out_des)
56 {
57   int bytes_written;
58 
59 #ifdef BROKEN_LONG_TAPE_DRIVER
60   static long output_bytes_before_lseek = 0;
61 
62   /* Some tape drivers seem to have a signed internal seek pointer and
63      they lose if it overflows and becomes negative (e.g. when writing
64      tapes > 2Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the
65      seek pointer and prevent it from overflowing.  */
66   if (output_is_special
67      && ( (output_bytes_before_lseek += output_size) >= 1073741824L) )
68     {
69       lseek(out_des, 0L, SEEK_SET);
70       output_bytes_before_lseek = 0;
71     }
72 #endif
73 
74   bytes_written = rmtwrite (out_des, output_buffer, output_size);
75   if (bytes_written != output_size)
76     {
77       int rest_bytes_written;
78       int rest_output_size;
79 
80       if (output_is_special
81 	  && (bytes_written >= 0
82 	      || (bytes_written < 0
83 		  && (errno == ENOSPC || errno == EIO || errno == ENXIO))))
84 	{
85 	  get_next_reel (out_des);
86 	  if (bytes_written > 0)
87 	    rest_output_size = output_size - bytes_written;
88 	  else
89 	    rest_output_size = output_size;
90 	  rest_bytes_written = rmtwrite (out_des, output_buffer,
91 					 rest_output_size);
92 	  if (rest_bytes_written != rest_output_size)
93 	    error (PAXEXIT_FAILURE, errno, _("write error"));
94 	}
95       else
96 	error (PAXEXIT_FAILURE, errno, _("write error"));
97     }
98   output_bytes += output_size;
99   out_buff = output_buffer;
100   output_size = 0;
101 }
102 
103 static ssize_t sparse_write (int fildes, char *buf, size_t nbyte, bool flush);
104 
105 /* Write `output_size' bytes of `output_buffer' to file
106    descriptor OUT_DES and reset `output_size' and `out_buff'.
107    If `swapping_halfwords' or `swapping_bytes' is set,
108    do the appropriate swapping first.  Our callers have
109    to make sure to only set these flags if `output_size'
110    is appropriate (a multiple of 4 for `swapping_halfwords',
111    2 for `swapping_bytes').  The fact that DISK_IO_BLOCK_SIZE
112    must always be a multiple of 4 helps us (and our callers)
113    insure this.  */
114 
115 void
disk_empty_output_buffer(int out_des,bool flush)116 disk_empty_output_buffer (int out_des, bool flush)
117 {
118   ssize_t bytes_written;
119 
120   if (swapping_halfwords || swapping_bytes)
121     {
122       if (swapping_halfwords)
123 	{
124 	  int complete_words;
125 	  complete_words = output_size / 4;
126 	  swahw_array (output_buffer, complete_words);
127 	  if (swapping_bytes)
128 	    swab_array (output_buffer, 2 * complete_words);
129 	}
130       else
131 	{
132 	  int complete_halfwords;
133 	  complete_halfwords = output_size /2;
134 	  swab_array (output_buffer, complete_halfwords);
135 	}
136     }
137 
138   if (sparse_flag)
139     bytes_written = sparse_write (out_des, output_buffer, output_size, flush);
140   else
141     bytes_written = write (out_des, output_buffer, output_size);
142 
143   if (bytes_written != output_size)
144     {
145       if (bytes_written == -1)
146 	error (PAXEXIT_FAILURE, errno, _("write error"));
147       else
148 	error (PAXEXIT_FAILURE, 0, _("write error: partial write"));
149     }
150   output_bytes += output_size;
151   out_buff = output_buffer;
152   output_size = 0;
153 }
154 
155 /* Exchange the halfwords of each element of the array of COUNT longs
156    starting at PTR.  PTR does not have to be aligned at a word
157    boundary.  */
158 
159 void
swahw_array(char * ptr,int count)160 swahw_array (char *ptr, int count)
161 {
162   char tmp;
163 
164   for (; count > 0; --count)
165     {
166       tmp = *ptr;
167       *ptr = *(ptr + 2);
168       *(ptr + 2) = tmp;
169       ++ptr;
170       tmp = *ptr;
171       *ptr = *(ptr + 2);
172       *(ptr + 2) = tmp;
173       ptr += 3;
174     }
175 }
176 
177 /* Read at most NUM_BYTES or `io_block_size' bytes, whichever is smaller,
178    into the start of `input_buffer' from file descriptor IN_DES.
179    Set `input_size' to the number of bytes read and reset `in_buff'.
180    Exit with an error if end of file is reached.  */
181 
182 #ifdef BROKEN_LONG_TAPE_DRIVER
183 static long input_bytes_before_lseek = 0;
184 #endif
185 
186 static void
tape_fill_input_buffer(int in_des,int num_bytes)187 tape_fill_input_buffer (int in_des, int num_bytes)
188 {
189 #ifdef BROKEN_LONG_TAPE_DRIVER
190   /* Some tape drivers seem to have a signed internal seek pointer and
191      they lose if it overflows and becomes negative (e.g. when writing
192      tapes > 4Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the
193      seek pointer and prevent it from overflowing.  */
194   if (input_is_special
195       && ( (input_bytes_before_lseek += num_bytes) >= 1073741824L) )
196     {
197       lseek(in_des, 0L, SEEK_SET);
198       input_bytes_before_lseek = 0;
199     }
200 #endif
201   in_buff = input_buffer;
202   num_bytes = (num_bytes < io_block_size) ? num_bytes : io_block_size;
203   input_size = rmtread (in_des, input_buffer, num_bytes);
204   if (input_size == 0 && input_is_special)
205     {
206       get_next_reel (in_des);
207       input_size = rmtread (in_des, input_buffer, num_bytes);
208     }
209   if (input_size == SAFE_READ_ERROR)
210     error (PAXEXIT_FAILURE, errno, _("read error"));
211   if (input_size == 0)
212     error (PAXEXIT_FAILURE, 0, _("premature end of file"));
213   input_bytes += input_size;
214 }
215 
216 /* Read at most NUM_BYTES or `DISK_IO_BLOCK_SIZE' bytes, whichever is smaller,
217    into the start of `input_buffer' from file descriptor IN_DES.
218    Set `input_size' to the number of bytes read and reset `in_buff'.
219    Exit with an error if end of file is reached.  */
220 
221 static int
disk_fill_input_buffer(int in_des,off_t num_bytes)222 disk_fill_input_buffer (int in_des, off_t num_bytes)
223 {
224   in_buff = input_buffer;
225   num_bytes = (num_bytes < DISK_IO_BLOCK_SIZE) ? num_bytes : DISK_IO_BLOCK_SIZE;
226   input_size = read (in_des, input_buffer, num_bytes);
227   if (input_size == SAFE_READ_ERROR)
228     {
229       input_size = 0;
230       return (-1);
231     }
232   else if (input_size == 0)
233     return (1);
234   input_bytes += input_size;
235   return (0);
236 }
237 
238 /* Copy NUM_BYTES of buffer IN_BUF to `out_buff', which may be partly full.
239    When `out_buff' fills up, flush it to file descriptor OUT_DES.  */
240 
241 void
tape_buffered_write(char * in_buf,int out_des,off_t num_bytes)242 tape_buffered_write (char *in_buf, int out_des, off_t num_bytes)
243 {
244   off_t bytes_left = num_bytes;	/* Bytes needing to be copied.  */
245   off_t space_left;	/* Room left in output buffer.  */
246 
247   while (bytes_left > 0)
248     {
249       space_left = io_block_size - output_size;
250       if (space_left == 0)
251 	tape_empty_output_buffer (out_des);
252       else
253 	{
254 	  if (bytes_left < space_left)
255 	    space_left = bytes_left;
256 	  memcpy (out_buff, in_buf, (unsigned) space_left);
257 	  out_buff += space_left;
258 	  output_size += space_left;
259 	  in_buf += space_left;
260 	  bytes_left -= space_left;
261 	}
262     }
263 }
264 
265 /* Copy NUM_BYTES of buffer IN_BUF to `out_buff', which may be partly full.
266    When `out_buff' fills up, flush it to file descriptor OUT_DES.  */
267 
268 void
disk_buffered_write(char * in_buf,int out_des,off_t num_bytes)269 disk_buffered_write (char *in_buf, int out_des, off_t num_bytes)
270 {
271   off_t bytes_left = num_bytes;	/* Bytes needing to be copied.  */
272   off_t space_left;	/* Room left in output buffer.  */
273 
274   while (bytes_left > 0)
275     {
276       space_left = DISK_IO_BLOCK_SIZE - output_size;
277       if (space_left == 0)
278 	disk_empty_output_buffer (out_des, false);
279       else
280 	{
281 	  if (bytes_left < space_left)
282 	    space_left = bytes_left;
283 	  memcpy (out_buff, in_buf, (unsigned) space_left);
284 	  out_buff += space_left;
285 	  output_size += space_left;
286 	  in_buf += space_left;
287 	  bytes_left -= space_left;
288 	}
289     }
290 }
291 
292 /* Copy NUM_BYTES of buffer `in_buff' into IN_BUF.
293    `in_buff' may be partly full.
294    When `in_buff' is exhausted, refill it from file descriptor IN_DES.  */
295 
296 void
tape_buffered_read(char * in_buf,int in_des,off_t num_bytes)297 tape_buffered_read (char *in_buf, int in_des, off_t num_bytes)
298 {
299   off_t bytes_left = num_bytes;	/* Bytes needing to be copied.  */
300   off_t space_left;	/* Bytes to copy from input buffer.  */
301 
302   while (bytes_left > 0)
303     {
304       if (input_size == 0)
305 	tape_fill_input_buffer (in_des, io_block_size);
306       if (bytes_left < input_size)
307 	space_left = bytes_left;
308       else
309 	space_left = input_size;
310       memcpy (in_buf, in_buff, (unsigned) space_left);
311       in_buff += space_left;
312       in_buf += space_left;
313       input_size -= space_left;
314       bytes_left -= space_left;
315     }
316 }
317 
318 /* Copy the the next NUM_BYTES bytes of `input_buffer' into PEEK_BUF.
319    If NUM_BYTES bytes are not available, read the next `io_block_size' bytes
320    into the end of `input_buffer' and update `input_size'.
321 
322    Return the number of bytes copied into PEEK_BUF.
323    If the number of bytes returned is less than NUM_BYTES,
324    then EOF has been reached.  */
325 
326 int
tape_buffered_peek(char * peek_buf,int in_des,int num_bytes)327 tape_buffered_peek (char *peek_buf, int in_des, int num_bytes)
328 {
329   long tmp_input_size;
330   long got_bytes;
331   char *append_buf;
332 
333 #ifdef BROKEN_LONG_TAPE_DRIVER
334   /* Some tape drivers seem to have a signed internal seek pointer and
335      they lose if it overflows and becomes negative (e.g. when writing
336      tapes > 4Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the
337      seek pointer and prevent it from overflowing.  */
338   if (input_is_special
339       && ( (input_bytes_before_lseek += num_bytes) >= 1073741824L) )
340     {
341       lseek(in_des, 0L, SEEK_SET);
342       input_bytes_before_lseek = 0;
343     }
344 #endif
345 
346   while (input_size < num_bytes)
347     {
348       append_buf = in_buff + input_size;
349       if ( (append_buf - input_buffer) >= input_buffer_size)
350 	{
351 	  /* We can keep up to 2 "blocks" (either the physical block size
352 	     or 512 bytes(the size of a tar record), which ever is
353 	     larger) in the input buffer when we are peeking.  We
354 	     assume that our caller will never be interested in peeking
355 	     ahead at more than 512 bytes, so we know that by the time
356 	     we need a 3rd "block" in the buffer we can throw away the
357 	     first block to make room.  */
358 	  int half;
359 	  half = input_buffer_size / 2;
360 	  memmove (input_buffer, input_buffer + half, half);
361 	  in_buff = in_buff - half;
362 	  append_buf = append_buf - half;
363 	}
364       tmp_input_size = rmtread (in_des, append_buf, io_block_size);
365       if (tmp_input_size == 0)
366 	{
367 	  if (input_is_special)
368 	    {
369 	      get_next_reel (in_des);
370 	      tmp_input_size = rmtread (in_des, append_buf, io_block_size);
371 	    }
372 	  else
373 	    break;
374 	}
375       if (tmp_input_size < 0)
376 	error (PAXEXIT_FAILURE, errno, _("read error"));
377       input_bytes += tmp_input_size;
378       input_size += tmp_input_size;
379     }
380   if (num_bytes <= input_size)
381     got_bytes = num_bytes;
382   else
383     got_bytes = input_size;
384   memcpy (peek_buf, in_buff, (unsigned) got_bytes);
385   return got_bytes;
386 }
387 
388 /* Skip the next NUM_BYTES bytes of file descriptor IN_DES.  */
389 
390 void
tape_toss_input(int in_des,off_t num_bytes)391 tape_toss_input (int in_des, off_t num_bytes)
392 {
393   off_t bytes_left = num_bytes;	/* Bytes needing to be copied.  */
394   off_t space_left;	/* Bytes to copy from input buffer.  */
395 
396   while (bytes_left > 0)
397     {
398       if (input_size == 0)
399 	tape_fill_input_buffer (in_des, io_block_size);
400       if (bytes_left < input_size)
401 	space_left = bytes_left;
402       else
403 	space_left = input_size;
404 
405       if (crc_i_flag && only_verify_crc_flag)
406 	{
407  	  int k;
408 	  for (k = 0; k < space_left; ++k)
409 	    crc += in_buff[k] & 0xff;
410 	}
411 
412       in_buff += space_left;
413       input_size -= space_left;
414       bytes_left -= space_left;
415     }
416 }
417 
418 void
write_nuls_to_file(off_t num_bytes,int out_des,void (* writer)(char * in_buf,int out_des,off_t num_bytes))419 write_nuls_to_file (off_t num_bytes, int out_des,
420                     void (*writer) (char *in_buf, int out_des, off_t num_bytes))
421 {
422   off_t	blocks;
423   off_t	extra_bytes;
424   off_t	i;
425   static char zeros_512[512];
426 
427   blocks = num_bytes / sizeof zeros_512;
428   extra_bytes = num_bytes % sizeof zeros_512;
429   for (i = 0; i < blocks; ++i)
430     writer (zeros_512, out_des, sizeof zeros_512);
431   if (extra_bytes)
432     writer (zeros_512, out_des, extra_bytes);
433 }
434 
435 /* Copy a file using the input and output buffers, which may start out
436    partly full.  After the copy, the files are not closed nor the last
437    block flushed to output, and the input buffer may still be partly
438    full.  If `crc_i_flag' is set, add each byte to `crc'.
439    IN_DES is the file descriptor for input;
440    OUT_DES is the file descriptor for output;
441    NUM_BYTES is the number of bytes to copy.  */
442 
443 void
copy_files_tape_to_disk(int in_des,int out_des,off_t num_bytes)444 copy_files_tape_to_disk (int in_des, int out_des, off_t num_bytes)
445 {
446   off_t size;
447   off_t k;
448 
449   while (num_bytes > 0)
450     {
451       if (input_size == 0)
452 	tape_fill_input_buffer (in_des, io_block_size);
453       size = (input_size < num_bytes) ? input_size : num_bytes;
454       if (crc_i_flag)
455 	{
456 	  for (k = 0; k < size; ++k)
457 	    crc += in_buff[k] & 0xff;
458 	}
459       disk_buffered_write (in_buff, out_des, size);
460       num_bytes -= size;
461       input_size -= size;
462       in_buff += size;
463     }
464 }
465 /* Copy a file using the input and output buffers, which may start out
466    partly full.  After the copy, the files are not closed nor the last
467    block flushed to output, and the input buffer may still be partly
468    full.  If `crc_i_flag' is set, add each byte to `crc'.
469    IN_DES is the file descriptor for input;
470    OUT_DES is the file descriptor for output;
471    NUM_BYTES is the number of bytes to copy.  */
472 
473 void
copy_files_disk_to_tape(int in_des,int out_des,off_t num_bytes,char * filename)474 copy_files_disk_to_tape (int in_des, int out_des, off_t num_bytes,
475 			 char *filename)
476 {
477   off_t size;
478   off_t k;
479   int rc;
480   off_t original_num_bytes;
481 
482   original_num_bytes = num_bytes;
483 
484   while (num_bytes > 0)
485     {
486       if (input_size == 0)
487 	if ((rc = disk_fill_input_buffer (in_des,
488 					  num_bytes < DISK_IO_BLOCK_SIZE ?
489 					  num_bytes : DISK_IO_BLOCK_SIZE)))
490 	  {
491 	    if (rc > 0)
492 	      {
493 		  char buf[UINTMAX_STRSIZE_BOUND];
494 		  error (0, 0,
495 			 ngettext ("File %s shrunk by %s byte, padding with zeros",
496 				   "File %s shrunk by %s bytes, padding with zeros",
497 				   num_bytes),
498 			 filename,  STRINGIFY_BIGINT (num_bytes, buf));
499 	      }
500 	    else
501 	      error (0, 0,
502 		     _("Read error at byte %lld in file %s, padding with zeros"),
503 		     (long long) (original_num_bytes - num_bytes), filename);
504 	    write_nuls_to_file (num_bytes, out_des, tape_buffered_write);
505 	    break;
506 	  }
507       size = (input_size < num_bytes) ? input_size : num_bytes;
508       if (crc_i_flag)
509 	{
510 	  for (k = 0; k < size; ++k)
511 	    crc += in_buff[k] & 0xff;
512 	}
513       tape_buffered_write (in_buff, out_des, size);
514       num_bytes -= size;
515       input_size -= size;
516       in_buff += size;
517     }
518 }
519 /* Copy a file using the input and output buffers, which may start out
520    partly full.  After the copy, the files are not closed nor the last
521    block flushed to output, and the input buffer may still be partly
522    full.  If `crc_i_flag' is set, add each byte to `crc'.
523    IN_DES is the file descriptor for input;
524    OUT_DES is the file descriptor for output;
525    NUM_BYTES is the number of bytes to copy.  */
526 
527 void
copy_files_disk_to_disk(int in_des,int out_des,off_t num_bytes,char * filename)528 copy_files_disk_to_disk (int in_des, int out_des, off_t num_bytes,
529 			 char *filename)
530 {
531   off_t size;
532   off_t k;
533   off_t original_num_bytes;
534   int rc;
535 
536   original_num_bytes = num_bytes;
537   while (num_bytes > 0)
538     {
539       if (input_size == 0)
540 	if ((rc = disk_fill_input_buffer (in_des, num_bytes)))
541 	  {
542 	    if (rc > 0)
543 	      {
544 		char buf[UINTMAX_STRSIZE_BOUND];
545 		error (0, 0,
546 		       ngettext ("File %s shrunk by %s byte, padding with zeros",
547 				 "File %s shrunk by %s bytes, padding with zeros",
548 				 num_bytes),
549 		       filename,  STRINGIFY_BIGINT (num_bytes, buf));
550 	      }
551 	    else
552 	      error (0, 0,
553 		     _("Read error at byte %lld in file %s, padding with zeros"),
554 		     (long long) (original_num_bytes - num_bytes), filename);
555 	    write_nuls_to_file (num_bytes, out_des, disk_buffered_write);
556 	    break;
557 	  }
558       size = (input_size < num_bytes) ? input_size : num_bytes;
559       if (crc_i_flag)
560 	{
561 	  for (k = 0; k < size; ++k)
562 	    crc += in_buff[k] & 0xff;
563 	}
564       disk_buffered_write (in_buff, out_des, size);
565       num_bytes -= size;
566       input_size -= size;
567       in_buff += size;
568     }
569 }
570 
571 /* Warn if file changed while it was being copied.  */
572 
573 void
warn_if_file_changed(char * file_name,off_t old_file_size,time_t old_file_mtime)574 warn_if_file_changed (char *file_name, off_t old_file_size,
575 		      time_t old_file_mtime)
576 {
577   struct stat new_file_stat;
578   if ((*xstat) (file_name, &new_file_stat) < 0)
579     {
580       stat_error (file_name);
581       return;
582     }
583 
584   /* Only check growth, shrinkage detected in copy_files_disk_to_{disk,tape}()
585    */
586   if (new_file_stat.st_size > old_file_size)
587     error (0, 0,
588 	   ngettext ("File %s grew, %"PRIuMAX" new byte not copied",
589 		     "File %s grew, %"PRIuMAX" new bytes not copied",
590 		     (long)(new_file_stat.st_size - old_file_size)),
591 	   file_name, (uintmax_t) (new_file_stat.st_size - old_file_size));
592 
593   else if (new_file_stat.st_mtime != old_file_mtime)
594     error (0, 0, _("File %s was modified while being copied"), file_name);
595 }
596 
597 /* Create all directories up to but not including the last part of NAME.
598    Do not destroy any nondirectories while creating directories.  */
599 
600 void
create_all_directories(char const * name)601 create_all_directories (char const *name)
602 {
603   char *dir;
604 
605   dir = dir_name (name);
606 
607   if (dir == NULL)
608     error (PAXEXIT_FAILURE, 0, _("virtual memory exhausted"));
609 
610   if (dir[0] != '.' || dir[1] != '\0')
611     {
612       const char *fmt;
613       if (warn_option & CPIO_WARN_INTERDIR)
614 	fmt = _("Creating intermediate directory `%s'");
615       else
616 	fmt = NULL;
617       make_path (dir, -1, -1, fmt);
618     }
619 
620   free (dir);
621 }
622 
623 /* Prepare to append to an archive.  We have been in
624    process_copy_in, keeping track of the position where
625    the last header started in `last_header_start'.  Now we
626    have the starting position of the last header (the TRAILER!!!
627    header, or blank record for tar archives) and we want to start
628    writing (appending) over the last header.  The last header may
629    be in the middle of a block, so to keep the buffering in sync
630    we lseek back to the start of the block, read everything up
631    to but not including the last header, lseek back to the start
632    of the block, and then do a copy_buf_out of what we read.
633    Actually, we probably don't have to worry so much about keeping the
634    buffering perfect since you can only append to archives that
635    are disk files.  */
636 
637 void
prepare_append(int out_file_des)638 prepare_append (int out_file_des)
639 {
640   int start_of_header;
641   int start_of_block;
642   int useful_bytes_in_block;
643   char *tmp_buf;
644 
645   start_of_header = last_header_start;
646   /* Figure out how many bytes we will rewrite, and where they start.  */
647   useful_bytes_in_block = start_of_header % io_block_size;
648   start_of_block = start_of_header - useful_bytes_in_block;
649 
650   if (lseek (out_file_des, start_of_block, SEEK_SET) < 0)
651     error (PAXEXIT_FAILURE, errno, _("cannot seek on output"));
652   if (useful_bytes_in_block > 0)
653     {
654       tmp_buf = (char *) xmalloc (useful_bytes_in_block);
655       read (out_file_des, tmp_buf, useful_bytes_in_block);
656       if (lseek (out_file_des, start_of_block, SEEK_SET) < 0)
657 	error (PAXEXIT_FAILURE, errno, _("cannot seek on output"));
658       /* fix juo -- is this copy_tape_buf_out?  or copy_disk? */
659       tape_buffered_write (tmp_buf, out_file_des, useful_bytes_in_block);
660       free (tmp_buf);
661     }
662 
663   /* We are done reading the archive, so clear these since they
664      will now be used for reading in files that we are appending
665      to the archive.  */
666   input_size = 0;
667   input_bytes = 0;
668   in_buff = input_buffer;
669 }
670 
671 /* Support for remembering inodes with multiple links.  Used in the
672    "copy in" and "copy pass" modes for making links instead of copying
673    the file.  */
674 
675 struct inode_val
676 {
677   ino_t inode;
678   unsigned long major_num;
679   unsigned long minor_num;
680   ino_t trans_inode;
681   char *file_name;
682 };
683 
684 /* Inode hash table.  Allocated by first call to add_inode.  */
685 static Hash_table *hash_table = NULL;
686 
687 static size_t
inode_val_hasher(const void * val,size_t n_buckets)688 inode_val_hasher (const void *val, size_t n_buckets)
689 {
690   const struct inode_val *ival = val;
691   return ival->inode % n_buckets;
692 }
693 
694 static bool
inode_val_compare(const void * val1,const void * val2)695 inode_val_compare (const void *val1, const void *val2)
696 {
697   const struct inode_val *ival1 = val1;
698   const struct inode_val *ival2 = val2;
699   return ival1->inode == ival2->inode
700          && ival1->major_num == ival2->major_num
701          && ival1->minor_num == ival2->minor_num;
702 }
703 
704 static struct inode_val *
find_inode_val(ino_t node_num,unsigned long major_num,unsigned long minor_num)705 find_inode_val (ino_t node_num, unsigned long major_num,
706 		 unsigned long minor_num)
707 {
708   struct inode_val sample;
709 
710   if (!hash_table)
711     return NULL;
712 
713   sample.inode = node_num;
714   sample.major_num = major_num;
715   sample.minor_num = minor_num;
716   return hash_lookup (hash_table, &sample);
717 }
718 
719 char *
find_inode_file(ino_t node_num,unsigned long major_num,unsigned long minor_num)720 find_inode_file (ino_t node_num, unsigned long major_num,
721 		 unsigned long minor_num)
722 {
723   struct inode_val *ival = find_inode_val (node_num, major_num, minor_num);
724   return ival ? ival->file_name : NULL;
725 }
726 
727 /* Associate FILE_NAME with the inode NODE_NUM.  (Insert into hash table.)  */
728 
729 static ino_t next_inode;
730 
731 struct inode_val *
add_inode(ino_t node_num,char * file_name,unsigned long major_num,unsigned long minor_num)732 add_inode (ino_t node_num, char *file_name, unsigned long major_num,
733 	   unsigned long minor_num)
734 {
735   struct inode_val *temp;
736   struct inode_val *e = NULL;
737 
738   /* Create new inode record.  */
739   temp = (struct inode_val *) xmalloc (sizeof (struct inode_val));
740   temp->inode = node_num;
741   temp->major_num = major_num;
742   temp->minor_num = minor_num;
743   temp->file_name = file_name ? xstrdup (file_name) : NULL;
744 
745   if (renumber_inodes_option)
746     temp->trans_inode = next_inode++;
747   else
748     temp->trans_inode = temp->inode;
749 
750   if (!((hash_table
751 	 || (hash_table = hash_initialize (0, 0, inode_val_hasher,
752 					   inode_val_compare, 0)))
753 	&& (e = hash_insert (hash_table, temp))))
754     xalloc_die ();
755   return e;
756 }
757 
758 static void
get_inode_and_dev(struct cpio_file_stat * hdr,struct stat * st)759 get_inode_and_dev (struct cpio_file_stat *hdr, struct stat *st)
760 {
761   if (renumber_inodes_option)
762     {
763       if (st->st_nlink > 1)
764 	{
765 	  struct inode_val *ival = find_inode_val (st->st_ino,
766 						   major (st->st_dev),
767 						   minor (st->st_dev));
768 	  if (!ival)
769 	    ival = add_inode (st->st_ino, NULL,
770 			      major (st->st_dev), minor (st->st_dev));
771 	  hdr->c_ino = ival->trans_inode;
772 	}
773       else
774 	hdr->c_ino = next_inode++;
775     }
776   else
777     hdr->c_ino = st->st_ino;
778   if (ignore_devno_option)
779     {
780       hdr->c_dev_maj = 0;
781       hdr->c_dev_min = 0;
782     }
783   else
784     {
785       hdr->c_dev_maj = major (st->st_dev);
786       hdr->c_dev_min = minor (st->st_dev);
787     }
788 }
789 
790 
791 /* Open FILE in the mode specified by the command line options
792    and return an open file descriptor for it,
793    or -1 if it can't be opened.  */
794 
795 int
open_archive(char * file)796 open_archive (char *file)
797 {
798   int fd;
799   void (*copy_in) ();		/* Workaround for pcc bug.  */
800 
801   copy_in = process_copy_in;
802 
803   if (copy_function == copy_in)
804     fd = rmtopen (file, O_RDONLY | O_BINARY, MODE_RW, rsh_command_option);
805   else
806     {
807       if (!append_flag)
808 	fd = rmtopen (file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, MODE_RW,
809 			rsh_command_option);
810       else
811 	fd = rmtopen (file, O_RDWR | O_BINARY, MODE_RW, rsh_command_option);
812     }
813 
814   return fd;
815 }
816 
817 /* Attempt to rewind the tape drive on file descriptor TAPE_DES
818    and take it offline.  */
819 
820 void
tape_offline(int tape_des)821 tape_offline (int tape_des)
822 {
823 #if defined(MTIOCTOP) && defined(MTOFFL)
824   struct mtop control;
825 
826   control.mt_op = MTOFFL;
827   control.mt_count = 1;
828   rmtioctl (tape_des, MTIOCTOP, (char*) &control);	/* Don't care if it fails.  */
829 #endif
830 }
831 
832 /* The file on file descriptor TAPE_DES is assumed to be magnetic tape
833    (or floppy disk or other device) and the end of the medium
834    has been reached.  Ask the user for to mount a new "tape" to continue
835    the processing.  If the user specified the device name on the
836    command line (with the -I, -O, -F or --file options), then we can
837    automatically re-open the same device to use the next medium.  If the
838    user did not specify the device name, then we have to ask them which
839    device to use.  */
840 
841 void
get_next_reel(int tape_des)842 get_next_reel (int tape_des)
843 {
844   static int reel_number = 1;
845   FILE *tty_in;			/* File for interacting with user.  */
846   FILE *tty_out;		/* File for interacting with user.  */
847   int old_tape_des;
848   char *next_archive_name;
849   dynamic_string new_name;
850   char *str_res;
851 
852   ds_init (&new_name, 128);
853 
854   /* Open files for interactive communication.  */
855   tty_in = fopen (TTY_NAME, "r");
856   if (tty_in == NULL)
857     error (PAXEXIT_FAILURE, errno, TTY_NAME);
858   tty_out = fopen (TTY_NAME, "w");
859   if (tty_out == NULL)
860     error (PAXEXIT_FAILURE, errno, TTY_NAME);
861 
862   old_tape_des = tape_des;
863   tape_offline (tape_des);
864   rmtclose (tape_des);
865 
866   /* Give message and wait for carrage return.  User should hit carrage return
867      only after loading the next tape.  */
868   ++reel_number;
869   if (new_media_message)
870     fprintf (tty_out, "%s", new_media_message);
871   else if (new_media_message_with_number)
872     fprintf (tty_out, "%s%d%s", new_media_message_with_number, reel_number,
873 	     new_media_message_after_number);
874   else if (archive_name)
875     fprintf (tty_out, _("Found end of tape.  Load next tape and press RETURN. "));
876   else
877     fprintf (tty_out, _("Found end of tape.  To continue, type device/file name when ready.\n"));
878 
879   fflush (tty_out);
880 
881   if (archive_name)
882     {
883       int c;
884 
885       do
886 	c = getc (tty_in);
887       while (c != EOF && c != '\n');
888 
889       tape_des = open_archive (archive_name);
890       if (tape_des == -1)
891 	open_error (archive_name);
892     }
893   else
894     {
895       do
896 	{
897 	  if (tape_des < 0)
898 	    {
899 	      fprintf (tty_out,
900 		       _("To continue, type device/file name when ready.\n"));
901 	      fflush (tty_out);
902 	    }
903 
904 	  str_res = ds_fgets (tty_in, &new_name);
905 	  if (str_res == NULL || str_res[0] == '\0')
906 	    exit (PAXEXIT_FAILURE);
907 	  next_archive_name = str_res;
908 
909 	  tape_des = open_archive (next_archive_name);
910 	  if (tape_des == -1)
911 	    open_error (next_archive_name);
912 	}
913       while (tape_des < 0);
914     }
915 
916   /* We have to make sure that `tape_des' has not changed its value even
917      though we closed it and reopened it, since there are local
918      copies of it in other routines.  This works fine on Unix (even with
919      rmtread and rmtwrite) since open will always return the lowest
920      available file descriptor and we haven't closed any files (e.g.,
921      stdin, stdout or stderr) that were opened before we originally opened
922      the archive.  */
923 
924   if (tape_des != old_tape_des)
925     error (PAXEXIT_FAILURE, 0, _("internal error: tape descriptor changed from %d to %d"),
926 	   old_tape_des, tape_des);
927 
928   free (new_name.ds_string);
929   fclose (tty_in);
930   fclose (tty_out);
931 }
932 
933 /* If MESSAGE does not contain the string "%d", make `new_media_message'
934    a copy of MESSAGE.  If MESSAGES does contain the string "%d", make
935    `new_media_message_with_number' a copy of MESSAGE up to, but
936    not including, the string "%d", and make `new_media_message_after_number'
937    a copy of MESSAGE after the string "%d".  */
938 
939 void
set_new_media_message(char * message)940 set_new_media_message (char *message)
941 {
942   char *p;
943   int prev_was_percent;
944 
945   p = message;
946   prev_was_percent = 0;
947   while (*p != '\0')
948     {
949       if (*p == 'd' && prev_was_percent)
950 	break;
951       prev_was_percent = (*p == '%');
952       ++p;
953     }
954   if (*p == '\0')
955     {
956       new_media_message = xstrdup (message);
957     }
958   else
959     {
960       int length = p - message - 1;
961 
962       new_media_message_with_number = xmalloc (length + 1);
963       strncpy (new_media_message_with_number, message, length);
964       new_media_message_with_number[length] = '\0';
965       length = strlen (p + 1);
966       new_media_message_after_number = xmalloc (length + 1);
967       strcpy (new_media_message_after_number, p + 1);
968     }
969 }
970 
971 #ifdef SYMLINK_USES_UMASK
972 /* Most machines always create symlinks with rwxrwxrwx protection,
973    but some (HP/UX 8.07; maybe DEC's OSF on MIPS, too?) use the
974    umask when creating symlinks, so if your umask is 022 you end
975    up with rwxr-xr-x symlinks (although HP/UX seems to completely
976    ignore the protection).  There doesn't seem to be any way to
977    manipulate the modes once the symlinks are created (e.g.
978    a hypothetical "lchmod"), so to create them with the right
979    modes we have to set the umask first.  */
980 
981 int
umasked_symlink(char * name1,char * name2,int mode)982 umasked_symlink (char *name1, char *name2, int mode)
983 {
984   int	old_umask;
985   int	rc;
986   mode = ~(mode & 0777) & 0777;
987   old_umask = umask (mode);
988   rc = symlink (name1, name2);
989   umask (old_umask);
990   return rc;
991 }
992 #endif /* SYMLINK_USES_UMASK */
993 
994 #define DISKBLOCKSIZE	(512)
995 
996 static int
buf_all_zeros(char * buf,int bufsize)997 buf_all_zeros (char *buf, int bufsize)
998 {
999   int	i;
1000   for (i = 0; i < bufsize; ++i)
1001     {
1002       if (*buf++ != '\0')
1003 	return 0;
1004     }
1005   return 1;
1006 }
1007 
1008 /* Write NBYTE bytes from BUF to file descriptor FILDES, trying to
1009    create holes instead of writing blockfuls of zeros.
1010 
1011    Return the number of bytes written (including bytes in zero
1012    regions) on success, -1 on error.
1013 
1014    If FLUSH is set, make sure the trailing zero region is flushed
1015    on disk.
1016 */
1017 
1018 static ssize_t
sparse_write(int fildes,char * buf,size_t nbytes,bool flush)1019 sparse_write (int fildes, char *buf, size_t nbytes, bool flush)
1020 {
1021   size_t nwritten = 0;
1022   ssize_t n;
1023   char *start_ptr = buf;
1024 
1025   static off_t delayed_seek_count = 0;
1026   off_t seek_count = 0;
1027 
1028   enum { begin, in_zeros, not_in_zeros } state =
1029 			   delayed_seek_count ? in_zeros : begin;
1030 
1031   while (nbytes)
1032     {
1033       size_t rest = nbytes;
1034 
1035       if (rest < DISKBLOCKSIZE)
1036 	/* Force write */
1037 	state = not_in_zeros;
1038       else
1039 	{
1040 	  if (buf_all_zeros (buf, rest))
1041 	    {
1042 	      if (state == not_in_zeros)
1043 		{
1044 		  ssize_t bytes = buf - start_ptr + rest;
1045 
1046 		  n = write (fildes, start_ptr, bytes);
1047 		  if (n == -1)
1048 		    return -1;
1049 		  nwritten += n;
1050 		  if (n < bytes)
1051 		    return nwritten + seek_count;
1052 		  start_ptr = NULL;
1053 		}
1054 	      else
1055 		seek_count += rest;
1056 	      state = in_zeros;
1057 	    }
1058 	  else
1059 	    {
1060 	      seek_count += delayed_seek_count;
1061 	      if (lseek (fildes, seek_count, SEEK_CUR) == -1)
1062 		return -1;
1063 	      delayed_seek_count = seek_count = 0;
1064 	      state = not_in_zeros;
1065 	      start_ptr = buf;
1066 	    }
1067 	}
1068       buf += rest;
1069       nbytes -= rest;
1070     }
1071 
1072   if (state != in_zeros)
1073     {
1074       seek_count += delayed_seek_count;
1075       if (seek_count && lseek (fildes, seek_count, SEEK_CUR) == -1)
1076 	return -1;
1077       delayed_seek_count = seek_count = 0;
1078 
1079       n = write (fildes, start_ptr, buf - start_ptr);
1080       if (n == -1)
1081 	return n;
1082       nwritten += n;
1083     }
1084   delayed_seek_count += seek_count;
1085 
1086   if (flush && delayed_seek_count)
1087     {
1088       if (lseek (fildes, delayed_seek_count - 1, SEEK_CUR) == -1)
1089 	return -1;
1090       n = write (fildes, "", 1);
1091       if (n != 1)
1092 	return n;
1093       delayed_seek_count = 0;
1094     }
1095 
1096   return nwritten + seek_count;
1097 }
1098 
1099 #define CPIO_UID(uid) (set_owner_flag ? set_owner : (uid))
1100 #define CPIO_GID(gid) (set_group_flag ? set_group : (gid))
1101 
1102 void
stat_to_cpio(struct cpio_file_stat * hdr,struct stat * st)1103 stat_to_cpio (struct cpio_file_stat *hdr, struct stat *st)
1104 {
1105   get_inode_and_dev (hdr, st);
1106 
1107   /* For POSIX systems that don't define the S_IF macros,
1108      we can't assume that S_ISfoo means the standard Unix
1109      S_IFfoo bit(s) are set.  So do it manually, with a
1110      different name.  Bleah.  */
1111   hdr->c_mode = (st->st_mode & 07777);
1112   if (S_ISREG (st->st_mode))
1113     hdr->c_mode |= CP_IFREG;
1114   else if (S_ISDIR (st->st_mode))
1115     hdr->c_mode |= CP_IFDIR;
1116 #ifdef S_ISBLK
1117   else if (S_ISBLK (st->st_mode))
1118     hdr->c_mode |= CP_IFBLK;
1119 #endif
1120 #ifdef S_ISCHR
1121   else if (S_ISCHR (st->st_mode))
1122     hdr->c_mode |= CP_IFCHR;
1123 #endif
1124 #ifdef S_ISFIFO
1125   else if (S_ISFIFO (st->st_mode))
1126     hdr->c_mode |= CP_IFIFO;
1127 #endif
1128 #ifdef S_ISLNK
1129   else if (S_ISLNK (st->st_mode))
1130     hdr->c_mode |= CP_IFLNK;
1131 #endif
1132 #ifdef S_ISSOCK
1133   else if (S_ISSOCK (st->st_mode))
1134     hdr->c_mode |= CP_IFSOCK;
1135 #endif
1136 #ifdef S_ISNWK
1137   else if (S_ISNWK (st->st_mode))
1138     hdr->c_mode |= CP_IFNWK;
1139 #endif
1140   hdr->c_nlink = st->st_nlink;
1141   hdr->c_uid = CPIO_UID (st->st_uid);
1142   hdr->c_gid = CPIO_GID (st->st_gid);
1143   if (S_ISBLK (st->st_mode) || S_ISCHR (st->st_mode))
1144     {
1145       hdr->c_rdev_maj = major (st->st_rdev);
1146       hdr->c_rdev_min = minor (st->st_rdev);
1147     }
1148   else
1149     {
1150       hdr->c_rdev_maj = 0;
1151       hdr->c_rdev_min = 0;
1152     }
1153   hdr->c_mtime = st->st_mtime;
1154   hdr->c_filesize = st->st_size;
1155   hdr->c_chksum = 0;
1156   hdr->c_tar_linkname = NULL;
1157 }
1158 
1159 void
cpio_to_stat(struct stat * st,struct cpio_file_stat * hdr)1160 cpio_to_stat (struct stat *st, struct cpio_file_stat *hdr)
1161 {
1162   memset (st, 0, sizeof (*st));
1163   st->st_dev = makedev (hdr->c_dev_maj, hdr->c_dev_min);
1164   st->st_ino = hdr->c_ino;
1165   st->st_mode = hdr->c_mode & 0777;
1166   if (hdr->c_mode & CP_IFREG)
1167     st->st_mode |= S_IFREG;
1168   else if (hdr->c_mode & CP_IFDIR)
1169     st->st_mode |= S_IFDIR;
1170 #ifdef S_IFBLK
1171   else if (hdr->c_mode & CP_IFBLK)
1172     st->st_mode |= S_IFBLK;
1173 #endif
1174 #ifdef S_IFCHR
1175   else if (hdr->c_mode & CP_IFCHR)
1176     st->st_mode |= S_IFCHR;
1177 #endif
1178 #ifdef S_IFFIFO
1179   else if (hdr->c_mode & CP_IFIFO)
1180     st->st_mode |= S_IFIFO;
1181 #endif
1182 #ifdef S_IFLNK
1183   else if (hdr->c_mode & CP_IFLNK)
1184     st->st_mode |= S_IFLNK;
1185 #endif
1186 #ifdef S_IFSOCK
1187   else if (hdr->c_mode & CP_IFSOCK)
1188     st->st_mode |= S_IFSOCK;
1189 #endif
1190 #ifdef S_IFNWK
1191   else if (hdr->c_mode & CP_IFNWK)
1192     st->st_mode |= S_IFNWK;
1193 #endif
1194   st->st_nlink = hdr->c_nlink;
1195   st->st_uid = CPIO_UID (hdr->c_uid);
1196   st->st_gid = CPIO_GID (hdr->c_gid);
1197   st->st_rdev = makedev (hdr->c_rdev_maj, hdr->c_rdev_min);
1198   st->st_mtime = hdr->c_mtime;
1199   st->st_size = hdr->c_filesize;
1200 }
1201 
1202 #ifndef HAVE_FCHOWN
1203 # define HAVE_FCHOWN 0
1204 #endif
1205 #ifndef HAVE_FCHMOD
1206 # define HAVE_FCHMOD 0
1207 #endif
1208 
1209 int
fchown_or_chown(int fd,const char * name,uid_t uid,uid_t gid)1210 fchown_or_chown (int fd, const char *name, uid_t uid, uid_t gid)
1211 {
1212   if (HAVE_FCHOWN && fd != -1)
1213     return fchown (fd, uid, gid);
1214   else
1215     return chown (name, uid, gid);
1216 }
1217 
1218 int
fchmod_or_chmod(int fd,const char * name,mode_t mode)1219 fchmod_or_chmod (int fd, const char *name, mode_t mode)
1220 {
1221   if (HAVE_FCHMOD && fd != -1)
1222     return fchmod (fd, mode);
1223   else
1224     return chmod (name, mode);
1225 }
1226 
1227 void
set_perms(int fd,struct cpio_file_stat * header)1228 set_perms (int fd, struct cpio_file_stat *header)
1229 {
1230   if (!no_chown_flag)
1231     {
1232       uid_t uid = CPIO_UID (header->c_uid);
1233       gid_t gid = CPIO_GID (header->c_gid);
1234       if ((fchown_or_chown (fd, header->c_name, uid, gid) < 0)
1235 	  && errno != EPERM)
1236 	chown_error_details (header->c_name, uid, gid);
1237     }
1238   /* chown may have turned off some permissions we wanted. */
1239   if (fchmod_or_chmod (fd, header->c_name, header->c_mode) < 0)
1240     chmod_error_details (header->c_name, header->c_mode);
1241   if (retain_time_flag)
1242     set_file_times (fd, header->c_name, header->c_mtime, header->c_mtime);
1243 }
1244 
1245 void
set_file_times(int fd,const char * name,unsigned long atime,unsigned long mtime)1246 set_file_times (int fd,
1247 		const char *name, unsigned long atime, unsigned long mtime)
1248 {
1249   struct timespec ts[2];
1250 
1251   memset (&ts, 0, sizeof ts);
1252 
1253   ts[0].tv_sec = atime;
1254   ts[1].tv_sec = mtime;
1255 
1256   /* Silently ignore EROFS because reading the file won't have upset its
1257      timestamp if it's on a read-only filesystem. */
1258   if (fdutimens (fd, name, ts) < 0 && errno != EROFS)
1259     utime_error (name);
1260 }
1261 
1262 /* Reallocate file_hdr->c_name to accomodate len bytes (including final \0) */
1263 void
cpio_realloc_c_name(struct cpio_file_stat * file_hdr,size_t len)1264 cpio_realloc_c_name (struct cpio_file_stat *file_hdr, size_t len)
1265 {
1266   while (file_hdr->c_name_buflen < len)
1267     file_hdr->c_name = x2realloc (file_hdr->c_name, &file_hdr->c_name_buflen);
1268 }
1269 
1270 void
cpio_set_c_name(struct cpio_file_stat * file_hdr,char * name)1271 cpio_set_c_name (struct cpio_file_stat *file_hdr, char *name)
1272 {
1273   size_t len = strlen (name) + 1;
1274 
1275   cpio_realloc_c_name (file_hdr, len);
1276   file_hdr->c_namesize = len;
1277   memmove (file_hdr->c_name, name, len);
1278 }
1279 
1280 /* Do we have to ignore absolute paths, and if so, does the filename
1281    have an absolute path?  Before calling this function make sure that the
1282    allocated NAME buffer has capacity at least 2 bytes. */
1283 
1284 void
cpio_safer_name_suffix(char * name,bool link_target,bool absolute_names,bool strip_leading_dots)1285 cpio_safer_name_suffix (char *name, bool link_target, bool absolute_names,
1286 			bool strip_leading_dots)
1287 {
1288   char *p = safer_name_suffix (name, link_target, absolute_names);
1289   if (strip_leading_dots && strcmp (p, "./"))
1290     /* strip leading `./' from the filename.  */
1291     while (*p == '.' && *(p + 1) == '/')
1292       {
1293 	++p;
1294 	while (*p == '/')
1295 	  ++p;
1296       }
1297   if (p != name)
1298     /* The 'p' string is shortened version of 'name' with one exception;  when
1299        the 'name' points to an empty string (buffer where name[0] == '\0') the
1300        'p' then points to static string ".".  So caller needs to ensure there
1301        are at least two bytes available in 'name' buffer so memmove succeeds. */
1302     memmove (name, p, (size_t)(strlen (p) + 1));
1303 }
1304 
1305 
1306 /* This is a simplified form of delayed set_stat used by GNU tar.
1307    With the time, both forms will merge and pass to paxutils
1308 
1309    List of directories whose statuses we need to extract after we've
1310    finished extracting their subsidiary files.  If you consider each
1311    contiguous subsequence of elements of the form [D]?[^D]*, where [D]
1312    represents an element where AFTER_LINKS is nonzero and [^D]
1313    represents an element where AFTER_LINKS is zero, then the head
1314    of the subsequence has the longest name, and each non-head element
1315    in the prefix is an ancestor (in the directory hierarchy) of the
1316    preceding element.  */
1317 
1318 struct delayed_set_stat
1319   {
1320     struct delayed_set_stat *next;
1321     struct cpio_file_stat stat;
1322     mode_t invert_permissions;
1323   };
1324 
1325 static struct delayed_set_stat *delayed_set_stat_head;
1326 
1327 void
delay_cpio_set_stat(struct cpio_file_stat * file_stat,mode_t invert_permissions)1328 delay_cpio_set_stat (struct cpio_file_stat *file_stat,
1329 		     mode_t invert_permissions)
1330 {
1331   size_t file_name_len = strlen (file_stat->c_name);
1332   struct delayed_set_stat *data =
1333     xmalloc (sizeof (struct delayed_set_stat) + file_name_len + 1);
1334   data->next = delayed_set_stat_head;
1335   memcpy (&data->stat, file_stat, sizeof data->stat);
1336   data->stat.c_name = (char*) (data + 1);
1337   strcpy (data->stat.c_name, file_stat->c_name);
1338   data->invert_permissions = invert_permissions;
1339   delayed_set_stat_head = data;
1340 }
1341 
1342 void
delay_set_stat(char const * file_name,struct stat * st,mode_t invert_permissions)1343 delay_set_stat (char const *file_name, struct stat *st,
1344 		mode_t invert_permissions)
1345 {
1346   struct cpio_file_stat fs;
1347 
1348   stat_to_cpio (&fs, st);
1349   fs.c_name = (char*) file_name;
1350   delay_cpio_set_stat (&fs, invert_permissions);
1351 }
1352 
1353 /* Update the delayed_set_stat info for an intermediate directory
1354    created within the file name of DIR.  The intermediate directory turned
1355    out to be the same as this directory, e.g. due to ".." or symbolic
1356    links.  *DIR_STAT_INFO is the status of the directory.  */
1357 int
repair_inter_delayed_set_stat(struct stat * dir_stat_info)1358 repair_inter_delayed_set_stat (struct stat *dir_stat_info)
1359 {
1360   struct delayed_set_stat *data;
1361   for (data = delayed_set_stat_head; data; data = data->next)
1362     {
1363       struct stat st;
1364       if (stat (data->stat.c_name, &st) != 0)
1365 	{
1366 	  stat_error (data->stat.c_name);
1367 	  return -1;
1368 	}
1369 
1370       if (st.st_dev == dir_stat_info->st_dev
1371 	  && st.st_ino == dir_stat_info->st_ino)
1372 	{
1373 	  stat_to_cpio (&data->stat, dir_stat_info);
1374 	  data->invert_permissions =
1375 	    ((dir_stat_info->st_mode ^ st.st_mode)
1376 	     & MODE_RWX & ~ newdir_umask);
1377 	  return 0;
1378 	}
1379     }
1380   return 1;
1381 }
1382 
1383 /* Update the delayed_set_stat info for a directory matching
1384    FILE_HDR.
1385 
1386    Return 0 if such info was found, 1 otherwise. */
1387 int
repair_delayed_set_stat(struct cpio_file_stat * file_hdr)1388 repair_delayed_set_stat (struct cpio_file_stat *file_hdr)
1389 {
1390   struct delayed_set_stat *data;
1391   for (data = delayed_set_stat_head; data; data = data->next)
1392     {
1393       if (strcmp (file_hdr->c_name, data->stat.c_name) == 0)
1394 	{
1395 	  data->invert_permissions = 0;
1396 	  memcpy (&data->stat, file_hdr,
1397 		  offsetof (struct cpio_file_stat, c_name));
1398 	  return 0;
1399 	}
1400     }
1401   return 1;
1402 }
1403 
1404 void
apply_delayed_set_stat()1405 apply_delayed_set_stat ()
1406 {
1407   while (delayed_set_stat_head)
1408     {
1409       struct delayed_set_stat *data = delayed_set_stat_head;
1410       if (data->invert_permissions)
1411 	{
1412 	  data->stat.c_mode ^= data->invert_permissions;
1413 	}
1414       set_perms (-1, &data->stat);
1415       delayed_set_stat_head = data->next;
1416       free (data);
1417     }
1418 }
1419 
1420 
1421 static int
cpio_mkdir(struct cpio_file_stat * file_hdr,int * setstat_delayed)1422 cpio_mkdir (struct cpio_file_stat *file_hdr, int *setstat_delayed)
1423 {
1424   int rc;
1425   mode_t mode = file_hdr->c_mode;
1426 
1427   if (!(file_hdr->c_mode & S_IWUSR))
1428     {
1429       rc = mkdir (file_hdr->c_name, mode | S_IWUSR);
1430       if (rc == 0)
1431 	{
1432 	  delay_cpio_set_stat (file_hdr, 0);
1433 	  *setstat_delayed = 1;
1434 	}
1435     }
1436   else
1437     {
1438       rc = mkdir (file_hdr->c_name, mode);
1439       *setstat_delayed = 0;
1440     }
1441   return rc;
1442 }
1443 
1444 int
cpio_create_dir(struct cpio_file_stat * file_hdr,int existing_dir)1445 cpio_create_dir (struct cpio_file_stat *file_hdr, int existing_dir)
1446 {
1447   int res;			/* Result of various function calls.  */
1448   int setstat_delayed = 0;
1449 
1450   if (to_stdout_option)
1451     return 0;
1452 
1453   /* Strip any trailing `/'s off the filename; tar puts
1454      them on.  We might as well do it here in case anybody
1455      else does too, since they cause strange things to happen.  */
1456   strip_trailing_slashes (file_hdr->c_name);
1457 
1458   /* Ignore the current directory.  It must already exist,
1459      and we don't want to change its permission, ownership
1460      or time.  */
1461   if (file_hdr->c_name[0] == '.' && file_hdr->c_name[1] == '\0')
1462     {
1463       return 0;
1464     }
1465 
1466   if (!existing_dir)
1467     res = cpio_mkdir (file_hdr, &setstat_delayed);
1468   else
1469     res = 0;
1470   if (res < 0 && create_dir_flag)
1471     {
1472       create_all_directories (file_hdr->c_name);
1473       res = cpio_mkdir (file_hdr, &setstat_delayed);
1474     }
1475   if (res < 0)
1476     {
1477       /* In some odd cases where the file_hdr->c_name includes `.',
1478 	 the directory may have actually been created by
1479 	 create_all_directories(), so the mkdir will fail
1480 	 because the directory exists.  If that's the case,
1481 	 don't complain about it.  */
1482       struct stat file_stat;
1483       if (errno != EEXIST)
1484 	{
1485 	  mkdir_error (file_hdr->c_name);
1486 	  return -1;
1487 	}
1488       if (lstat (file_hdr->c_name, &file_stat))
1489 	{
1490 	  stat_error (file_hdr->c_name);
1491 	  return -1;
1492 	}
1493       if (!(S_ISDIR (file_stat.st_mode)))
1494 	{
1495 	  error (0, 0, _("%s is not a directory"),
1496 		 quotearg_colon (file_hdr->c_name));
1497 	  return -1;
1498 	}
1499     }
1500 
1501   if (!setstat_delayed && repair_delayed_set_stat (file_hdr))
1502     set_perms (-1, file_hdr);
1503   return 0;
1504 }
1505 
1506 void
change_dir()1507 change_dir ()
1508 {
1509   if (change_directory_option && chdir (change_directory_option))
1510     {
1511       if (errno == ENOENT && create_dir_flag)
1512 	{
1513 	  if (make_path (change_directory_option, -1, -1,
1514 			 (warn_option & CPIO_WARN_INTERDIR) ?
1515 			 _("Creating directory `%s'") : NULL))
1516 	    exit (PAXEXIT_FAILURE);
1517 
1518 	  if (chdir (change_directory_option) == 0)
1519 	    return;
1520 	}
1521       error (PAXEXIT_FAILURE, errno,
1522 	     _("cannot change to directory `%s'"), change_directory_option);
1523     }
1524 }
1525 
1526 /* Return true if the archive format ARF stores inode numbers */
1527 int
arf_stores_inode_p(enum archive_format arf)1528 arf_stores_inode_p (enum archive_format arf)
1529 {
1530   switch (arf)
1531     {
1532     case arf_tar:
1533     case arf_ustar:
1534       return 0;
1535 
1536     default:
1537       break;
1538     }
1539   return 1;
1540 }
1541 
1542 void
cpio_file_stat_init(struct cpio_file_stat * file_hdr)1543 cpio_file_stat_init (struct cpio_file_stat *file_hdr)
1544 {
1545   memset (file_hdr, 0, sizeof (*file_hdr));
1546 }
1547 
1548 void
cpio_file_stat_free(struct cpio_file_stat * file_hdr)1549 cpio_file_stat_free (struct cpio_file_stat *file_hdr)
1550 {
1551   free (file_hdr->c_name);
1552   cpio_file_stat_init (file_hdr);
1553 }
1554