]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - contrib/cpio/src/util.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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 Free Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License along
17    with this program; if not, write to the Free Software Foundation, Inc.,
18    59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 <rmt.h>
29
30 #include <sys/ioctl.h>
31
32 #ifdef HAVE_SYS_MTIO_H
33 #ifdef HAVE_SYS_IO_TRIOCTL_H
34 #include <sys/io/trioctl.h>
35 #endif
36 #include <sys/mtio.h>
37 #endif
38
39 #if !HAVE_DECL_ERRNO
40 extern int errno;
41 #endif
42
43 /* Write `output_size' bytes of `output_buffer' to file
44    descriptor OUT_DES and reset `output_size' and `out_buff'.  */
45
46 void
47 tape_empty_output_buffer (int out_des)
48 {
49   int bytes_written;
50
51 #ifdef BROKEN_LONG_TAPE_DRIVER
52   static long output_bytes_before_lseek = 0;
53
54   /* Some tape drivers seem to have a signed internal seek pointer and
55      they lose if it overflows and becomes negative (e.g. when writing 
56      tapes > 2Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the 
57      seek pointer and prevent it from overflowing.  */
58   if (output_is_special
59      && ( (output_bytes_before_lseek += output_size) >= 1073741824L) )
60     {
61       lseek(out_des, 0L, SEEK_SET);
62       output_bytes_before_lseek = 0;
63     }
64 #endif
65
66   bytes_written = rmtwrite (out_des, output_buffer, output_size);
67   if (bytes_written != output_size)
68     {
69       int rest_bytes_written;
70       int rest_output_size;
71
72       if (output_is_special
73           && (bytes_written >= 0
74               || (bytes_written < 0
75                   && (errno == ENOSPC || errno == EIO || errno == ENXIO))))
76         {
77           get_next_reel (out_des);
78           if (bytes_written > 0)
79             rest_output_size = output_size - bytes_written;
80           else
81             rest_output_size = output_size;
82           rest_bytes_written = rmtwrite (out_des, output_buffer,
83                                          rest_output_size);
84           if (rest_bytes_written != rest_output_size)
85             error (1, errno, _("write error"));
86         }
87       else
88         error (1, errno, _("write error"));
89     }
90   output_bytes += output_size;
91   out_buff = output_buffer;
92   output_size = 0;
93 }
94
95 /* Write `output_size' bytes of `output_buffer' to file
96    descriptor OUT_DES and reset `output_size' and `out_buff'.
97    If `swapping_halfwords' or `swapping_bytes' is set,
98    do the appropriate swapping first.  Our callers have
99    to make sure to only set these flags if `output_size' 
100    is appropriate (a multiple of 4 for `swapping_halfwords',
101    2 for `swapping_bytes').  The fact that DISK_IO_BLOCK_SIZE
102    must always be a multiple of 4 helps us (and our callers)
103    insure this.  */
104
105 void
106 disk_empty_output_buffer (int out_des)
107 {
108   int bytes_written;
109
110   if (swapping_halfwords || swapping_bytes)
111     {
112       if (swapping_halfwords)
113         {
114           int complete_words;
115           complete_words = output_size / 4;
116           swahw_array (output_buffer, complete_words);
117           if (swapping_bytes)
118             swab_array (output_buffer, 2 * complete_words);
119         }
120       else
121         {
122           int complete_halfwords;
123           complete_halfwords = output_size /2;
124           swab_array (output_buffer, complete_halfwords);
125         }
126     }
127
128   if (sparse_flag)
129     bytes_written = sparse_write (out_des, output_buffer, output_size);
130   else
131     bytes_written = write (out_des, output_buffer, output_size);
132
133   if (bytes_written != output_size)
134     {
135       error (1, errno, _("write error"));
136     }
137   output_bytes += output_size;
138   out_buff = output_buffer;
139   output_size = 0;
140 }
141
142 /* Exchange the halfwords of each element of the array of COUNT longs
143    starting at PTR.  PTR does not have to be aligned at a word
144    boundary.  */
145
146 void
147 swahw_array (char *ptr, int count)
148 {
149   char tmp;
150
151   for (; count > 0; --count)
152     {
153       tmp = *ptr;
154       *ptr = *(ptr + 2);
155       *(ptr + 2) = tmp;
156       ++ptr;
157       tmp = *ptr;
158       *ptr = *(ptr + 2);
159       *(ptr + 2) = tmp;
160       ptr += 3;
161     }
162 }
163
164 /* Read at most NUM_BYTES or `io_block_size' bytes, whichever is smaller,
165    into the start of `input_buffer' from file descriptor IN_DES.
166    Set `input_size' to the number of bytes read and reset `in_buff'.
167    Exit with an error if end of file is reached.  */
168
169 #ifdef BROKEN_LONG_TAPE_DRIVER
170 static long input_bytes_before_lseek = 0;
171 #endif
172
173 static void
174 tape_fill_input_buffer (int in_des, int num_bytes)
175 {
176 #ifdef BROKEN_LONG_TAPE_DRIVER
177   /* Some tape drivers seem to have a signed internal seek pointer and
178      they lose if it overflows and becomes negative (e.g. when writing 
179      tapes > 4Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the 
180      seek pointer and prevent it from overflowing.  */
181   if (input_is_special
182       && ( (input_bytes_before_lseek += num_bytes) >= 1073741824L) )
183     {
184       lseek(in_des, 0L, SEEK_SET);
185       input_bytes_before_lseek = 0;
186     }
187 #endif
188   in_buff = input_buffer;
189   num_bytes = (num_bytes < io_block_size) ? num_bytes : io_block_size;
190   input_size = rmtread (in_des, input_buffer, num_bytes);
191   if (input_size == 0 && input_is_special)
192     {
193       get_next_reel (in_des);
194       input_size = rmtread (in_des, input_buffer, num_bytes);
195     }
196   if (input_size < 0)
197     error (1, errno, _("read error"));
198   if (input_size == 0)
199     {
200       error (0, 0, _("premature end of file"));
201       exit (1);
202     }
203   input_bytes += input_size;
204 }
205
206 /* Read at most NUM_BYTES or `DISK_IO_BLOCK_SIZE' bytes, whichever is smaller,
207    into the start of `input_buffer' from file descriptor IN_DES.
208    Set `input_size' to the number of bytes read and reset `in_buff'.
209    Exit with an error if end of file is reached.  */
210
211 static int
212 disk_fill_input_buffer (int in_des, int num_bytes)
213 {
214   in_buff = input_buffer;
215   num_bytes = (num_bytes < DISK_IO_BLOCK_SIZE) ? num_bytes : DISK_IO_BLOCK_SIZE;
216   input_size = read (in_des, input_buffer, num_bytes);
217   if (input_size < 0) 
218     {
219       input_size = 0;
220       return (-1);
221     }
222   else if (input_size == 0)
223     return (1);
224   input_bytes += input_size;
225   return (0);
226 }
227 \f
228 /* Copy NUM_BYTES of buffer IN_BUF to `out_buff', which may be partly full.
229    When `out_buff' fills up, flush it to file descriptor OUT_DES.  */
230
231 void
232 tape_buffered_write (char *in_buf, int out_des, long num_bytes)
233 {
234   register long bytes_left = num_bytes; /* Bytes needing to be copied.  */
235   register long space_left;     /* Room left in output buffer.  */
236
237   while (bytes_left > 0)
238     {
239       space_left = io_block_size - output_size;
240       if (space_left == 0)
241         tape_empty_output_buffer (out_des);
242       else
243         {
244           if (bytes_left < space_left)
245             space_left = bytes_left;
246           bcopy (in_buf, out_buff, (unsigned) space_left);
247           out_buff += space_left;
248           output_size += space_left;
249           in_buf += space_left;
250           bytes_left -= space_left;
251         }
252     }
253 }
254
255 /* Copy NUM_BYTES of buffer IN_BUF to `out_buff', which may be partly full.
256    When `out_buff' fills up, flush it to file descriptor OUT_DES.  */
257
258 void
259 disk_buffered_write (char *in_buf, int out_des, long num_bytes)
260 {
261   register long bytes_left = num_bytes; /* Bytes needing to be copied.  */
262   register long space_left;     /* Room left in output buffer.  */
263
264   while (bytes_left > 0)
265     {
266       space_left = DISK_IO_BLOCK_SIZE - output_size;
267       if (space_left == 0)
268         disk_empty_output_buffer (out_des);
269       else
270         {
271           if (bytes_left < space_left)
272             space_left = bytes_left;
273           bcopy (in_buf, out_buff, (unsigned) space_left);
274           out_buff += space_left;
275           output_size += space_left;
276           in_buf += space_left;
277           bytes_left -= space_left;
278         }
279     }
280 }
281
282 /* Copy NUM_BYTES of buffer `in_buff' into IN_BUF.
283    `in_buff' may be partly full.
284    When `in_buff' is exhausted, refill it from file descriptor IN_DES.  */
285
286 void
287 tape_buffered_read (char *in_buf, int in_des, long num_bytes)
288 {
289   register long bytes_left = num_bytes; /* Bytes needing to be copied.  */
290   register long space_left;     /* Bytes to copy from input buffer.  */
291
292   while (bytes_left > 0)
293     {
294       if (input_size == 0)
295         tape_fill_input_buffer (in_des, io_block_size);
296       if (bytes_left < input_size)
297         space_left = bytes_left;
298       else
299         space_left = input_size;
300       bcopy (in_buff, in_buf, (unsigned) space_left);
301       in_buff += space_left;
302       in_buf += space_left;
303       input_size -= space_left;
304       bytes_left -= space_left;
305     }
306 }
307
308 /* Copy the the next NUM_BYTES bytes of `input_buffer' into PEEK_BUF.
309    If NUM_BYTES bytes are not available, read the next `io_block_size' bytes
310    into the end of `input_buffer' and update `input_size'.
311
312    Return the number of bytes copied into PEEK_BUF.
313    If the number of bytes returned is less than NUM_BYTES,
314    then EOF has been reached.  */
315
316 int
317 tape_buffered_peek (char *peek_buf, int in_des, int num_bytes)
318 {
319   long tmp_input_size;
320   long got_bytes;
321   char *append_buf;
322
323 #ifdef BROKEN_LONG_TAPE_DRIVER
324   /* Some tape drivers seem to have a signed internal seek pointer and
325      they lose if it overflows and becomes negative (e.g. when writing 
326      tapes > 4Gb).  Doing an lseek (des, 0, SEEK_SET) seems to reset the 
327      seek pointer and prevent it from overflowing.  */
328   if (input_is_special
329       && ( (input_bytes_before_lseek += num_bytes) >= 1073741824L) )
330     {
331       lseek(in_des, 0L, SEEK_SET);
332       input_bytes_before_lseek = 0;
333     }
334 #endif
335
336   while (input_size < num_bytes)
337     {
338       append_buf = in_buff + input_size;
339       if ( (append_buf - input_buffer) >= input_buffer_size)
340         {
341           /* We can keep up to 2 "blocks" (either the physical block size
342              or 512 bytes(the size of a tar record), which ever is
343              larger) in the input buffer when we are peeking.  We
344              assume that our caller will never be interested in peeking
345              ahead at more than 512 bytes, so we know that by the time
346              we need a 3rd "block" in the buffer we can throw away the
347              first block to make room.  */
348           int half;
349           half = input_buffer_size / 2;
350           bcopy (input_buffer + half, input_buffer, half);
351           in_buff = in_buff - half;
352           append_buf = append_buf - half;
353         }
354       tmp_input_size = rmtread (in_des, append_buf, io_block_size);
355       if (tmp_input_size == 0)
356         {
357           if (input_is_special)
358             {
359               get_next_reel (in_des);
360               tmp_input_size = rmtread (in_des, append_buf, io_block_size);
361             }
362           else
363             break;
364         }
365       if (tmp_input_size < 0)
366         error (1, errno, _("read error"));
367       input_bytes += tmp_input_size;
368       input_size += tmp_input_size;
369     }
370   if (num_bytes <= input_size)
371     got_bytes = num_bytes;
372   else
373     got_bytes = input_size;
374   bcopy (in_buff, peek_buf, (unsigned) got_bytes);
375   return got_bytes;
376 }
377 \f
378 /* Skip the next NUM_BYTES bytes of file descriptor IN_DES.  */
379
380 void
381 tape_toss_input (int in_des, long num_bytes)
382 {
383   register long bytes_left = num_bytes; /* Bytes needing to be copied.  */
384   register long space_left;     /* Bytes to copy from input buffer.  */
385
386   while (bytes_left > 0)
387     {
388       if (input_size == 0)
389         tape_fill_input_buffer (in_des, io_block_size);
390       if (bytes_left < input_size)
391         space_left = bytes_left;
392       else
393         space_left = input_size;
394
395       if (crc_i_flag && only_verify_crc_flag)
396         {
397           int k;
398           for (k = 0; k < space_left; ++k)
399             crc += in_buff[k] & 0xff;
400         }
401
402       in_buff += space_left;
403       input_size -= space_left;
404       bytes_left -= space_left;
405     }
406 }
407 \f
408 static void
409 write_nuls_to_file (long num_bytes, int out_des, 
410                     void (*writer) (char *in_buf, int out_des, long num_bytes))
411 {
412   long  blocks;
413   long  extra_bytes;
414   long  i;
415
416   blocks = num_bytes / 512;
417   extra_bytes = num_bytes % 512;
418   for (i = 0; i < blocks; ++i)
419     writer (zeros_512, out_des, 512);
420   if (extra_bytes)
421     writer (zeros_512, out_des, extra_bytes);
422 }
423 \f
424 /* Copy a file using the input and output buffers, which may start out
425    partly full.  After the copy, the files are not closed nor the last
426    block flushed to output, and the input buffer may still be partly
427    full.  If `crc_i_flag' is set, add each byte to `crc'.
428    IN_DES is the file descriptor for input;
429    OUT_DES is the file descriptor for output;
430    NUM_BYTES is the number of bytes to copy.  */
431
432 void
433 copy_files_tape_to_disk (int in_des, int out_des, long num_bytes)
434 {
435   long size;
436   long k;
437
438   while (num_bytes > 0)
439     {
440       if (input_size == 0)
441         tape_fill_input_buffer (in_des, io_block_size);
442       size = (input_size < num_bytes) ? input_size : num_bytes;
443       if (crc_i_flag)
444         {
445           for (k = 0; k < size; ++k)
446             crc += in_buff[k] & 0xff;
447         }
448       disk_buffered_write (in_buff, out_des, size);
449       num_bytes -= size;
450       input_size -= size;
451       in_buff += size;
452     }
453 }
454 /* Copy a file using the input and output buffers, which may start out
455    partly full.  After the copy, the files are not closed nor the last
456    block flushed to output, and the input buffer may still be partly
457    full.  If `crc_i_flag' is set, add each byte to `crc'.
458    IN_DES is the file descriptor for input;
459    OUT_DES is the file descriptor for output;
460    NUM_BYTES is the number of bytes to copy.  */
461
462 void
463 copy_files_disk_to_tape (int in_des, int out_des, long num_bytes,
464                          char *filename)
465 {
466   long size;
467   long k;
468   int rc;
469   long original_num_bytes;
470
471   original_num_bytes = num_bytes;
472
473   while (num_bytes > 0)
474     {
475       if (input_size == 0)
476         if (rc = disk_fill_input_buffer (in_des,
477           num_bytes < DISK_IO_BLOCK_SIZE ?
478           num_bytes : DISK_IO_BLOCK_SIZE))
479           {
480             if (rc > 0)
481               error (0, 0, _("File %s shrunk by %ld bytes, padding with zeros"),
482                                 filename, num_bytes);
483             else
484               error (0, 0, _("Read error at byte %ld in file %s, padding with zeros"),
485                         original_num_bytes - num_bytes, filename);
486             write_nuls_to_file (num_bytes, out_des, tape_buffered_write);
487             break;
488           }
489       size = (input_size < num_bytes) ? input_size : num_bytes;
490       if (crc_i_flag)
491         {
492           for (k = 0; k < size; ++k)
493             crc += in_buff[k] & 0xff;
494         }
495       tape_buffered_write (in_buff, out_des, size);
496       num_bytes -= size;
497       input_size -= size;
498       in_buff += size;
499     }
500 }
501 /* Copy a file using the input and output buffers, which may start out
502    partly full.  After the copy, the files are not closed nor the last
503    block flushed to output, and the input buffer may still be partly
504    full.  If `crc_i_flag' is set, add each byte to `crc'.
505    IN_DES is the file descriptor for input;
506    OUT_DES is the file descriptor for output;
507    NUM_BYTES is the number of bytes to copy.  */
508
509 void
510 copy_files_disk_to_disk (int in_des, int out_des, long num_bytes,
511                          char *filename)
512 {
513   long size;
514   long k;
515   long original_num_bytes;
516   int rc;
517
518   original_num_bytes = num_bytes;
519   while (num_bytes > 0)
520     {
521       if (input_size == 0)
522         if (rc = disk_fill_input_buffer (in_des, num_bytes))
523           {
524             if (rc > 0)
525               error (0, 0, _("File %s shrunk by %ld bytes, padding with zeros"),
526                                 filename, num_bytes);
527             else
528               error (0, 0, _("Read error at byte %ld in file %s, padding with zeros"),
529                         original_num_bytes - num_bytes, filename);
530             write_nuls_to_file (num_bytes, out_des, disk_buffered_write);
531             break;
532           }
533       size = (input_size < num_bytes) ? input_size : num_bytes;
534       if (crc_i_flag)
535         {
536           for (k = 0; k < size; ++k)
537             crc += in_buff[k] & 0xff;
538         }
539       disk_buffered_write (in_buff, out_des, size);
540       num_bytes -= size;
541       input_size -= size;
542       in_buff += size;
543     }
544 }
545 \f
546 /* Warn if file changed while it was being copied.  */
547
548 void
549 warn_if_file_changed (char *file_name, unsigned long old_file_size,
550                       unsigned long old_file_mtime)
551 {
552   struct stat new_file_stat;
553   if ((*xstat) (file_name, &new_file_stat) < 0)
554     {
555       error (0, errno, "%s", file_name);
556       return;
557     }
558
559   /* Only check growth, shrinkage detected in copy_files_disk_to_{disk,tape}()
560    */
561   if (new_file_stat.st_size > old_file_size)
562     error (0, 0, _("File %s grew, %ld new bytes not copied"),
563            file_name, (long)(new_file_stat.st_size - old_file_size));
564
565   else if (new_file_stat.st_mtime != old_file_mtime)
566     error (0, 0, _("File %s was modified while being copied"), file_name);
567 }
568 \f
569 /* Create all directories up to but not including the last part of NAME.
570    Do not destroy any nondirectories while creating directories.  */
571
572 void
573 create_all_directories (char *name)
574 {
575   char *dir;
576   int   mode;
577 #ifdef HPUX_CDF
578   int   cdf;
579 #endif
580
581   dir = dir_name (name);
582   mode = 0700;
583 #ifdef HPUX_CDF
584   cdf = islastparentcdf (name);
585   if (cdf)
586     {
587       dir [strlen (dir) - 1] = '\0';    /* remove final + */
588       mode = 04700;
589     }
590   
591 #endif
592   
593   if (dir == NULL)
594     error (2, 0, _("virtual memory exhausted"));
595
596   if (dir[0] != '.' || dir[1] != '\0')
597     make_path (dir, mode, 0700, -1, -1, (char *) NULL);
598
599   free (dir);
600 }
601
602 /* Prepare to append to an archive.  We have been in
603    process_copy_in, keeping track of the position where
604    the last header started in `last_header_start'.  Now we
605    have the starting position of the last header (the TRAILER!!!
606    header, or blank record for tar archives) and we want to start
607    writing (appending) over the last header.  The last header may
608    be in the middle of a block, so to keep the buffering in sync
609    we lseek back to the start of the block, read everything up
610    to but not including the last header, lseek back to the start
611    of the block, and then do a copy_buf_out of what we read.
612    Actually, we probably don't have to worry so much about keeping the
613    buffering perfect since you can only append to archives that
614    are disk files.  */
615
616 void
617 prepare_append (int out_file_des)
618 {
619   int start_of_header;
620   int start_of_block;
621   int useful_bytes_in_block;
622   char *tmp_buf;
623
624   start_of_header = last_header_start;
625   /* Figure out how many bytes we will rewrite, and where they start.  */
626   useful_bytes_in_block = start_of_header % io_block_size;
627   start_of_block = start_of_header - useful_bytes_in_block;
628
629   if (lseek (out_file_des, start_of_block, SEEK_SET) < 0)
630     error (1, errno, _("cannot seek on output"));
631   if (useful_bytes_in_block > 0)
632     {
633       tmp_buf = (char *) xmalloc (useful_bytes_in_block);
634       read (out_file_des, tmp_buf, useful_bytes_in_block);
635       if (lseek (out_file_des, start_of_block, SEEK_SET) < 0)
636         error (1, errno, _("cannot seek on output"));
637       /* fix juo -- is this copy_tape_buf_out?  or copy_disk? */
638       tape_buffered_write (tmp_buf, out_file_des, useful_bytes_in_block);
639       free (tmp_buf);
640     }
641
642   /* We are done reading the archive, so clear these since they
643      will now be used for reading in files that we are appending
644      to the archive.  */
645   input_size = 0;
646   input_bytes = 0;
647   in_buff = input_buffer;
648 }
649
650 /* Support for remembering inodes with multiple links.  Used in the
651    "copy in" and "copy pass" modes for making links instead of copying
652    the file.  */
653
654 struct inode_val
655 {
656   unsigned long inode;
657   unsigned long major_num;
658   unsigned long minor_num;
659   char *file_name;
660 };
661
662 /* Inode hash table.  Allocated by first call to add_inode.  */
663 static struct inode_val **hash_table = NULL;
664
665 /* Size of current hash table.  Initial size is 47.  (47 = 2*22 + 3) */
666 static int hash_size = 22;
667
668 /* Number of elements in current hash table.  */
669 static int hash_num;
670
671 /* Find the file name associated with NODE_NUM.  If there is no file
672    associated with NODE_NUM, return NULL.  */
673
674 char *
675 find_inode_file (unsigned long node_num, unsigned long major_num,
676                  unsigned long minor_num)
677 {
678   int start;                    /* Initial hash location.  */
679   int temp;                     /* Rehash search variable.  */
680
681   if (hash_table != NULL)
682     {
683       /* Hash function is node number modulo the table size.  */
684       start = node_num % hash_size;
685
686       /* Initial look into the table.  */
687       if (hash_table[start] == NULL)
688         return NULL;
689       if (hash_table[start]->inode == node_num
690           && hash_table[start]->major_num == major_num
691           && hash_table[start]->minor_num == minor_num)
692         return hash_table[start]->file_name;
693
694       /* The home position is full with a different inode record.
695          Do a linear search terminated by a NULL pointer.  */
696       for (temp = (start + 1) % hash_size;
697            hash_table[temp] != NULL && temp != start;
698            temp = (temp + 1) % hash_size)
699         {
700           if (hash_table[temp]->inode == node_num
701               && hash_table[start]->major_num == major_num
702               && hash_table[start]->minor_num == minor_num)
703             return hash_table[temp]->file_name;
704         }
705     }
706   return NULL;
707 }
708
709 /* Do the hash insert.  Used in normal inserts and resizing the hash
710    table.  It is guaranteed that there is room to insert the item.
711    NEW_VALUE is the pointer to the previously allocated inode, file
712    name association record.  */
713
714 static void
715 hash_insert (struct inode_val *new_value)
716 {
717   int start;                    /* Home position for the value.  */
718   int temp;                     /* Used for rehashing.  */
719
720   /* Hash function is node number modulo the table size.  */
721   start = new_value->inode % hash_size;
722
723   /* Do the initial look into the table.  */
724   if (hash_table[start] == NULL)
725     {
726       hash_table[start] = new_value;
727       return;
728     }
729
730   /* If we get to here, the home position is full with a different inode
731      record.  Do a linear search for the first NULL pointer and insert
732      the new item there.  */
733   temp = (start + 1) % hash_size;
734   while (hash_table[temp] != NULL)
735     temp = (temp + 1) % hash_size;
736
737   /* Insert at the NULL.  */
738   hash_table[temp] = new_value;
739 }
740
741 /* Associate FILE_NAME with the inode NODE_NUM.  (Insert into hash table.)  */
742
743 void
744 add_inode (unsigned long node_num, char *file_name, unsigned long major_num,
745            unsigned long minor_num)
746 {
747   struct inode_val *temp;
748
749   /* Create new inode record.  */
750   temp = (struct inode_val *) xmalloc (sizeof (struct inode_val));
751   temp->inode = node_num;
752   temp->major_num = major_num;
753   temp->minor_num = minor_num;
754   temp->file_name = xstrdup (file_name);
755
756   /* Do we have to increase the size of (or initially allocate)
757      the hash table?  */
758   if (hash_num == hash_size || hash_table == NULL)
759     {
760       struct inode_val **old_table;     /* Pointer to old table.  */
761       int i;                    /* Index for re-insert loop.  */
762
763       /* Save old table.  */
764       old_table = hash_table;
765       if (old_table == NULL)
766         hash_num = 0;
767
768       /* Calculate new size of table and allocate it.
769          Sequence of table sizes is 47, 97, 197, 397, 797, 1597, 3197, 6397 ...
770          where 3197 and most of the sizes after 6397 are not prime.  The other
771          numbers listed are prime.  */
772       hash_size = 2 * hash_size + 3;
773       hash_table = (struct inode_val **)
774         xmalloc (hash_size * sizeof (struct inode_val *));
775       bzero (hash_table, hash_size * sizeof (struct inode_val *));
776
777       /* Insert the values from the old table into the new table.  */
778       for (i = 0; i < hash_num; i++)
779         hash_insert (old_table[i]);
780
781       if (old_table != NULL)
782         free (old_table);
783     }
784
785   /* Insert the new record and increment the count of elements in the
786       hash table.  */
787   hash_insert (temp);
788   hash_num++;
789 }
790
791 \f
792 /* Open FILE in the mode specified by the command line options
793    and return an open file descriptor for it,
794    or -1 if it can't be opened.  */
795
796 int
797 open_archive (char *file)
798 {
799   int fd;
800   void (*copy_in) ();           /* Workaround for pcc bug.  */
801
802   copy_in = process_copy_in;
803
804   if (copy_function == copy_in)
805     fd = rmtopen (file, O_RDONLY | O_BINARY, 0666, rsh_command_option);
806   else
807     {
808       if (!append_flag)
809         fd = rmtopen (file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666,
810                         rsh_command_option);
811       else
812         fd = rmtopen (file, O_RDWR | O_BINARY, 0666, rsh_command_option);
813     }
814
815   return fd;
816 }
817
818 /* Attempt to rewind the tape drive on file descriptor TAPE_DES
819    and take it offline.  */
820
821 void
822 tape_offline (int tape_des)
823 {
824 #if defined(MTIOCTOP) && defined(MTOFFL)
825   struct mtop control;
826
827   control.mt_op = MTOFFL;
828   control.mt_count = 1;
829   rmtioctl (tape_des, MTIOCTOP, (char*) &control);      /* Don't care if it fails.  */
830 #endif
831 }
832
833 /* The file on file descriptor TAPE_DES is assumed to be magnetic tape
834    (or floppy disk or other device) and the end of the medium
835    has been reached.  Ask the user for to mount a new "tape" to continue
836    the processing.  If the user specified the device name on the
837    command line (with the -I, -O, -F or --file options), then we can
838    automatically re-open the same device to use the next medium.  If the
839    user did not specify the device name, then we have to ask them which
840    device to use.  */
841
842 void
843 get_next_reel (int tape_des)
844 {
845   static int reel_number = 1;
846   FILE *tty_in;                 /* File for interacting with user.  */
847   FILE *tty_out;                /* File for interacting with user.  */
848   int old_tape_des;
849   char *next_archive_name;
850   dynamic_string new_name;
851   char *str_res;
852
853   ds_init (&new_name, 128);
854
855   /* Open files for interactive communication.  */
856   tty_in = fopen (TTY_NAME, "r");
857   if (tty_in == NULL)
858     error (2, errno, TTY_NAME);
859   tty_out = fopen (TTY_NAME, "w");
860   if (tty_out == NULL)
861     error (2, errno, TTY_NAME);
862
863   old_tape_des = tape_des;
864   tape_offline (tape_des);
865   rmtclose (tape_des);
866
867   /* Give message and wait for carrage return.  User should hit carrage return
868      only after loading the next tape.  */
869   ++reel_number;
870   if (new_media_message)
871     fprintf (tty_out, "%s", new_media_message);
872   else if (new_media_message_with_number)
873     fprintf (tty_out, "%s%d%s", new_media_message_with_number, reel_number,
874              new_media_message_after_number);
875   else if (archive_name)
876     fprintf (tty_out, _("Found end of volume.  Load next volume and press RETURN. "));
877   else
878     fprintf (tty_out, _("Found end of volume.  To continue, type device/file name when ready.\n"));
879
880   fflush (tty_out);
881
882   if (archive_name)
883     {
884       int c;
885
886       do
887         c = getc (tty_in);
888       while (c != EOF && c != '\n');
889
890       tape_des = open_archive (archive_name);
891       if (tape_des == -1)
892         error (1, errno, "%s", archive_name);
893     }
894   else
895     {
896       do
897         {
898           if (tape_des < 0)
899             {
900               fprintf (tty_out,
901                        _("To continue, type device/file name when ready.\n"));
902               fflush (tty_out);
903             }
904
905           str_res = ds_fgets (tty_in, &new_name);
906           if (str_res == NULL || str_res[0] == '\0')
907             exit (1);
908           next_archive_name = str_res;
909
910           tape_des = open_archive (next_archive_name);
911           if (tape_des == -1)
912             error (0, errno, "%s", next_archive_name);
913         }
914       while (tape_des < 0);
915     }
916
917   /* We have to make sure that `tape_des' has not changed its value even
918      though we closed it and reopened it, since there are local
919      copies of it in other routines.  This works fine on Unix (even with
920      rmtread and rmtwrite) since open will always return the lowest
921      available file descriptor and we haven't closed any files (e.g.,
922      stdin, stdout or stderr) that were opened before we originally opened
923      the archive.  */
924
925   if (tape_des != old_tape_des)
926     error (1, 0, _("internal error: tape descriptor changed from %d to %d"),
927            old_tape_des, tape_des);
928
929   free (new_name.ds_string);
930   fclose (tty_in);
931   fclose (tty_out);
932 }
933
934 /* If MESSAGE does not contain the string "%d", make `new_media_message'
935    a copy of MESSAGE.  If MESSAGES does contain the string "%d", make
936    `new_media_message_with_number' a copy of MESSAGE up to, but
937    not including, the string "%d", and make `new_media_message_after_number'
938    a copy of MESSAGE after the string "%d".  */
939
940 void
941 set_new_media_message (char *message)
942 {
943   char *p;
944   int prev_was_percent;
945
946   p = message;
947   prev_was_percent = 0;
948   while (*p != '\0')
949     {
950       if (*p == 'd' && prev_was_percent)
951         break;
952       prev_was_percent = (*p == '%');
953       ++p;
954     }
955   if (*p == '\0')
956     {
957       new_media_message = xstrdup (message);
958     }
959   else
960     {
961       int length = p - message - 1;
962
963       new_media_message_with_number = xmalloc (length + 1);
964       strncpy (new_media_message_with_number, message, length);
965       new_media_message_with_number[length] = '\0';
966       length = strlen (p + 1);
967       new_media_message_after_number = xmalloc (length + 1);
968       strcpy (new_media_message_after_number, p + 1);
969     }
970 }
971
972 #ifdef SYMLINK_USES_UMASK
973 /* Most machines always create symlinks with rwxrwxrwx protection,
974    but some (HP/UX 8.07; maybe DEC's OSF on MIPS, too?) use the
975    umask when creating symlinks, so if your umask is 022 you end
976    up with rwxr-xr-x symlinks (although HP/UX seems to completely
977    ignore the protection).  There doesn't seem to be any way to
978    manipulate the modes once the symlinks are created (e.g.
979    a hypothetical "lchmod"), so to create them with the right
980    modes we have to set the umask first.  */
981
982 int
983 umasked_symlink (char *name1, char *name2, int mode)
984 {
985   int   old_umask;
986   int   rc;
987   mode = ~(mode & 0777) & 0777;
988   old_umask = umask (mode);
989   rc = symlink (name1, name2);
990   umask (old_umask);
991   return rc;
992 }
993 #endif /* SYMLINK_USES_UMASK */
994
995 #ifdef HPUX_CDF
996 /* When we create a cpio archive we mark CDF's by putting an extra `/'
997    after their component name so we can distinguish the CDF's when we
998    extract the archive (in case the "hidden" directory's files appear
999    in the archive before the directory itself).  E.g., in the path
1000    "a/b+/c", if b+ is a CDF, we will write this path as "a/b+//c" in
1001    the archive so when we extract the archive we will know that b+
1002    is actually a CDF, and not an ordinary directory whose name happens
1003    to end in `+'.  We also do the same thing internally in copypass.c.  */
1004
1005
1006 /* Take an input pathname and check it for CDF's.  Insert an extra
1007    `/' in the pathname after each "hidden" directory.  If we add
1008    any `/'s, return a malloced string (which it will reuse for
1009    later calls so our caller doesn't have to worry about freeing
1010    the string) instead of the original input string.  */
1011
1012 char *
1013 add_cdf_double_slashes (char *input_name)
1014 {
1015   static char *ret_name = NULL; /* re-usuable return buffer (malloc'ed)  */
1016   static int ret_size = -1;     /* size of return buffer.  */
1017   char *p;
1018   char *q;
1019   int n;
1020   struct stat dir_stat;
1021
1022   /*  Search for a `/' preceeded by a `+'.  */
1023
1024   for (p = input_name; *p != '\0'; ++p)
1025     {
1026       if ( (*p == '+') && (*(p + 1) == '/') )
1027         break;
1028     }
1029
1030   /* If we didn't find a `/' preceeded by a `+' then there are
1031      no CDF's in this pathname.  Return the original pathname.  */
1032
1033   if (*p == '\0')
1034     return input_name;
1035
1036   /* There was a `/' preceeded by a `+' in the pathname.  If it is a CDF 
1037      then we will need to copy the input pathname to our return
1038      buffer so we can insert the extra `/'s.  Since we can't tell
1039      yet whether or not it is a CDF we will just always copy the
1040      string to the return buffer.  First we have to make sure the
1041      buffer is large enough to hold the string and any number of
1042      extra `/'s we might add.  */
1043
1044   n = 2 * (strlen (input_name) + 1);
1045   if (n >= ret_size)
1046     {
1047       if (ret_size < 0)
1048         ret_name = (char *) malloc (n);
1049       else
1050         ret_name = (char *)realloc (ret_name, n);
1051       ret_size = n;
1052     }
1053
1054   /* Clear the `/' after this component, so we can stat the pathname 
1055      up to and including this component.  */
1056   ++p;
1057   *p = '\0';
1058   if ((*xstat) (input_name, &dir_stat) < 0)
1059     {
1060       error (0, errno, "%s", input_name);
1061       return input_name;
1062     }
1063
1064   /* Now put back the `/' after this component and copy the pathname up to
1065      and including this component and its trailing `/' to the return
1066      buffer.  */
1067   *p++ = '/';
1068   strncpy (ret_name, input_name, p - input_name);
1069   q = ret_name + (p - input_name);
1070
1071   /* If it was a CDF, add another `/'.  */
1072   if (S_ISDIR (dir_stat.st_mode) && (dir_stat.st_mode & 04000) )
1073     *q++ = '/';
1074
1075   /* Go through the rest of the input pathname, copying it to the
1076      return buffer, and adding an extra `/' after each CDF.  */
1077   while (*p != '\0')
1078     {
1079       if ( (*p == '+') && (*(p + 1) == '/') )
1080         {
1081           *q++ = *p++;
1082
1083           *p = '\0';
1084           if ((*xstat) (input_name, &dir_stat) < 0)
1085             {
1086               error (0, errno, "%s", input_name);
1087               return input_name;
1088             }
1089           *p = '/';
1090
1091           if (S_ISDIR (dir_stat.st_mode) && (dir_stat.st_mode & 04000) )
1092             *q++ = '/';
1093         }
1094       *q++ = *p++;
1095     }
1096   *q = '\0';
1097
1098   return ret_name;
1099 }
1100
1101 /* Is the last parent directory (e.g., c in a/b/c/d) a CDF?  If the
1102    directory name ends in `+' and is followed by 2 `/'s instead of 1
1103    then it is.  This is only the case for cpio archives, but we don't
1104    have to worry about tar because tar always has the directory before
1105    its files (or else we lose).  */
1106 int
1107 islastparentcdf (char *path)
1108 {
1109   char *newpath;
1110   char *slash;
1111   int slash_count;
1112   int length;                   /* Length of result, not including NUL.  */
1113
1114   slash = rindex (path, '/');
1115   if (slash == 0)
1116     return 0;
1117   else
1118     {
1119       slash_count = 0;
1120       while (slash > path && *slash == '/')
1121         {
1122           ++slash_count;
1123           --slash;
1124         }
1125
1126
1127       if ( (*slash == '+') && (slash_count >= 2) )
1128         return 1;
1129     }
1130   return 0;
1131 }
1132 #endif
1133
1134 #define DISKBLOCKSIZE   (512)
1135
1136 enum sparse_write_states { begin, in_zeros, not_in_zeros };
1137
1138
1139 static int
1140 buf_all_zeros (char *buf, int bufsize)
1141 {
1142   int   i;
1143   for (i = 0; i < bufsize; ++i)
1144     {
1145       if (*buf++ != '\0')
1146         return 0;
1147     }
1148   return 1;
1149 }
1150
1151 int delayed_seek_count = 0;
1152
1153 /* Write NBYTE bytes from BUF to remote tape connection FILDES.
1154    Return the number of bytes written on success, -1 on error.  */
1155
1156 int
1157 sparse_write (int fildes, char *buf, unsigned int nbyte)
1158 {
1159   int complete_block_count;
1160   int leftover_bytes_count;
1161   int seek_count;
1162   int write_count;
1163   char *cur_write_start;
1164   int lseek_rc;
1165   int write_rc;
1166   int i;
1167   enum sparse_write_states state;
1168
1169   complete_block_count = nbyte / DISKBLOCKSIZE;
1170   leftover_bytes_count = nbyte % DISKBLOCKSIZE;
1171
1172   if (delayed_seek_count != 0)
1173     state = in_zeros;
1174   else
1175     state = begin;
1176
1177   seek_count = delayed_seek_count;
1178
1179   for (i = 0; i < complete_block_count; ++i)
1180     {
1181       switch (state)
1182         {
1183           case begin :
1184             if (buf_all_zeros (buf, DISKBLOCKSIZE))
1185               {
1186                 seek_count = DISKBLOCKSIZE;
1187                 state = in_zeros;
1188               }
1189             else
1190               {
1191                 cur_write_start = buf;
1192                 write_count = DISKBLOCKSIZE;
1193                 state = not_in_zeros;
1194               }
1195             buf += DISKBLOCKSIZE;
1196             break;
1197           case in_zeros :
1198             if (buf_all_zeros (buf, DISKBLOCKSIZE))
1199               {
1200                 seek_count += DISKBLOCKSIZE;
1201               }
1202             else
1203               {
1204                 lseek (fildes, seek_count, SEEK_CUR);
1205                 cur_write_start = buf;
1206                 write_count = DISKBLOCKSIZE;
1207                 state = not_in_zeros;
1208               }
1209             buf += DISKBLOCKSIZE;
1210             break;
1211           case not_in_zeros :
1212             if (buf_all_zeros (buf, DISKBLOCKSIZE))
1213               {
1214                 write_rc = write (fildes, cur_write_start, write_count);
1215                 seek_count = DISKBLOCKSIZE;
1216                 state = in_zeros;
1217               }
1218             else
1219               {
1220                 write_count += DISKBLOCKSIZE;
1221               }
1222             buf += DISKBLOCKSIZE;
1223             break;
1224         }
1225     }
1226
1227   switch (state)
1228     {
1229       case begin :
1230       case in_zeros :
1231         delayed_seek_count = seek_count;
1232         break;
1233       case not_in_zeros :
1234         write_rc = write (fildes, cur_write_start, write_count);
1235         delayed_seek_count = 0;
1236         break;
1237     }
1238
1239   if (leftover_bytes_count != 0)
1240     {
1241       if (delayed_seek_count != 0)
1242         {
1243           lseek_rc = lseek (fildes, delayed_seek_count, SEEK_CUR);
1244           delayed_seek_count = 0;
1245         }
1246       write_rc = write (fildes, buf, leftover_bytes_count);
1247     }
1248   return nbyte;
1249 }