]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - contrib/cpio/src/util.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / contrib / cpio / src / util.c
1 /* $FreeBSD$ */
2
3 /* util.c - Several utility routines for cpio.
4    Copyright (C) 1990, 1991, 1992, 2001, 2004,
5    2006 Free Software Foundation, Inc.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public
18    License along with this program; if not, write to the Free
19    Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20    Boston, MA 02110-1301 USA.  */
21
22 #include <system.h>
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include "cpiohdr.h"
28 #include "dstring.h"
29 #include "extern.h"
30 #include <paxlib.h>
31 #include "filetypes.h"
32 #include <safe-read.h>
33 #include <full-write.h>
34 #include <rmt.h>
35 #include <hash.h>
36 #include <utimens.h>
37
38 #include <sys/ioctl.h>
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
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 (1, errno, _("write error"));
94         }
95       else
96         error (1, errno, _("write error"));
97     }
98   output_bytes += output_size;
99   out_buff = output_buffer;
100   output_size = 0;
101 }
102
103 static int sparse_write (int fildes, char *buf, unsigned int nbyte);
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
116 disk_empty_output_buffer (int out_des)
117 {
118   int 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);
140   else
141     bytes_written = write (out_des, output_buffer, output_size);
142
143   if (bytes_written != output_size)
144     {
145       error (1, errno, _("write error"));
146     }
147   output_bytes += output_size;
148   out_buff = output_buffer;
149   output_size = 0;
150 }
151
152 /* Exchange the halfwords of each element of the array of COUNT longs
153    starting at PTR.  PTR does not have to be aligned at a word
154    boundary.  */
155
156 void
157 swahw_array (char *ptr, int count)
158 {
159   char tmp;
160
161   for (; count > 0; --count)
162     {
163       tmp = *ptr;
164       *ptr = *(ptr + 2);
165       *(ptr + 2) = tmp;
166       ++ptr;
167       tmp = *ptr;
168       *ptr = *(ptr + 2);
169       *(ptr + 2) = tmp;
170       ptr += 3;
171     }
172 }
173
174 /* Read at most NUM_BYTES or `io_block_size' bytes, whichever is smaller,
175    into the start of `input_buffer' from file descriptor IN_DES.
176    Set `input_size' to the number of bytes read and reset `in_buff'.
177    Exit with an error if end of file is reached.  */
178
179 #ifdef BROKEN_LONG_TAPE_DRIVER
180 static long input_bytes_before_lseek = 0;
181 #endif
182
183 static void
184 tape_fill_input_buffer (int in_des, int num_bytes)
185 {
186 #ifdef BROKEN_LONG_TAPE_DRIVER
187   /* Some tape drivers seem to have a signed internal seek pointer and
188      they lose if it overflows and becomes negative (e.g. when writing 
189      tapes > 4Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the 
190      seek pointer and prevent it from overflowing.  */
191   if (input_is_special
192       && ( (input_bytes_before_lseek += num_bytes) >= 1073741824L) )
193     {
194       lseek(in_des, 0L, SEEK_SET);
195       input_bytes_before_lseek = 0;
196     }
197 #endif
198   in_buff = input_buffer;
199   num_bytes = (num_bytes < io_block_size) ? num_bytes : io_block_size;
200   input_size = rmtread (in_des, input_buffer, num_bytes);
201   if (input_size == 0 && input_is_special)
202     {
203       get_next_reel (in_des);
204       input_size = rmtread (in_des, input_buffer, num_bytes);
205     }
206   if (input_size < 0)
207     error (1, errno, _("read error"));
208   if (input_size == 0)
209     {
210       error (0, 0, _("premature end of file"));
211       exit (1);
212     }
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
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 < 0) 
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 \f
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
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
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);
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
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
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 (1, 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 \f
388 /* Skip the next NUM_BYTES bytes of file descriptor IN_DES.  */
389
390 void
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 \f
418 void
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 \f
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
444 copy_files_tape_to_disk (int in_des, int out_des, off_t num_bytes)
445 {
446   long size;
447   long 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
474 copy_files_disk_to_tape (int in_des, int out_des, off_t num_bytes,
475                          char *filename)
476 {
477   long size;
478   long 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, _("Read error at byte %lld in file %s, padding with zeros"),
502                         original_num_bytes - num_bytes, filename);
503             write_nuls_to_file (num_bytes, out_des, tape_buffered_write);
504             break;
505           }
506       size = (input_size < num_bytes) ? input_size : num_bytes;
507       if (crc_i_flag)
508         {
509           for (k = 0; k < size; ++k)
510             crc += in_buff[k] & 0xff;
511         }
512       tape_buffered_write (in_buff, out_des, size);
513       num_bytes -= size;
514       input_size -= size;
515       in_buff += size;
516     }
517 }
518 /* Copy a file using the input and output buffers, which may start out
519    partly full.  After the copy, the files are not closed nor the last
520    block flushed to output, and the input buffer may still be partly
521    full.  If `crc_i_flag' is set, add each byte to `crc'.
522    IN_DES is the file descriptor for input;
523    OUT_DES is the file descriptor for output;
524    NUM_BYTES is the number of bytes to copy.  */
525
526 void
527 copy_files_disk_to_disk (int in_des, int out_des, off_t num_bytes,
528                          char *filename)
529 {
530   long size;
531   long k;
532   off_t original_num_bytes;
533   int rc;
534
535   original_num_bytes = num_bytes;
536   while (num_bytes > 0)
537     {
538       if (input_size == 0)
539         if (rc = disk_fill_input_buffer (in_des, num_bytes))
540           {
541             if (rc > 0)
542               {
543                 char buf[UINTMAX_STRSIZE_BOUND];
544                 error (0, 0,
545                        ngettext ("File %s shrunk by %s byte, padding with zeros",
546                                  "File %s shrunk by %s bytes, padding with zeros",
547                                  num_bytes),
548                        filename,  STRINGIFY_BIGINT (num_bytes, buf));
549               }
550             else
551               error (0, 0, _("Read error at byte %lld in file %s, padding with zeros"),
552                         original_num_bytes - num_bytes, filename);
553             write_nuls_to_file (num_bytes, out_des, disk_buffered_write);
554             break;
555           }
556       size = (input_size < num_bytes) ? input_size : num_bytes;
557       if (crc_i_flag)
558         {
559           for (k = 0; k < size; ++k)
560             crc += in_buff[k] & 0xff;
561         }
562       disk_buffered_write (in_buff, out_des, size);
563       num_bytes -= size;
564       input_size -= size;
565       in_buff += size;
566     }
567 }
568 \f
569 /* Warn if file changed while it was being copied.  */
570
571 void
572 warn_if_file_changed (char *file_name, unsigned long old_file_size,
573                       off_t old_file_mtime)
574 {
575   struct stat new_file_stat;
576   if ((*xstat) (file_name, &new_file_stat) < 0)
577     {
578       stat_error (file_name);
579       return;
580     }
581
582   /* Only check growth, shrinkage detected in copy_files_disk_to_{disk,tape}()
583    */
584   if (new_file_stat.st_size > old_file_size)
585     error (0, 0,
586            ngettext ("File %s grew, %"PRIuMAX" new byte not copied",
587                      "File %s grew, %"PRIuMAX" new bytes not copied",
588                      (long)(new_file_stat.st_size - old_file_size)),
589            file_name, (uintmax_t) (new_file_stat.st_size - old_file_size));
590
591   else if (new_file_stat.st_mtime != old_file_mtime)
592     error (0, 0, _("File %s was modified while being copied"), file_name);
593 }
594 \f
595 /* Create all directories up to but not including the last part of NAME.
596    Do not destroy any nondirectories while creating directories.  */
597
598 void
599 create_all_directories (char *name)
600 {
601   char *dir;
602   int   mode;
603 #ifdef HPUX_CDF
604   int   cdf;
605 #endif
606
607   dir = dir_name (name);
608   mode = 0700;
609 #ifdef HPUX_CDF
610   cdf = islastparentcdf (name);
611   if (cdf)
612     {
613       dir [strlen (dir) - 1] = '\0';    /* remove final + */
614       mode = 04700;
615     }
616   
617 #endif
618   
619   if (dir == NULL)
620     error (2, 0, _("virtual memory exhausted"));
621
622   if (dir[0] != '.' || dir[1] != '\0')
623     make_path (dir, mode, 0700, -1, -1, (char *) NULL);
624
625   free (dir);
626 }
627
628 /* Prepare to append to an archive.  We have been in
629    process_copy_in, keeping track of the position where
630    the last header started in `last_header_start'.  Now we
631    have the starting position of the last header (the TRAILER!!!
632    header, or blank record for tar archives) and we want to start
633    writing (appending) over the last header.  The last header may
634    be in the middle of a block, so to keep the buffering in sync
635    we lseek back to the start of the block, read everything up
636    to but not including the last header, lseek back to the start
637    of the block, and then do a copy_buf_out of what we read.
638    Actually, we probably don't have to worry so much about keeping the
639    buffering perfect since you can only append to archives that
640    are disk files.  */
641
642 void
643 prepare_append (int out_file_des)
644 {
645   int start_of_header;
646   int start_of_block;
647   int useful_bytes_in_block;
648   char *tmp_buf;
649
650   start_of_header = last_header_start;
651   /* Figure out how many bytes we will rewrite, and where they start.  */
652   useful_bytes_in_block = start_of_header % io_block_size;
653   start_of_block = start_of_header - useful_bytes_in_block;
654
655   if (lseek (out_file_des, start_of_block, SEEK_SET) < 0)
656     error (1, errno, _("cannot seek on output"));
657   if (useful_bytes_in_block > 0)
658     {
659       tmp_buf = (char *) xmalloc (useful_bytes_in_block);
660       read (out_file_des, tmp_buf, useful_bytes_in_block);
661       if (lseek (out_file_des, start_of_block, SEEK_SET) < 0)
662         error (1, errno, _("cannot seek on output"));
663       /* fix juo -- is this copy_tape_buf_out?  or copy_disk? */
664       tape_buffered_write (tmp_buf, out_file_des, useful_bytes_in_block);
665       free (tmp_buf);
666     }
667
668   /* We are done reading the archive, so clear these since they
669      will now be used for reading in files that we are appending
670      to the archive.  */
671   input_size = 0;
672   input_bytes = 0;
673   in_buff = input_buffer;
674 }
675
676 /* Support for remembering inodes with multiple links.  Used in the
677    "copy in" and "copy pass" modes for making links instead of copying
678    the file.  */
679
680 struct inode_val
681 {
682   unsigned long inode;
683   unsigned long major_num;
684   unsigned long minor_num;
685   char *file_name;
686 };
687
688 /* Inode hash table.  Allocated by first call to add_inode.  */
689 static Hash_table *hash_table = NULL;
690
691 static size_t
692 inode_val_hasher (const void *val, size_t n_buckets)
693 {
694   const struct inode_val *ival = val;
695   return ival->inode % n_buckets;
696 }
697
698 static bool
699 inode_val_compare (const void *val1, const void *val2)
700 {
701   const struct inode_val *ival1 = val1;
702   const struct inode_val *ival2 = val2;
703   return ival1->inode == ival2->inode
704          && ival1->major_num == ival2->major_num
705          && ival1->minor_num == ival2->minor_num;
706 }
707
708 char *
709 find_inode_file (unsigned long node_num, unsigned long major_num,
710                  unsigned long minor_num)
711 {
712   struct inode_val sample;
713   struct inode_val *ival;
714   
715   if (!hash_table)
716     return NULL;
717   
718   sample.inode = node_num;
719   sample.major_num = major_num;
720   sample.minor_num = minor_num;
721   ival = hash_lookup (hash_table, &sample);
722   return ival ? ival->file_name : NULL;
723 }
724
725 /* Associate FILE_NAME with the inode NODE_NUM.  (Insert into hash table.)  */
726
727 void
728 add_inode (unsigned long node_num, char *file_name, unsigned long major_num,
729            unsigned long minor_num)
730 {
731   struct inode_val *temp;
732   struct inode_val *e;
733   
734   /* Create new inode record.  */
735   temp = (struct inode_val *) xmalloc (sizeof (struct inode_val));
736   temp->inode = node_num;
737   temp->major_num = major_num;
738   temp->minor_num = minor_num;
739   temp->file_name = xstrdup (file_name);
740
741   if (!((hash_table
742          || (hash_table = hash_initialize (0, 0, inode_val_hasher,
743                                            inode_val_compare, 0)))
744         && (e = hash_insert (hash_table, temp))))
745     xalloc_die ();
746   /* FIXME: e is not used */
747 }
748
749 \f
750 /* Open FILE in the mode specified by the command line options
751    and return an open file descriptor for it,
752    or -1 if it can't be opened.  */
753
754 int
755 open_archive (char *file)
756 {
757   int fd;
758   void (*copy_in) ();           /* Workaround for pcc bug.  */
759
760   copy_in = process_copy_in;
761
762   if (copy_function == copy_in)
763     fd = rmtopen (file, O_RDONLY | O_BINARY, MODE_RW, rsh_command_option);
764   else
765     {
766       if (!append_flag)
767         fd = rmtopen (file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, MODE_RW,
768                         rsh_command_option);
769       else
770         fd = rmtopen (file, O_RDWR | O_BINARY, MODE_RW, rsh_command_option);
771     }
772
773   return fd;
774 }
775
776 /* Attempt to rewind the tape drive on file descriptor TAPE_DES
777    and take it offline.  */
778
779 void
780 tape_offline (int tape_des)
781 {
782 #if defined(MTIOCTOP) && defined(MTOFFL)
783   struct mtop control;
784
785   control.mt_op = MTOFFL;
786   control.mt_count = 1;
787   rmtioctl (tape_des, MTIOCTOP, (char*) &control);      /* Don't care if it fails.  */
788 #endif
789 }
790
791 /* The file on file descriptor TAPE_DES is assumed to be magnetic tape
792    (or floppy disk or other device) and the end of the medium
793    has been reached.  Ask the user for to mount a new "tape" to continue
794    the processing.  If the user specified the device name on the
795    command line (with the -I, -O, -F or --file options), then we can
796    automatically re-open the same device to use the next medium.  If the
797    user did not specify the device name, then we have to ask them which
798    device to use.  */
799
800 void
801 get_next_reel (int tape_des)
802 {
803   static int reel_number = 1;
804   FILE *tty_in;                 /* File for interacting with user.  */
805   FILE *tty_out;                /* File for interacting with user.  */
806   int old_tape_des;
807   char *next_archive_name;
808   dynamic_string new_name;
809   char *str_res;
810
811   ds_init (&new_name, 128);
812
813   /* Open files for interactive communication.  */
814   tty_in = fopen (TTY_NAME, "r");
815   if (tty_in == NULL)
816     error (2, errno, TTY_NAME);
817   tty_out = fopen (TTY_NAME, "w");
818   if (tty_out == NULL)
819     error (2, errno, TTY_NAME);
820
821   old_tape_des = tape_des;
822   tape_offline (tape_des);
823   rmtclose (tape_des);
824
825   /* Give message and wait for carrage return.  User should hit carrage return
826      only after loading the next tape.  */
827   ++reel_number;
828   if (new_media_message)
829     fprintf (tty_out, "%s", new_media_message);
830   else if (new_media_message_with_number)
831     fprintf (tty_out, "%s%d%s", new_media_message_with_number, reel_number,
832              new_media_message_after_number);
833   else if (archive_name)
834     fprintf (tty_out, _("Found end of volume.  Load next volume and press RETURN. "));
835   else
836     fprintf (tty_out, _("Found end of volume.  To continue, type device/file name when ready.\n"));
837
838   fflush (tty_out);
839
840   if (archive_name)
841     {
842       int c;
843
844       do
845         c = getc (tty_in);
846       while (c != EOF && c != '\n');
847
848       tape_des = open_archive (archive_name);
849       if (tape_des == -1)
850         open_error (archive_name);
851     }
852   else
853     {
854       do
855         {
856           if (tape_des < 0)
857             {
858               fprintf (tty_out,
859                        _("To continue, type device/file name when ready.\n"));
860               fflush (tty_out);
861             }
862
863           str_res = ds_fgets (tty_in, &new_name);
864           if (str_res == NULL || str_res[0] == '\0')
865             exit (1);
866           next_archive_name = str_res;
867
868           tape_des = open_archive (next_archive_name);
869           if (tape_des == -1)
870             open_error (next_archive_name);
871         }
872       while (tape_des < 0);
873     }
874
875   /* We have to make sure that `tape_des' has not changed its value even
876      though we closed it and reopened it, since there are local
877      copies of it in other routines.  This works fine on Unix (even with
878      rmtread and rmtwrite) since open will always return the lowest
879      available file descriptor and we haven't closed any files (e.g.,
880      stdin, stdout or stderr) that were opened before we originally opened
881      the archive.  */
882
883   if (tape_des != old_tape_des)
884     error (1, 0, _("internal error: tape descriptor changed from %d to %d"),
885            old_tape_des, tape_des);
886
887   free (new_name.ds_string);
888   fclose (tty_in);
889   fclose (tty_out);
890 }
891
892 /* If MESSAGE does not contain the string "%d", make `new_media_message'
893    a copy of MESSAGE.  If MESSAGES does contain the string "%d", make
894    `new_media_message_with_number' a copy of MESSAGE up to, but
895    not including, the string "%d", and make `new_media_message_after_number'
896    a copy of MESSAGE after the string "%d".  */
897
898 void
899 set_new_media_message (char *message)
900 {
901   char *p;
902   int prev_was_percent;
903
904   p = message;
905   prev_was_percent = 0;
906   while (*p != '\0')
907     {
908       if (*p == 'd' && prev_was_percent)
909         break;
910       prev_was_percent = (*p == '%');
911       ++p;
912     }
913   if (*p == '\0')
914     {
915       new_media_message = xstrdup (message);
916     }
917   else
918     {
919       int length = p - message - 1;
920
921       new_media_message_with_number = xmalloc (length + 1);
922       strncpy (new_media_message_with_number, message, length);
923       new_media_message_with_number[length] = '\0';
924       length = strlen (p + 1);
925       new_media_message_after_number = xmalloc (length + 1);
926       strcpy (new_media_message_after_number, p + 1);
927     }
928 }
929
930 #ifdef SYMLINK_USES_UMASK
931 /* Most machines always create symlinks with rwxrwxrwx protection,
932    but some (HP/UX 8.07; maybe DEC's OSF on MIPS, too?) use the
933    umask when creating symlinks, so if your umask is 022 you end
934    up with rwxr-xr-x symlinks (although HP/UX seems to completely
935    ignore the protection).  There doesn't seem to be any way to
936    manipulate the modes once the symlinks are created (e.g.
937    a hypothetical "lchmod"), so to create them with the right
938    modes we have to set the umask first.  */
939
940 int
941 umasked_symlink (char *name1, char *name2, int mode)
942 {
943   int   old_umask;
944   int   rc;
945   mode = ~(mode & 0777) & 0777;
946   old_umask = umask (mode);
947   rc = symlink (name1, name2);
948   umask (old_umask);
949   return rc;
950 }
951 #endif /* SYMLINK_USES_UMASK */
952
953 #ifdef HPUX_CDF
954 /* When we create a cpio archive we mark CDF's by putting an extra `/'
955    after their component name so we can distinguish the CDF's when we
956    extract the archive (in case the "hidden" directory's files appear
957    in the archive before the directory itself).  E.g., in the path
958    "a/b+/c", if b+ is a CDF, we will write this path as "a/b+//c" in
959    the archive so when we extract the archive we will know that b+
960    is actually a CDF, and not an ordinary directory whose name happens
961    to end in `+'.  We also do the same thing internally in copypass.c.  */
962
963
964 /* Take an input pathname and check it for CDF's.  Insert an extra
965    `/' in the pathname after each "hidden" directory.  If we add
966    any `/'s, return a malloced string instead of the original input
967    string.
968    FIXME: This creates a memory leak.
969 */
970
971 char *
972 add_cdf_double_slashes (char *input_name)
973 {
974   static char *ret_name = NULL; /* re-usuable return buffer (malloc'ed)  */
975   static int ret_size = -1;     /* size of return buffer.  */
976   char *p;
977   char *q;
978   int n;
979   struct stat dir_stat;
980
981   /*  Search for a `/' preceeded by a `+'.  */
982
983   for (p = input_name; *p != '\0'; ++p)
984     {
985       if ( (*p == '+') && (*(p + 1) == '/') )
986         break;
987     }
988
989   /* If we didn't find a `/' preceeded by a `+' then there are
990      no CDF's in this pathname.  Return the original pathname.  */
991
992   if (*p == '\0')
993     return input_name;
994
995   /* There was a `/' preceeded by a `+' in the pathname.  If it is a CDF 
996      then we will need to copy the input pathname to our return
997      buffer so we can insert the extra `/'s.  Since we can't tell
998      yet whether or not it is a CDF we will just always copy the
999      string to the return buffer.  First we have to make sure the
1000      buffer is large enough to hold the string and any number of
1001      extra `/'s we might add.  */
1002
1003   n = 2 * (strlen (input_name) + 1);
1004   if (n >= ret_size)
1005     {
1006       if (ret_size < 0)
1007         ret_name = (char *) malloc (n);
1008       else
1009         ret_name = (char *)realloc (ret_name, n);
1010       ret_size = n;
1011     }
1012
1013   /* Clear the `/' after this component, so we can stat the pathname 
1014      up to and including this component.  */
1015   ++p;
1016   *p = '\0';
1017   if ((*xstat) (input_name, &dir_stat) < 0)
1018     {
1019       stat_error (input_name);
1020       return input_name;
1021     }
1022
1023   /* Now put back the `/' after this component and copy the pathname up to
1024      and including this component and its trailing `/' to the return
1025      buffer.  */
1026   *p++ = '/';
1027   strncpy (ret_name, input_name, p - input_name);
1028   q = ret_name + (p - input_name);
1029
1030   /* If it was a CDF, add another `/'.  */
1031   if (S_ISDIR (dir_stat.st_mode) && (dir_stat.st_mode & 04000) )
1032     *q++ = '/';
1033
1034   /* Go through the rest of the input pathname, copying it to the
1035      return buffer, and adding an extra `/' after each CDF.  */
1036   while (*p != '\0')
1037     {
1038       if ( (*p == '+') && (*(p + 1) == '/') )
1039         {
1040           *q++ = *p++;
1041
1042           *p = '\0';
1043           if ((*xstat) (input_name, &dir_stat) < 0)
1044             {
1045               stat_error (input_name);
1046               return input_name;
1047             }
1048           *p = '/';
1049
1050           if (S_ISDIR (dir_stat.st_mode) && (dir_stat.st_mode & 04000) )
1051             *q++ = '/';
1052         }
1053       *q++ = *p++;
1054     }
1055   *q = '\0';
1056
1057   return ret_name;
1058 }
1059
1060 /* Is the last parent directory (e.g., c in a/b/c/d) a CDF?  If the
1061    directory name ends in `+' and is followed by 2 `/'s instead of 1
1062    then it is.  This is only the case for cpio archives, but we don't
1063    have to worry about tar because tar always has the directory before
1064    its files (or else we lose).  */
1065 int
1066 islastparentcdf (char *path)
1067 {
1068   char *newpath;
1069   char *slash;
1070   int slash_count;
1071   int length;                   /* Length of result, not including NUL.  */
1072
1073   slash = strrchr (path, '/');
1074   if (slash == 0)
1075     return 0;
1076   else
1077     {
1078       slash_count = 0;
1079       while (slash > path && *slash == '/')
1080         {
1081           ++slash_count;
1082           --slash;
1083         }
1084
1085
1086       if ( (*slash == '+') && (slash_count >= 2) )
1087         return 1;
1088     }
1089   return 0;
1090 }
1091 #endif
1092
1093 #define DISKBLOCKSIZE   (512)
1094
1095 static int
1096 buf_all_zeros (char *buf, int bufsize)
1097 {
1098   int   i;
1099   for (i = 0; i < bufsize; ++i)
1100     {
1101       if (*buf++ != '\0')
1102         return 0;
1103     }
1104   return 1;
1105 }
1106
1107 int delayed_seek_count = 0;
1108
1109 /* Write NBYTE bytes from BUF to remote tape connection FILDES.
1110    Return the number of bytes written on success, -1 on error.  */
1111
1112 static int
1113 sparse_write (int fildes, char *buf, unsigned int nbyte)
1114 {
1115   int complete_block_count;
1116   int leftover_bytes_count;
1117   int seek_count;
1118   int write_count;
1119   char *cur_write_start;
1120   int lseek_rc;
1121   int write_rc;
1122   int i;
1123   enum { begin, in_zeros, not_in_zeros } state;
1124
1125   complete_block_count = nbyte / DISKBLOCKSIZE;
1126   leftover_bytes_count = nbyte % DISKBLOCKSIZE;
1127
1128   if (delayed_seek_count != 0)
1129     state = in_zeros;
1130   else
1131     state = begin;
1132
1133   seek_count = delayed_seek_count;
1134
1135   for (i = 0; i < complete_block_count; ++i)
1136     {
1137       switch (state)
1138         {
1139           case begin :
1140             if (buf_all_zeros (buf, DISKBLOCKSIZE))
1141               {
1142                 seek_count = DISKBLOCKSIZE;
1143                 state = in_zeros;
1144               }
1145             else
1146               {
1147                 cur_write_start = buf;
1148                 write_count = DISKBLOCKSIZE;
1149                 state = not_in_zeros;
1150               }
1151             buf += DISKBLOCKSIZE;
1152             break;
1153             
1154           case in_zeros :
1155             if (buf_all_zeros (buf, DISKBLOCKSIZE))
1156               {
1157                 seek_count += DISKBLOCKSIZE;
1158               }
1159             else
1160               {
1161                 lseek (fildes, seek_count, SEEK_CUR);
1162                 cur_write_start = buf;
1163                 write_count = DISKBLOCKSIZE;
1164                 state = not_in_zeros;
1165               }
1166             buf += DISKBLOCKSIZE;
1167             break;
1168             
1169           case not_in_zeros :
1170             if (buf_all_zeros (buf, DISKBLOCKSIZE))
1171               {
1172                 write_rc = write (fildes, cur_write_start, write_count);
1173                 seek_count = DISKBLOCKSIZE;
1174                 state = in_zeros;
1175               }
1176             else
1177               {
1178                 write_count += DISKBLOCKSIZE;
1179               }
1180             buf += DISKBLOCKSIZE;
1181             break;
1182         }
1183     }
1184
1185   switch (state)
1186     {
1187       case begin :
1188       case in_zeros :
1189         delayed_seek_count = seek_count;
1190         break;
1191         
1192       case not_in_zeros :
1193         write_rc = write (fildes, cur_write_start, write_count);
1194         delayed_seek_count = 0;
1195         break;
1196     }
1197
1198   if (leftover_bytes_count != 0)
1199     {
1200       if (delayed_seek_count != 0)
1201         {
1202           lseek_rc = lseek (fildes, delayed_seek_count, SEEK_CUR);
1203           delayed_seek_count = 0;
1204         }
1205       write_rc = write (fildes, buf, leftover_bytes_count);
1206     }
1207   return nbyte;
1208 }
1209
1210 #define CPIO_UID(uid) (set_owner_flag ? set_owner : (uid))
1211 #define CPIO_GID(gid) (set_group_flag ? set_group : (gid))
1212
1213 void
1214 stat_to_cpio (struct cpio_file_stat *hdr, struct stat *st)
1215 {
1216   hdr->c_dev_maj = major (st->st_dev);
1217   hdr->c_dev_min = minor (st->st_dev);
1218   hdr->c_ino = st->st_ino;
1219   /* For POSIX systems that don't define the S_IF macros,
1220      we can't assume that S_ISfoo means the standard Unix
1221      S_IFfoo bit(s) are set.  So do it manually, with a
1222      different name.  Bleah.  */
1223   hdr->c_mode = (st->st_mode & 07777);
1224   if (S_ISREG (st->st_mode))
1225     hdr->c_mode |= CP_IFREG;
1226   else if (S_ISDIR (st->st_mode))
1227     hdr->c_mode |= CP_IFDIR;
1228 #ifdef S_ISBLK
1229   else if (S_ISBLK (st->st_mode))
1230     hdr->c_mode |= CP_IFBLK;
1231 #endif
1232 #ifdef S_ISCHR
1233   else if (S_ISCHR (st->st_mode))
1234     hdr->c_mode |= CP_IFCHR;
1235 #endif
1236 #ifdef S_ISFIFO
1237   else if (S_ISFIFO (st->st_mode))
1238     hdr->c_mode |= CP_IFIFO;
1239 #endif
1240 #ifdef S_ISLNK
1241   else if (S_ISLNK (st->st_mode))
1242     hdr->c_mode |= CP_IFLNK;
1243 #endif
1244 #ifdef S_ISSOCK
1245   else if (S_ISSOCK (st->st_mode))
1246     hdr->c_mode |= CP_IFSOCK;
1247 #endif
1248 #ifdef S_ISNWK
1249   else if (S_ISNWK (st->st_mode))
1250     hdr->c_mode |= CP_IFNWK;
1251 #endif
1252   hdr->c_uid = CPIO_UID (st->st_uid);
1253   hdr->c_gid = CPIO_GID (st->st_gid);
1254   hdr->c_nlink = st->st_nlink;
1255   hdr->c_rdev_maj = major (st->st_rdev);
1256   hdr->c_rdev_min = minor (st->st_rdev);
1257   hdr->c_mtime = st->st_mtime;
1258   hdr->c_filesize = st->st_size;
1259   hdr->c_chksum = 0;
1260   hdr->c_tar_linkname = NULL;
1261 }
1262
1263 #ifndef HAVE_FCHOWN
1264 # define fchown(fd, uid, gid) (-1)
1265 #endif
1266
1267 int
1268 fchown_or_chown (int fd, const char *name, uid_t uid, uid_t gid)
1269 {
1270   if (HAVE_FCHOWN && fd != -1)
1271     return fchown (fd, uid, gid);
1272   else
1273     return chown (name, uid, gid);
1274 }
1275
1276 int
1277 fchmod_or_chmod (int fd, const char *name, mode_t mode)
1278 {
1279   if (HAVE_FCHMOD && fd != -1)
1280     return fchmod (fd, mode);
1281   else
1282     return chmod(name, mode);
1283 }
1284
1285 void
1286 set_perms (int fd, struct cpio_file_stat *header)
1287 {
1288   if (!no_chown_flag)
1289     {
1290       uid_t uid = CPIO_UID (header->c_uid);
1291       gid_t gid = CPIO_GID (header->c_gid); 
1292       if ((fchown_or_chown (fd, header->c_name, uid, gid) < 0)
1293           && errno != EPERM)
1294         chown_error_details (header->c_name, uid, gid);
1295     }
1296   /* chown may have turned off some permissions we wanted. */
1297   if (fchmod_or_chmod (fd, header->c_name, header->c_mode) < 0)
1298     chmod_error_details (header->c_name, header->c_mode);
1299 #ifdef HPUX_CDF
1300   if ((header->c_mode & CP_IFMT) && cdf_flag)
1301     /* Once we "hide" the directory with the chmod(),
1302        we have to refer to it using name+ instead of name.  */
1303     file_hdr->c_name [cdf_char] = '+';
1304 #endif
1305   if (retain_time_flag)
1306     set_file_times (fd, header->c_name, header->c_mtime, header->c_mtime);
1307 }
1308
1309 void
1310 set_file_times (int fd,
1311                 const char *name, unsigned long atime, unsigned long mtime)
1312 {
1313   struct timespec ts[2];
1314   
1315   memset (&ts, 0, sizeof ts);
1316
1317   ts[0].tv_sec = atime;
1318   ts[1].tv_sec = mtime;
1319
1320   /* Silently ignore EROFS because reading the file won't have upset its 
1321      timestamp if it's on a read-only filesystem. */
1322   if (gl_futimens (fd, name, ts) < 0 && errno != EROFS)
1323     utime_error (name);
1324 }
1325
1326 /* Do we have to ignore absolute paths, and if so, does the filename
1327    have an absolute path?  */
1328 void
1329 cpio_safer_name_suffix (char *name, bool link_target, bool absolute_names,
1330                         bool strip_leading_dots)
1331 {
1332   char *p = safer_name_suffix (name, link_target, absolute_names);
1333   if (strip_leading_dots && strcmp (p, "./"))
1334     /* strip leading `./' from the filename.  */
1335     while (*p == '.' && *(p + 1) == '/')
1336       {
1337         ++p;
1338         while (*p == '/')
1339           ++p;
1340       }
1341   if (p != name)
1342     memmove (name, p, (size_t)(strlen (p) + 1));
1343 }
1344