home *** CD-ROM | disk | FTP | other *** search
/ Mega Demo / MegaDemoCDRom1.cdr / os2 / archive / gtar109.exe / BUFFER.C next >
C/C++ Source or Header  |  1991-01-14  |  31KB  |  1,337 lines

  1. /* Buffer management for tar.
  2.    Copyright (C) 1988 Free Software Foundation
  3.  
  4. This file is part of GNU Tar.
  5.  
  6. GNU Tar 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 1, or (at your option)
  9. any later version.
  10.  
  11. GNU Tar 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
  17. along with GNU Tar; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /*
  21.  * Buffer management for tar.
  22.  *
  23.  * Written by John Gilmore, ihnp4!hoptoad!gnu, on 25 August 1985.
  24.  *
  25.  * @(#) buffer.c 1.28 11/6/87 - gnu
  26.  */
  27.  
  28. #include <stdio.h>
  29. #include <errno.h>
  30. #include <sys/types.h>        /* For non-Berkeley systems */
  31. #include <sys/stat.h>
  32. #include <signal.h>
  33.  
  34. #ifdef MSDOS
  35. #include <io.h>
  36. #else
  37. #include <sys/ioctl.h>
  38. #if !defined(USG) || defined(HAVE_MTIO)
  39. #include <sys/mtio.h>
  40. #endif
  41. #endif
  42.  
  43. #ifdef    MSDOS
  44. # include <fcntl.h>
  45. #include <process.h>
  46. #else
  47. # ifdef XENIX
  48. #  include <sys/inode.h>
  49. # endif
  50. # include <sys/file.h>
  51. #endif
  52.  
  53. #ifndef MSDOS
  54. extern int errno;
  55. #endif
  56.  
  57. #include "tar.h"
  58. #include "port.h"
  59. #include "rmt.h"
  60.  
  61. /* Either stdout or stderr:  The thing we write messages (standard msgs, not
  62.    errors) to.  Stdout unless we're writing a pipe, in which case stderr */
  63. FILE *msg_file = stdout;
  64.  
  65. #define    STDIN    0        /* Standard input  file descriptor */
  66. #define    STDOUT    1        /* Standard output file descriptor */
  67.  
  68. #define    PREAD    0        /* Read  file descriptor from pipe() */
  69. #define    PWRITE    1        /* Write file descriptor from pipe() */
  70.  
  71. #ifdef __STDC__
  72. extern void    *malloc();
  73. extern void    *valloc();
  74. #else
  75. extern char    *malloc();
  76. extern char    *valloc();
  77. #endif
  78. extern time_t time();
  79.  
  80. extern char    *index(), *strcat();
  81. extern char    *strcpy();
  82.  
  83. /*
  84.  * V7 doesn't have a #define for this.
  85.  */
  86. #ifndef O_RDONLY
  87. #define    O_RDONLY    0
  88. #endif
  89. #ifndef O_RDWR
  90. #define O_RDWR        2
  91. #endif
  92. #ifndef O_CREAT
  93. #define O_CREAT        0
  94. #endif
  95. #ifndef O_BINARY
  96. #define O_BINARY    0
  97. #endif
  98.  
  99. #define    MAGIC_STAT    105    /* Magic status returned by child, if
  100.                    it can't exec.  We hope compress/sh
  101.                    never return this status! */
  102.  
  103. void writeerror();
  104. void readerror();
  105.  
  106. void ck_pipe();
  107. void ck_close();
  108.  
  109. extern void finish_header();
  110. extern void to_oct();
  111.  
  112. /* Obnoxious test to see if dimwit is trying to dump the archive */
  113. dev_t ar_dev;
  114. ino_t ar_ino;
  115.  
  116. /*
  117.  * The record pointed to by save_rec should not be overlaid
  118.  * when reading in a new tape block.  Copy it to record_save_area first, and
  119.  * change the pointer in *save_rec to point to record_save_area.
  120.  * Saved_recno records the record number at the time of the save.
  121.  * This is used by annofile() to print the record number of a file's
  122.  * header record.
  123.  */
  124. static union record **save_rec;
  125.  union record record_save_area;
  126. static long        saved_recno;
  127.  
  128. /*
  129.  * PID of child program, if f_compress or remote archive access.
  130.  */
  131. static int    childpid = 0;
  132.  
  133. /*
  134.  * Record number of the start of this block of records
  135.  */
  136. long    baserec;
  137.  
  138. /*
  139.  * Error recovery stuff
  140.  */
  141. static int    r_error_count;
  142.  
  143. /*
  144.  * Have we hit EOF yet?
  145.  */
  146. static int      _eof;
  147.  
  148. /* JF we're reading, but we just read the last record and its time to update */
  149. extern time_to_start_writing;
  150. int file_to_switch_to= -1;    /* If remote update, close archive, and use
  151.                    this descriptor to write to */
  152.  
  153. static int volno = 1;        /* JF which volume of a multi-volume tape
  154.                    we're on */
  155.  
  156. char *save_name = 0;        /* Name of the file we are currently writing */
  157. long save_totsize;        /* total size of file we are writing.  Only
  158.                    valid if save_name is non_zero */
  159. long save_sizeleft;        /* Where we are in the file we are writing.
  160.                    Only valid if save_name is non-zero */
  161.  
  162. int write_archive_to_stdout;
  163.  
  164. /* Used by fl_read and fl_write to store the real info about saved names */
  165. static char real_s_name[NAMSIZ];
  166. static long real_s_totsize;
  167. static long real_s_sizeleft;
  168.  
  169. /* Reset the EOF flag (if set), and re-set ar_record, etc */
  170.  
  171. void
  172. reset_eof()
  173. {
  174.     if(_eof) {
  175.         _eof=0;
  176.         ar_record=ar_block;
  177.         ar_last=ar_block+blocking;
  178.         ar_reading=0;
  179.     }
  180. }
  181.  
  182. /*
  183.  * Return the location of the next available input or output record.
  184.  * Return NULL for EOF.  Once we have returned NULL, we just keep returning
  185.  * it, to avoid accidentally going on to the next file on the "tape".
  186.  */
  187. union record *
  188. findrec()
  189. {
  190.     if (ar_record == ar_last) {
  191.                 if (_eof)
  192.             return (union record *)NULL;    /* EOF */
  193.         flush_archive();
  194.         if (ar_record == ar_last) {
  195.                         _eof++;
  196.             return (union record *)NULL;    /* EOF */
  197.         }
  198.     }
  199.     return ar_record;
  200. }
  201.  
  202.  
  203. /*
  204.  * Indicate that we have used all records up thru the argument.
  205.  * (should the arg have an off-by-1? XXX FIXME)
  206.  */
  207. void
  208. userec(rec)
  209.     union record *rec;
  210. {
  211.     while(rec >= ar_record)
  212.         ar_record++;
  213.     /*
  214.      * Do NOT flush the archive here.  If we do, the same
  215.      * argument to userec() could mean the next record (if the
  216.      * input block is exactly one record long), which is not what
  217.      * is intended.
  218.      */
  219.     if (ar_record > ar_last)
  220.         abort();
  221. }
  222.  
  223.  
  224. /*
  225.  * Return a pointer to the end of the current records buffer.
  226.  * All the space between findrec() and endofrecs() is available
  227.  * for filling with data, or taking data from.
  228.  */
  229. union record *
  230. endofrecs()
  231. {
  232.     return ar_last;
  233. }
  234.  
  235.  
  236. /*
  237.  * Duplicate a file descriptor into a certain slot.
  238.  * Equivalent to BSD "dup2" with error reporting.
  239.  */
  240. void
  241. dupto(from, to, msg)
  242.     int from, to;
  243.     char *msg;
  244. {
  245.     int err;
  246.  
  247.     if (from != to) {
  248.         err=close(to);
  249.         if(err<0 && errno!=EBADF) {
  250.             msg_perror("Cannot close descriptor %d",to);
  251.             exit(EX_SYSTEM);
  252.         }
  253.         err = dup(from);
  254.         if (err != to) {
  255.             msg_perror("cannot dup %s",msg);
  256.             exit(EX_SYSTEM);
  257.         }
  258.         ck_close(from);
  259.     }
  260. }
  261.  
  262. #ifdef MSDOS
  263. void
  264. child_open()
  265. {
  266.     fprintf(stderr,"MSDOS %s can't use compressed or remote archives\n",tar);
  267.     exit(EX_ARGSBAD);
  268. }
  269. #else
  270. void
  271. child_open()
  272. {
  273.     int pipe[2];
  274.     int err = 0;
  275.  
  276.     int kidpipe[2];
  277.     int kidchildpid;
  278.  
  279. #define READ    0
  280. #define WRITE    1
  281.  
  282.     ck_pipe(pipe);
  283.  
  284.     childpid=fork();
  285.     if(childpid<0) {
  286.         msg_perror("cannot fork");
  287.         exit(EX_SYSTEM);
  288.     }
  289.     if(childpid>0) {
  290.         /* We're the parent.  Clean up and be happy */
  291.         /* This, at least, is easy */
  292.  
  293.         if(ar_reading) {
  294.             f_reblock++;
  295.             archive=pipe[READ];
  296.             ck_close(pipe[WRITE]);
  297.         } else {
  298.             archive = pipe[WRITE];
  299.             ck_close(pipe[READ]);
  300.         }
  301.         return;
  302.     }
  303.  
  304.     /* We're the kid */
  305.     if(ar_reading) {
  306.         dupto(pipe[WRITE],STDOUT,"(child) pipe to stdout");
  307.         ck_close(pipe[READ]);
  308.     } else {
  309.         dupto(pipe[READ],STDIN,"(child) pipe to stdin");
  310.         ck_close(pipe[WRITE]);
  311.     }
  312.  
  313.     /* We need a child tar only if
  314.        1: we're reading/writing stdin/out (to force reblocking)
  315.        2: the file is to be accessed by rmt (compress doesn't know how)
  316.        3: the file is not a plain file */
  317. #ifdef NO_REMOTE
  318.     if(!(ar_file[0]=='-' && ar_file[1]=='\0') && isfile(ar_file))
  319. #else
  320.     if(!(ar_file[0]=='-' && ar_file[1]=='\0') && !_remdev(ar_file) && isfile(ar_file))
  321. #endif
  322.     {
  323.         /* We don't need a child tar.  Open the archive */
  324.         if(ar_reading) {
  325.             archive=open(ar_file, O_RDONLY|O_BINARY, 0666);
  326.             if(archive<0) {
  327.                 msg_perror("can't open archive %s",ar_file);
  328.                 exit(EX_BADARCH);
  329.             }
  330.             dupto(archive,STDIN,"archive to stdin");
  331.             /* close(archive); */
  332.         } else {
  333.             archive=creat(ar_file,0666);
  334.             if(archive<0) {
  335.                 msg_perror("can't open archive %s",ar_file);
  336.                 exit(EX_BADARCH);
  337.             }
  338.             dupto(archive,STDOUT,"archive to stdout");
  339.             /* close(archive); */
  340.         }
  341.     } else {
  342.         /* We need a child tar */
  343.         ck_pipe(kidpipe);
  344.  
  345.         kidchildpid=fork();
  346.         if(kidchildpid<0) {
  347.             msg_perror("child can't fork");
  348.             exit(EX_SYSTEM);
  349.         }
  350.  
  351.         if(kidchildpid>0) {
  352.             /* About to exec compress:  set up the files */
  353.             if(ar_reading) {
  354.                 dupto(kidpipe[READ],STDIN,"((child)) pipe to stdin");
  355.                 ck_close(kidpipe[WRITE]);
  356.                 /* dup2(pipe[WRITE],STDOUT); */
  357.             } else {
  358.                 /* dup2(pipe[READ],STDIN); */
  359.                 dupto(kidpipe[WRITE],STDOUT,"((child)) pipe to stdout");
  360.                 ck_close(kidpipe[READ]);
  361.             }
  362.             /* ck_close(pipe[READ]); */
  363.             /* ck_close(pipe[WRITE]); */
  364.             /* ck_close(kidpipe[READ]);
  365.             ck_close(kidpipe[WRITE]); */
  366.         } else {
  367.         /* Grandchild.  Do the right thing, namely sit here and
  368.            read/write the archive, and feed stuff back to compress */
  369.             tar="tar (child)";
  370.             if(ar_reading) {
  371.                 dupto(kidpipe[WRITE],STDOUT,"[child] pipe to stdout");
  372.                 ck_close(kidpipe[READ]);
  373.             } else {
  374.                 dupto(kidpipe[READ],STDIN,"[child] pipe to stdin");
  375.                 ck_close(kidpipe[WRITE]);
  376.             }
  377.  
  378.             if (ar_file[0] == '-' && ar_file[1] == '\0') {
  379.                 if (ar_reading)
  380.                     archive = STDIN;
  381.                 else
  382.                     archive = STDOUT;
  383.             } else /* This can't happen if (ar_reading==2)
  384.                 archive = rmtopen(ar_file, O_RDWR|O_CREAT|O_BINARY, 0666);
  385.             else */if(ar_reading)
  386.                 archive = rmtopen(ar_file, O_RDONLY|O_BINARY, 0666);
  387.             else
  388.                 archive = rmtcreat(ar_file, 0666);
  389.  
  390.             if (archive < 0) {
  391.                 msg_perror("can't open archive %s",ar_file);
  392.                 exit(EX_BADARCH);
  393.             }
  394.  
  395.             if(ar_reading) {
  396.                 for(;;) {
  397.                     char *ptr;
  398.                     int max,count;
  399.  
  400.                     r_error_count = 0;
  401.                 error_loop:
  402.                     err=rmtread(archive, ar_block->charptr,(int)(blocksize));
  403.                     if(err<0) {
  404.                         readerror();
  405.                         goto error_loop;
  406.                     }
  407.                     if(err==0)
  408.                         break;
  409.                     ptr = ar_block->charptr;
  410.                     max = err;
  411.                     while(max) {
  412.                         count = (max<RECORDSIZE) ? max : RECORDSIZE;
  413.                         err=write(STDOUT,ptr,count);
  414.                         if(err!=count) {
  415.                             if(err<0) {
  416.                                 msg_perror("can't write to compress");
  417.                                 exit(EX_SYSTEM);
  418.                             } else
  419.                                 msg("write to compress short %d bytes",count-err);
  420.                             count = (err<0) ? 0 : err;
  421.                         }
  422.                         ptr+=count;
  423.                         max-=count;
  424.                     }
  425.                 }
  426.             } else {
  427.                 for(;;) {
  428.                     int n;
  429.                     char *ptr;
  430.  
  431.                     n=blocksize;
  432.                     ptr = ar_block->charptr;
  433.                     while(n) {
  434.                         err=read(STDIN,ptr,(n<RECORDSIZE) ? n : RECORDSIZE);
  435.                         if(err<=0)
  436.                             break;
  437.                         n-=err;
  438.                         ptr+=err;
  439.                     }
  440.                         /* EOF */
  441.                     if(err==0) {
  442.                         if(f_compress<2)
  443.                             blocksize-=n;
  444.                         else
  445.                             bzero(ar_block->charptr+n,blocksize-n,n);
  446.                         err=rmtwrite(archive,ar_block->charptr,blocksize);
  447.                         if(err!=(blocksize))
  448.                             writeerror(err);
  449.                         if(f_compress<2)
  450.                             blocksize+=n;
  451.                         break;
  452.                     }
  453.                     if(n) {
  454.                         msg_perror("can't read from compress");
  455.                         exit(EX_SYSTEM);
  456.                     }
  457.                     err=rmtwrite(archive, ar_block->charptr, (int)blocksize);
  458.                     if(err!=blocksize)
  459.                         writeerror(err);
  460.                 }
  461.             }
  462.  
  463.             /* close_archive(); */
  464.             exit(0);
  465.         }
  466.     }
  467.         /* So we should exec compress (-d) */
  468.     if(ar_reading)
  469.         execlp("compress", "compress", "-d", (char *)0);
  470.     else
  471.         execlp("compress", "compress", (char *)0);
  472.     msg_perror("can't exec compress");
  473.     _exit(EX_SYSTEM);
  474. }
  475.  
  476.  
  477. /* return non-zero if p is the name of a directory */
  478. isfile(p)
  479. char *p;
  480. {
  481.     struct stat stbuf;
  482.  
  483.     if(stat(p,&stbuf)<0)
  484.         return 1;
  485.     if((stbuf.st_mode&S_IFMT)==S_IFREG)
  486.         return 1;
  487.     return 0;
  488. }
  489.  
  490. #endif
  491.  
  492. /*
  493.  * Open an archive file.  The argument specifies whether we are
  494.  * reading or writing.
  495.  */
  496. /* JF if the arg is 2, open for reading and writing. */
  497. open_archive(reading)
  498.     int reading;
  499. {
  500.     msg_file = f_exstdout ? stderr : stdout;
  501.  
  502.     if (blocksize == 0) {
  503.         msg("invalid value for blocksize");
  504.         exit(EX_ARGSBAD);
  505.     }
  506.  
  507.     if(ar_file==0) {
  508.         msg("No archive name given, what should I do?");
  509.         exit(EX_BADARCH);
  510.     }
  511.  
  512.     /*NOSTRICT*/
  513.     if(f_multivol) {
  514.         ar_block = (union record *) valloc((unsigned)(blocksize+(2*RECORDSIZE)));
  515.         if(ar_block)
  516.             ar_block += 2;
  517.     } else
  518.         ar_block = (union record *) valloc((unsigned)blocksize);
  519.     if (!ar_block) {
  520.         msg("could not allocate memory for blocking factor %d",
  521.             blocking);
  522.         exit(EX_ARGSBAD);
  523.     }
  524.  
  525.     ar_record = ar_block;
  526.     ar_last   = ar_block + blocking;
  527.     ar_reading = reading;
  528.  
  529.     if (f_compress) {
  530.         if(reading==2 || f_verify) {
  531.             msg("cannot update or verify compressed archives");
  532.             exit(EX_ARGSBAD);
  533.         }
  534.         child_open();
  535.         if(!reading && ar_file[0]=='-' && ar_file[1]=='\0')
  536.             msg_file = stderr;
  537.         /* child_open(rem_host, rem_file); */
  538.     } else if (ar_file[0] == '-' && ar_file[1] == '\0') {
  539.         f_reblock++;    /* Could be a pipe, be safe */
  540.         if(f_verify) {
  541.             msg("can't verify stdin/stdout archive");
  542.             exit(EX_ARGSBAD);
  543.         }
  544.         if(reading==2) {
  545.             archive=STDIN;
  546.             msg_file=stderr;
  547.             write_archive_to_stdout++;
  548.         } else if (reading)
  549.             archive = STDIN;
  550.         else {
  551.             archive = STDOUT;
  552.             msg_file = stderr;
  553.         }
  554.     } else if (reading==2 || f_verify) {
  555.         archive = rmtopen(ar_file, O_RDWR|O_CREAT|O_BINARY, 0666);
  556.     } else if(reading) {
  557.         archive = rmtopen(ar_file, O_RDONLY|O_BINARY, 0666);
  558.     } else {
  559.         archive = rmtcreat(ar_file, 0666);
  560.     }
  561.     if(!_isrmt(archive)) {
  562.         struct stat tmp_stat;
  563.  
  564.         fstat(archive,&tmp_stat);
  565.         if((tmp_stat.st_mode&S_IFMT)==S_IFREG) {
  566.             ar_dev=tmp_stat.st_dev;
  567.             ar_ino=tmp_stat.st_ino;
  568.         }
  569.     }
  570.  
  571.     if (archive < 0) {
  572.         msg_perror("can't open %s",ar_file);
  573.         exit(EX_BADARCH);
  574.     }
  575. #ifdef    MSDOS
  576.     setmode(archive, O_BINARY);
  577. #endif
  578.  
  579.     if (reading) {
  580.         ar_last = ar_block;        /* Set up for 1st block = # 0 */
  581.         (void) findrec();        /* Read it in, check for EOF */
  582.  
  583.         if(f_volhdr) {
  584.             union record *head;
  585.             char *ptr;
  586.  
  587.             if(f_multivol) {
  588.                 ptr=malloc(strlen(f_volhdr)+20);
  589.                 sprintf(ptr,"%s Volume %d",f_volhdr,1);
  590.             } else
  591.                 ptr=f_volhdr;
  592.             head=findrec();
  593.             if(!head)
  594.                 exit(EX_BADARCH);
  595.             if(strcmp(ptr,head->header.name)) {
  596.                 msg("Volume mismatch!  %s!=%s\n",ptr,head->header.name);
  597.                 exit(EX_BADARCH);
  598.             }
  599.             if(ptr!=f_volhdr)
  600.                 free(ptr);
  601.         }
  602.     } else if(f_volhdr) {
  603.         bzero((void *)ar_block,RECORDSIZE);
  604.         if(f_multivol)
  605.             sprintf(ar_block->header.name,"%s Volume 1",f_volhdr);
  606.         else
  607.             strcpy(ar_block->header.name,f_volhdr);
  608.         ar_block->header.linkflag = LF_VOLHDR;
  609.         to_oct(time(0),    1+12, ar_block->header.mtime);
  610.         finish_header(ar_block);
  611.         /* ar_record++; */
  612.     }
  613. }
  614.  
  615.  
  616. /*
  617.  * Remember a union record * as pointing to something that we
  618.  * need to keep when reading onward in the file.  Only one such
  619.  * thing can be remembered at once, and it only works when reading
  620.  * an archive.
  621.  *
  622.  * We calculate "offset" then add it because some compilers end up
  623.  * adding (baserec+ar_record), doing a 9-bit shift of baserec, then
  624.  * subtracting ar_block from that, shifting it back, losing the top 9 bits.
  625.  */
  626. saverec(pointer)
  627.     union record **pointer;
  628. {
  629.     long offset;
  630.  
  631.     save_rec = pointer;
  632.     offset = ar_record - ar_block;
  633.     saved_recno = baserec + offset;
  634. }
  635.  
  636. /*
  637.  * Perform a write to flush the buffer.
  638.  */
  639.  
  640. /*send_buffer_to_file();
  641.   if(new_volume) {
  642.       deal_with_new_volume_stuff();
  643.     send_buffer_to_file();
  644.   }
  645.  */
  646.  
  647. fl_write()
  648. {
  649.     int err;
  650.     int copy_back;
  651. #ifdef TEST
  652.     static long test_written = 0;
  653. #endif
  654.  
  655. #ifdef TEST
  656.     if(test_written>=30720) {
  657.         errno = ENOSPC;
  658.         err = 0;
  659.     } else
  660. #endif
  661.     err = rmtwrite(archive, ar_block->charptr,(int) blocksize);
  662.     if(err!=blocksize && !f_multivol)
  663.         writeerror(err);
  664.  
  665. #ifdef TEST
  666.     if(err>0)
  667.         test_written+=err;
  668. #endif
  669.     if (err == blocksize) {
  670.         if(f_multivol) {
  671.             if(!save_name) {
  672.                 real_s_name[0]='\0';
  673.                 real_s_totsize=0;
  674.                 real_s_sizeleft = 0;
  675.                 return;
  676.             }
  677. #ifdef MSDOS
  678.             if(save_name[1]==':')
  679.                 save_name+=2;
  680. #endif
  681.             while(*save_name=='/')
  682.                 save_name++;
  683.  
  684.             strcpy(real_s_name,save_name);
  685.             real_s_totsize = save_totsize;
  686.             real_s_sizeleft = save_sizeleft;
  687.         }
  688.         return;
  689.     }
  690.  
  691.     /* We're multivol  Panic if we didn't get the right kind of response */
  692.     /* ENXIO is for the UNIX PC */
  693.     if(err>0 || (err<0 && errno!=ENOSPC && errno!=EIO && errno!=ENXIO))
  694.         writeerror(err);
  695.  
  696.     if(new_volume(0)<0)
  697.         return;
  698. #ifdef TEST
  699.     test_written=0;
  700. #endif
  701.     if(f_volhdr && real_s_name[0]) {
  702.         copy_back=2;
  703.         ar_block-=2;
  704.     } else if(f_volhdr || real_s_name[0]) {
  705.         copy_back = 1;
  706.         ar_block--;
  707.     } else
  708.         copy_back = 0;
  709.     if(f_volhdr) {
  710.         bzero((void *)ar_block,RECORDSIZE);
  711.         sprintf(ar_block->header.name,"%s Volume %d",f_volhdr,volno);
  712.         to_oct(time(0),    1+12, ar_block->header.mtime);
  713.         ar_block->header.linkflag = LF_VOLHDR;
  714.         finish_header(ar_block);
  715.     }
  716.     if(real_s_name[0]) {
  717.         int tmp;
  718.  
  719.         if(f_volhdr)
  720.             ar_block++;
  721.         bzero((void *)ar_block,RECORDSIZE);
  722.         strcpy(ar_block->header.name,real_s_name);
  723.         ar_block->header.linkflag = LF_MULTIVOL;
  724.         to_oct((long)real_s_sizeleft,1+12,
  725.                ar_block->header.size);
  726.         to_oct((long)real_s_totsize-real_s_sizeleft,
  727.                1+12,ar_block->header.offset);
  728.         tmp=f_verbose;
  729.         f_verbose=0;
  730.         finish_header(ar_block);
  731.         f_verbose=tmp;
  732.         if(f_volhdr)
  733.             ar_block--;
  734.     }
  735.  
  736.     err = rmtwrite(archive, ar_block->charptr,(int) blocksize);
  737.     if(err!=blocksize)
  738.         writeerror(err);
  739.  
  740. #ifdef TEST
  741.     test_written = blocksize;
  742. #endif
  743.     if(copy_back) {
  744.         ar_block+=copy_back;
  745.         bcopy((void *)(ar_block+blocking-copy_back),
  746.               (void *)ar_record,
  747.               copy_back*RECORDSIZE);
  748.         ar_record+=copy_back;
  749.  
  750.         if(real_s_sizeleft>=copy_back*RECORDSIZE)
  751.             real_s_sizeleft-=copy_back*RECORDSIZE;
  752.         else if((real_s_sizeleft+RECORDSIZE-1)/RECORDSIZE<=copy_back)
  753.             real_s_name[0] = '\0';
  754.         else {
  755. #ifdef MSDOS
  756.             if(save_name[1]==':')
  757.                 save_name+=2;
  758. #endif
  759.             while(*save_name=='/')
  760.                 save_name++;
  761.  
  762.             strcpy(real_s_name,save_name);
  763.             real_s_sizeleft = save_sizeleft;
  764.             real_s_totsize=save_totsize;
  765.         }
  766.         copy_back = 0;
  767.     }
  768. }
  769.  
  770. /* Handle write errors on the archive.  Write errors are always fatal */
  771. /* Hitting the end of a volume does not cause a write error unless the write
  772. *  was the first block of the volume */
  773.  
  774. void
  775. writeerror(err)
  776. int err;
  777. {
  778.     if (err < 0) {
  779.         msg_perror("can't write to %s",ar_file);
  780.         exit(EX_BADARCH);
  781.     } else {
  782.         msg("only wrote %u of %u bytes to %s",err,blocksize,ar_file);
  783.         exit(EX_BADARCH);
  784.     }
  785. }
  786.  
  787. /*
  788.  * Handle read errors on the archive.
  789.  *
  790.  * If the read should be retried, readerror() returns to the caller.
  791.  */
  792. void
  793. readerror()
  794. {
  795. #    define    READ_ERROR_MAX    10
  796.  
  797.     read_error_flag++;        /* Tell callers */
  798.  
  799.     msg_perror("read error on %s",ar_file);
  800.  
  801.     if (baserec == 0) {
  802.         /* First block of tape.  Probably stupidity error */
  803.         exit(EX_BADARCH);
  804.     }
  805.  
  806.     /*
  807.      * Read error in mid archive.  We retry up to READ_ERROR_MAX times
  808.      * and then give up on reading the archive.  We set read_error_flag
  809.      * for our callers, so they can cope if they want.
  810.      */
  811.     if (r_error_count++ > READ_ERROR_MAX) {
  812.         msg("Too many errors, quitting.");
  813.         exit(EX_BADARCH);
  814.     }
  815.     return;
  816. }
  817.  
  818.  
  819. /*
  820.  * Perform a read to flush the buffer.
  821.  */
  822. fl_read()
  823. {
  824.     int err;        /* Result from system call */
  825.     int left;        /* Bytes left */
  826.     char *more;        /* Pointer to next byte to read */
  827.  
  828.     /*
  829.      * Clear the count of errors.  This only applies to a single
  830.      * call to fl_read.  We leave read_error_flag alone; it is
  831.      * only turned off by higher level software.
  832.      */
  833.     r_error_count = 0;    /* Clear error count */
  834.  
  835.     /*
  836.      * If we are about to wipe out a record that
  837.      * somebody needs to keep, copy it out to a holding
  838.      * area and adjust somebody's pointer to it.
  839.      */
  840.     if (save_rec &&
  841.         *save_rec >= ar_record &&
  842.         *save_rec < ar_last) {
  843.         record_save_area = **save_rec;
  844.         *save_rec = &record_save_area;
  845.     }
  846.     if(write_archive_to_stdout && baserec!=0) {
  847.         err=rmtwrite(1, ar_block->charptr, blocksize);
  848.         if(err!=blocksize)
  849.             writeerror(err);
  850.     }
  851.     if(f_multivol) {
  852.         if(save_name) {
  853.             if(save_name!=real_s_name) {
  854. #ifdef MSDOS
  855.                 if(save_name[1]==':')
  856.                     save_name+=2;
  857. #endif
  858.                 while(*save_name=='/')
  859.                     save_name++;
  860.  
  861.                 strcpy(real_s_name,save_name);
  862.                 save_name=real_s_name;
  863.             }
  864.             real_s_totsize = save_totsize;
  865.             real_s_sizeleft = save_sizeleft;
  866.  
  867.         } else {
  868.             real_s_name[0]='\0';
  869.             real_s_totsize=0;
  870.             real_s_sizeleft = 0;
  871.         }
  872.     }
  873.  
  874. error_loop:
  875.     err = rmtread(archive, ar_block->charptr, (int)blocksize);
  876.     if (err == blocksize)
  877.         return;
  878.  
  879.     if((err == 0 || (err<0 && errno==ENOSPC)) && f_multivol) {
  880.         union record *head;
  881.  
  882.     try_volume:
  883.         if(new_volume((cmd_mode==CMD_APPEND || cmd_mode==CMD_CAT || cmd_mode==CMD_UPDATE) ? 2 : 1)<0)
  884.             return;
  885.     vol_error:
  886.         err = rmtread(archive, ar_block->charptr,(int) blocksize);
  887.         if(err < 0) {
  888.             readerror();
  889.             goto vol_error;
  890.         }
  891.         if(err!=blocksize)
  892.             goto short_read;
  893.  
  894.         head=ar_block;
  895.  
  896.         if(head->header.linkflag==LF_VOLHDR) {
  897.             if(f_volhdr) {
  898.                 char *ptr;
  899.  
  900.                 ptr=(char *)malloc(strlen(f_volhdr)+20);
  901.                 sprintf(ptr,"%s Volume %d",f_volhdr,volno);
  902.                  if(strcmp(ptr,head->header.name)) {
  903.                     msg("Volume mismatch! %s!=%s\n",ptr,head->header.name);
  904.                     --volno;
  905.                     free(ptr);
  906.                     goto try_volume;
  907.                 }
  908.                 free(ptr);
  909.             }
  910.             if(f_verbose)
  911.                 fprintf(msg_file,"Reading %s\n",head->header.name);
  912.             head++;
  913.         } else if(f_volhdr) {
  914.             msg("Warning:  No volume header!");
  915.         }
  916.  
  917.         if(real_s_name[0]) {
  918.             long from_oct();
  919.  
  920.             if(head->header.linkflag!=LF_MULTIVOL || strcmp(head->header.name,real_s_name)) {
  921.                 msg("%s is not continued on this volume!",real_s_name);
  922.                 --volno;
  923.                 goto try_volume;
  924.             }
  925.             if(real_s_totsize!=from_oct(1+12,head->header.size)+from_oct(1+12,head->header.offset)) {
  926.                 msg("%s is the wrong size (%ld!=%ld+%ld)",
  927.                        head->header.name,save_totsize,
  928.                        from_oct(1+12,head->header.size),
  929.                        from_oct(1+12,head->header.offset));
  930.                 --volno;
  931.                 goto try_volume;
  932.             }
  933.             if(real_s_totsize-real_s_sizeleft!=from_oct(1+12,head->header.offset)) {
  934.                 msg("This volume is out of sequence");
  935.                 --volno;
  936.                 goto try_volume;
  937.             }
  938.             head++;
  939.         }
  940.         ar_record=head;
  941.         return;
  942.     } else if (err < 0) {
  943.         readerror();
  944.         goto error_loop;    /* Try again */
  945.     }
  946.  
  947.  short_read:
  948.     more = ar_block->charptr + err;
  949.     left = blocksize - err;
  950.  
  951. again:
  952.     if (0 == (((unsigned)left) % RECORDSIZE)) {
  953.         /* FIXME, for size=0, multi vol support */
  954.         /* On the first block, warn about the problem */
  955.         if (!f_reblock && baserec == 0 && f_verbose && err > 0) {
  956.         /*    msg("Blocksize = %d record%s",
  957.                 err / RECORDSIZE, (err > RECORDSIZE)? "s": "");*/
  958.             msg("Blocksize = %d records", err / RECORDSIZE);
  959.         }
  960.         ar_last = ar_block + ((unsigned)(blocksize - left))/RECORDSIZE;
  961.         return;
  962.     }
  963.     if (f_reblock) {
  964.         /*
  965.          * User warned us about this.  Fix up.
  966.          */
  967.         if (left > 0) {
  968. error2loop:
  969.             err = rmtread(archive, more, (int)left);
  970.             if (err < 0) {
  971.                 readerror();
  972.                 goto error2loop;    /* Try again */
  973.             }
  974.             if (err == 0) {
  975.                 msg("archive %s EOF not on block boundary",ar_file);
  976.                 exit(EX_BADARCH);
  977.             }
  978.             left -= err;
  979.             more += err;
  980.             goto again;
  981.         }
  982.     } else {
  983.         msg("only read %d bytes from archive %s",err,ar_file);
  984.         exit(EX_BADARCH);
  985.     }
  986. }
  987.  
  988.  
  989. /*
  990.  * Flush the current buffer to/from the archive.
  991.  */
  992. flush_archive()
  993. {
  994.     int c;
  995.  
  996.     baserec += ar_last - ar_block;    /* Keep track of block #s */
  997.     ar_record = ar_block;        /* Restore pointer to start */
  998.     ar_last = ar_block + blocking;    /* Restore pointer to end */
  999.  
  1000.     if (ar_reading) {
  1001.         if(time_to_start_writing) {
  1002.             time_to_start_writing=0;
  1003.             ar_reading=0;
  1004.  
  1005.             if(file_to_switch_to>=0) {
  1006.                 if((c=rmtclose(archive))<0)
  1007.                     msg_perror("Warning: can't close %s(%d,%d)",ar_file,archive,c);
  1008.  
  1009.                 archive=file_to_switch_to;
  1010.             } else
  1011.                  (void)backspace_output();
  1012.             fl_write();
  1013.         } else
  1014.             fl_read();
  1015.     } else {
  1016.         fl_write();
  1017.     }
  1018. }
  1019.  
  1020. /* Backspace the archive descriptor by one blocks worth.
  1021.    If its a tape, MTIOCTOP will work.  If its something else,
  1022.    we try to seek on it.  If we can't seek, we lose! */
  1023. backspace_output()
  1024. {
  1025.     long cur;
  1026.     /* int er; */
  1027.     extern char *output_start;
  1028.  
  1029. #ifdef MTIOCTOP
  1030.     struct mtop t;
  1031.  
  1032.     t.mt_op = MTBSR;
  1033.     t.mt_count = 1;
  1034.     if((rmtioctl(archive,MTIOCTOP,&t))>=0)
  1035.         return 1;
  1036.     if(errno==EIO && (rmtioctl(archive,MTIOCTOP,&t))>=0)
  1037.         return 1;
  1038. #endif
  1039.  
  1040.         cur=rmtlseek(archive,0L,1);
  1041.     cur-=blocksize;
  1042.     /* Seek back to the beginning of this block and
  1043.        start writing there. */
  1044.  
  1045.     if(rmtlseek(archive,cur,0)!=cur) {
  1046.         /* Lseek failed.  Try a different method */
  1047.         msg("Couldn't backspace archive file.  It may be unreadable without -i.");
  1048.         /* Replace the first part of the block with nulls */
  1049.         if(ar_block->charptr!=output_start)
  1050.             bzero(ar_block->charptr,output_start-ar_block->charptr);
  1051.         return 2;
  1052.     }
  1053.     return 3;
  1054. }
  1055.  
  1056.  
  1057. /*
  1058.  * Close the archive file.
  1059.  */
  1060. close_archive()
  1061. {
  1062.     int child;
  1063.     int status;
  1064.     int c;
  1065.  
  1066.     if (time_to_start_writing || !ar_reading)
  1067.         flush_archive();
  1068.     if(cmd_mode==CMD_DELETE) {
  1069.         long pos;
  1070.  
  1071.         pos = rmtlseek(archive,0L,1);
  1072. #ifndef MSDOS
  1073.         /* FIXME does ftruncate really take an INT?! */
  1074.         (void) ftruncate(archive,(int)pos);
  1075. #else
  1076.         (void)rmtwrite(archive,"",0);
  1077. #endif
  1078.     }
  1079.     if(f_verify)
  1080.         verify_volume();
  1081.  
  1082.     if((c=rmtclose(archive))<0)
  1083.         msg_perror("Warning: can't close %s(%d,%d)",ar_file,archive,c);
  1084.  
  1085. #ifndef    MSDOS
  1086.     if (childpid) {
  1087.         /*
  1088.          * Loop waiting for the right child to die, or for
  1089.          * no more kids.
  1090.          */
  1091.         while (((child = wait(&status)) != childpid) && child != -1)
  1092.             ;
  1093.  
  1094.         if (child != -1) {
  1095.             switch (TERM_SIGNAL(status)) {
  1096.             case 0:
  1097.                 /* Child voluntarily terminated  -- but why? */
  1098.                 if (TERM_VALUE(status) == MAGIC_STAT) {
  1099.                     exit(EX_SYSTEM);/* Child had trouble */
  1100.                 }
  1101.                 if (TERM_VALUE(status) == (SIGPIPE + 128)) {
  1102.                     /*
  1103.                      * /bin/sh returns this if its child
  1104.                      * dies with SIGPIPE.  'Sok.
  1105.                      */
  1106.                     break;
  1107.                 } else if (TERM_VALUE(status))
  1108.                     msg("child returned status %d",
  1109.                         TERM_VALUE(status));
  1110.             case SIGPIPE:
  1111.                 break;        /* This is OK. */
  1112.  
  1113.             default:
  1114.                 msg("child died with signal %d%s",
  1115.                  TERM_SIGNAL(status),
  1116.                  TERM_COREDUMP(status)? " (core dumped)": "");
  1117.             }
  1118.         }
  1119.     }
  1120. #endif    /* MSDOS */
  1121. }
  1122.  
  1123.  
  1124. #ifdef DONTDEF
  1125. /*
  1126.  * Message management.
  1127.  *
  1128.  * anno writes a message prefix on stream (eg stdout, stderr).
  1129.  *
  1130.  * The specified prefix is normally output followed by a colon and a space.
  1131.  * However, if other command line options are set, more output can come
  1132.  * out, such as the record # within the archive.
  1133.  *
  1134.  * If the specified prefix is NULL, no output is produced unless the
  1135.  * command line option(s) are set.
  1136.  *
  1137.  * If the third argument is 1, the "saved" record # is used; if 0, the
  1138.  * "current" record # is used.
  1139.  */
  1140. void
  1141. anno(stream, prefix, savedp)
  1142.     FILE    *stream;
  1143.     char    *prefix;
  1144.     int    savedp;
  1145. {
  1146. #    define    MAXANNO    50
  1147.     char    buffer[MAXANNO];    /* Holds annorecment */
  1148. #    define    ANNOWIDTH 13
  1149.     int    space;
  1150.     long    offset;
  1151.     int    save_e;
  1152.  
  1153.     save_e=errno;
  1154.     /* Make sure previous output gets out in sequence */
  1155.     if (stream == stderr)
  1156.         fflush(stdout);
  1157.     if (f_sayblock) {
  1158.         if (prefix) {
  1159.             fputs(prefix, stream);
  1160.             putc(' ', stream);
  1161.         }
  1162.         offset = ar_record - ar_block;
  1163.         (void) sprintf(buffer, "rec %d: ",
  1164.             savedp?    saved_recno:
  1165.                 baserec + offset);
  1166.         fputs(buffer, stream);
  1167.         space = ANNOWIDTH - strlen(buffer);
  1168.         if (space > 0) {
  1169.             fprintf(stream, "%*s", space, "");
  1170.         }
  1171.     } else if (prefix) {
  1172.         fputs(prefix, stream);
  1173.         fputs(": ", stream);
  1174.     }
  1175.     errno=save_e;
  1176. }
  1177. #endif
  1178.  
  1179. /* We've hit the end of the old volume.  Close it and open the next one */
  1180. /* Values for type:  0: writing  1: reading  2: updating */
  1181. new_volume(type)
  1182. int    type;
  1183. {
  1184.     int    c;
  1185.     char    inbuf[80];
  1186.     char    *p;
  1187.     static FILE *read_file = 0;
  1188.     extern int now_verifying;
  1189.     extern char TTY_NAME[];
  1190.     char *getenv();
  1191.  
  1192.     if(!read_file && !f_run_script_at_end)
  1193.         read_file = (archive==0) ? fopen(TTY_NAME, "r") : stdin;
  1194.  
  1195.     if(now_verifying)
  1196.         return -1;
  1197.     if(f_verify)
  1198.         verify_volume();
  1199.     if((c=rmtclose(archive))<0)
  1200.         msg_perror("Warning: can't close %s(%d,%d)",ar_file,archive,c);
  1201.  
  1202.     volno++;
  1203.  tryagain:
  1204.     if (f_run_script_at_end)
  1205.         system(info_script);
  1206.     else for(;;) {
  1207.         fprintf(msg_file,"Prepare volume #%d and hit return: ",volno);
  1208. #ifdef MSDOS
  1209.                 while (kbhit())
  1210.                   getch();
  1211. #endif
  1212.         if(fgets(inbuf,sizeof(inbuf),read_file)==0 || inbuf[0]=='\n')
  1213.             break;
  1214.         switch(inbuf[0]) {
  1215.         case '?':
  1216.         {
  1217.             fprintf(msg_file,"\
  1218.  n [name]   Give a new filename for the next (and subsequent) volume(s)\n\
  1219.  q          Abort tar\n\
  1220.  !          Spawn a subshell\n\
  1221.  ?          Print this list\n");
  1222.         }
  1223.             break;
  1224.  
  1225.         case 'q':    /* Quit */
  1226.             fprintf(msg_file,"No new volume; exiting.\n");
  1227.             if(cmd_mode!=CMD_EXTRACT && cmd_mode!=CMD_LIST && cmd_mode!=CMD_DIFF)
  1228.                 msg("Warning:  Archive is INCOMPLETE!");
  1229.             exit(EX_BADARCH);
  1230.  
  1231.         case 'n':    /* Get new file name */
  1232.         {
  1233.             char *q,*r;
  1234.             static char *old_name;
  1235.  
  1236.             for(q= &inbuf[1];*q==' ' || *q=='\t';q++)
  1237.                 ;
  1238.             for(r=q;*r;r++)
  1239.                 if(*r=='\n')
  1240.                     *r='\0';
  1241.             if(old_name)
  1242.                 free(old_name);
  1243.             old_name=p=(char *)malloc((unsigned)(strlen(q)+2));
  1244.             if(p==0) {
  1245.                 msg("Can't allocate memory for name");
  1246.                 exit(EX_SYSTEM);
  1247.             }
  1248.             (void) strcpy(p,q);
  1249.             ar_file=p;
  1250.         }
  1251.             break;
  1252.  
  1253.         case '!':
  1254. #ifdef MSDOS
  1255.             spawnl(P_WAIT,getenv("COMSPEC"),"-",0);
  1256. #else
  1257.                 /* JF this needs work! */
  1258.             switch(fork()) {
  1259.             case -1:
  1260.                 msg_perror("can't fork!");
  1261.                 break;
  1262.             case 0:
  1263.                 p=getenv("SHELL");
  1264.                 if(p==0) p="/bin/sh";
  1265.                 execlp(p,"-sh","-i",0);
  1266.                 msg_perror("can't exec a shell %s",p);
  1267.                 _exit(55);
  1268.             default:
  1269.                 wait(0);
  1270.                 break;
  1271.             }
  1272. #endif
  1273.             break;
  1274.         }
  1275.     }
  1276.  
  1277.     if(type==2 || f_verify)
  1278.         archive=rmtopen(ar_file,O_RDWR|O_CREAT,0666);
  1279.     else if(type==1)
  1280.         archive=rmtopen(ar_file,O_RDONLY,0666);
  1281.     else if(type==0)
  1282.         archive=rmtcreat(ar_file,0666);
  1283.     else
  1284.         archive= -1;
  1285.  
  1286.     if(archive<0) {
  1287.         msg_perror("can't open %s",ar_file);
  1288.         goto tryagain;
  1289.     }
  1290. #ifdef MSDOS
  1291.     setmode(archive,O_BINARY);
  1292. #endif
  1293.     return 0;
  1294. }
  1295.  
  1296. /* this is a useless function that takes a buffer returned by wantbytes
  1297.    and does nothing with it.  If the function called by wantbytes returns
  1298.    an error indicator (non-zero), this function is called for the rest of
  1299.    the file.
  1300.  */
  1301. int
  1302. no_op(size,data)
  1303. int size;
  1304. char *data;
  1305. {
  1306.     return 0;
  1307. }
  1308.  
  1309. /* Some other routine wants SIZE bytes in the archive.  For each chunk of
  1310.    the archive, call FUNC with the size of the chunk, and the address of
  1311.    the chunk it can work with.
  1312.  */
  1313. int
  1314. wantbytes(size,func)
  1315. long size;
  1316. int (*func)();
  1317. {
  1318.     char *data;
  1319.     long    data_size;
  1320.  
  1321.     while(size) {
  1322.         data = findrec()->charptr;
  1323.         if (data == NULL) {    /* Check it... */
  1324.             msg("Unexpected EOF on archive file");
  1325.             return -1;
  1326.         }
  1327.         data_size = endofrecs()->charptr - data;
  1328.         if(data_size>size)
  1329.             data_size=size;
  1330.         if((*func)(data_size,data))
  1331.             func=no_op;
  1332.         userec((union record *)(data + data_size - 1));
  1333.         size-=data_size;
  1334.     }
  1335.     return 0;
  1336. }
  1337.