/*-1* SPDX-License-Identifier: BSD-3-Clause2*3* Copyright (c) 1992 Keith Muller.4* Copyright (c) 1992, 19935* The Regents of the University of California. All rights reserved.6*7* This code is derived from software contributed to Berkeley by8* Keith Muller of the University of California, San Diego.9*10* Redistribution and use in source and binary forms, with or without11* modification, are permitted provided that the following conditions12* are met:13* 1. Redistributions of source code must retain the above copyright14* notice, this list of conditions and the following disclaimer.15* 2. Redistributions in binary form must reproduce the above copyright16* notice, this list of conditions and the following disclaimer in the17* documentation and/or other materials provided with the distribution.18* 3. Neither the name of the University nor the names of its contributors19* may be used to endorse or promote products derived from this software20* without specific prior written permission.21*22* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND23* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE24* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE25* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE26* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL27* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS28* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)29* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT30* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY31* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF32* SUCH DAMAGE.33*/3435#include <sys/types.h>36#include <sys/time.h>37#include <sys/stat.h>38#include <signal.h>39#include <string.h>40#include <stdio.h>41#include <fcntl.h>42#include <errno.h>43#include <unistd.h>44#include "pax.h"45#include "extern.h"4647static void wr_archive(ARCHD *, int is_app);48static int get_arc(void);49static int next_head(ARCHD *);5051/*52* Routines which control the overall operation modes of pax as specified by53* the user: list, append, read ...54*/5556static char hdbuf[BLKMULT]; /* space for archive header on read */57u_long flcnt; /* number of files processed */5859/*60* list()61* list the contents of an archive which match user supplied pattern(s)62* (no pattern matches all).63*/6465void66list(void)67{68ARCHD *arcn;69int res;70ARCHD archd;71time_t now;7273arcn = &archd;74/*75* figure out archive type; pass any format specific options to the76* archive option processing routine; call the format init routine. We77* also save current time for ls_list() so we do not make a system78* call for each file we need to print. If verbose (vflag) start up79* the name and group caches.80*/81if ((get_arc() < 0) || ((*frmt->options)() < 0) ||82((*frmt->st_rd)() < 0))83return;8485if (vflag && ((uidtb_start() < 0) || (gidtb_start() < 0)))86return;8788now = time(NULL);8990/*91* step through the archive until the format says it is done92*/93while (next_head(arcn) == 0) {94/*95* check for pattern, and user specified options match.96* When all patterns are matched we are done.97*/98if ((res = pat_match(arcn)) < 0)99break;100101if ((res == 0) && (sel_chk(arcn) == 0)) {102/*103* pattern resulted in a selected file104*/105if (pat_sel(arcn) < 0)106break;107108/*109* modify the name as requested by the user if name110* survives modification, do a listing of the file111*/112if ((res = mod_name(arcn)) < 0)113break;114if (res == 0)115ls_list(arcn, now, stdout);116}117118/*119* skip to next archive format header using values calculated120* by the format header read routine121*/122if (rd_skip(arcn->skip + arcn->pad) == 1)123break;124}125126/*127* all done, let format have a chance to cleanup, and make sure that128* the patterns supplied by the user were all matched129*/130(void)(*frmt->end_rd)();131(void)sigprocmask(SIG_BLOCK, &s_mask, NULL);132ar_close();133pat_chk();134}135136/*137* extract()138* extract the member(s) of an archive as specified by user supplied139* pattern(s) (no patterns extracts all members)140*/141142void143extract(void)144{145ARCHD *arcn;146int res;147off_t cnt;148ARCHD archd;149struct stat sb;150int fd;151time_t now;152153arcn = &archd;154/*155* figure out archive type; pass any format specific options to the156* archive option processing routine; call the format init routine;157* start up the directory modification time and access mode database158*/159if ((get_arc() < 0) || ((*frmt->options)() < 0) ||160((*frmt->st_rd)() < 0) || (dir_start() < 0))161return;162163/*164* When we are doing interactive rename, we store the mapping of names165* so we can fix up hard links files later in the archive.166*/167if (iflag && (name_start() < 0))168return;169170now = time(NULL);171172/*173* step through each entry on the archive until the format read routine174* says it is done175*/176while (next_head(arcn) == 0) {177178/*179* check for pattern, and user specified options match. When180* all the patterns are matched we are done181*/182if ((res = pat_match(arcn)) < 0)183break;184185if ((res > 0) || (sel_chk(arcn) != 0)) {186/*187* file is not selected. skip past any file data and188* padding and go back for the next archive member189*/190(void)rd_skip(arcn->skip + arcn->pad);191continue;192}193194/*195* with -u or -D only extract when the archive member is newer196* than the file with the same name in the file system (no197* test of being the same type is required).198* NOTE: this test is done BEFORE name modifications as199* specified by pax. this operation can be confusing to the200* user who might expect the test to be done on an existing201* file AFTER the name mod. In honesty the pax spec is probably202* flawed in this respect.203*/204if ((uflag || Dflag) && ((lstat(arcn->name, &sb) == 0))) {205if (uflag && Dflag) {206if ((arcn->sb.st_mtime <= sb.st_mtime) &&207(arcn->sb.st_ctime <= sb.st_ctime)) {208(void)rd_skip(arcn->skip + arcn->pad);209continue;210}211} else if (Dflag) {212if (arcn->sb.st_ctime <= sb.st_ctime) {213(void)rd_skip(arcn->skip + arcn->pad);214continue;215}216} else if (arcn->sb.st_mtime <= sb.st_mtime) {217(void)rd_skip(arcn->skip + arcn->pad);218continue;219}220}221222/*223* this archive member is now been selected. modify the name.224*/225if ((pat_sel(arcn) < 0) || ((res = mod_name(arcn)) < 0))226break;227if (res > 0) {228/*229* a bad name mod, skip and purge name from link table230*/231purg_lnk(arcn);232(void)rd_skip(arcn->skip + arcn->pad);233continue;234}235236/*237* Non standard -Y and -Z flag. When the existing file is238* same age or newer skip239*/240if ((Yflag || Zflag) && ((lstat(arcn->name, &sb) == 0))) {241if (Yflag && Zflag) {242if ((arcn->sb.st_mtime <= sb.st_mtime) &&243(arcn->sb.st_ctime <= sb.st_ctime)) {244(void)rd_skip(arcn->skip + arcn->pad);245continue;246}247} else if (Yflag) {248if (arcn->sb.st_ctime <= sb.st_ctime) {249(void)rd_skip(arcn->skip + arcn->pad);250continue;251}252} else if (arcn->sb.st_mtime <= sb.st_mtime) {253(void)rd_skip(arcn->skip + arcn->pad);254continue;255}256}257258if (vflag) {259if (vflag > 1)260ls_list(arcn, now, listf);261else {262(void)fputs(arcn->name, listf);263vfpart = 1;264}265}266267/*268* if required, chdir around.269*/270if ((arcn->pat != NULL) && (arcn->pat->chdname != NULL))271if (chdir(arcn->pat->chdname) != 0)272syswarn(1, errno, "Cannot chdir to %s",273arcn->pat->chdname);274275/*276* all ok, extract this member based on type277*/278if ((arcn->type != PAX_REG) && (arcn->type != PAX_CTG)) {279/*280* process archive members that are not regular files.281* throw out padding and any data that might follow the282* header (as determined by the format).283*/284if ((arcn->type == PAX_HLK) || (arcn->type == PAX_HRG))285res = lnk_creat(arcn);286else287res = node_creat(arcn);288289(void)rd_skip(arcn->skip + arcn->pad);290if (res < 0)291purg_lnk(arcn);292293if (vflag && vfpart) {294(void)putc('\n', listf);295vfpart = 0;296}297continue;298}299/*300* we have a file with data here. If we can not create it, skip301* over the data and purge the name from hard link table302*/303if ((fd = file_creat(arcn)) < 0) {304(void)rd_skip(arcn->skip + arcn->pad);305purg_lnk(arcn);306continue;307}308/*309* extract the file from the archive and skip over padding and310* any unprocessed data311*/312res = (*frmt->rd_data)(arcn, fd, &cnt);313file_close(arcn, fd);314if (vflag && vfpart) {315(void)putc('\n', listf);316vfpart = 0;317}318if (!res)319(void)rd_skip(cnt + arcn->pad);320321/*322* if required, chdir around.323*/324if ((arcn->pat != NULL) && (arcn->pat->chdname != NULL))325if (fchdir(cwdfd) != 0)326syswarn(1, errno,327"Can't fchdir to starting directory");328}329330/*331* all done, restore directory modes and times as required; make sure332* all patterns supplied by the user were matched; block off signals333* to avoid chance for multiple entry into the cleanup code.334*/335(void)(*frmt->end_rd)();336(void)sigprocmask(SIG_BLOCK, &s_mask, NULL);337ar_close();338proc_dir();339pat_chk();340}341342/*343* wr_archive()344* Write an archive. used in both creating a new archive and appends on345* previously written archive.346*/347348static void349wr_archive(ARCHD *arcn, int is_app)350{351int res;352int hlk;353int wr_one;354off_t cnt;355int (*wrf)(ARCHD *);356int fd = -1;357time_t now;358359/*360* if this format supports hard link storage, start up the database361* that detects them.362*/363if (((hlk = frmt->hlk) == 1) && (lnk_start() < 0))364return;365366/*367* start up the file traversal code and format specific write368*/369if ((ftree_start() < 0) || ((*frmt->st_wr)() < 0))370return;371wrf = frmt->wr;372373/*374* When we are doing interactive rename, we store the mapping of names375* so we can fix up hard links files later in the archive.376*/377if (iflag && (name_start() < 0))378return;379380/*381* if this is not append, and there are no files, we do not write a382* trailer383*/384wr_one = is_app;385386now = time(NULL);387388/*389* while there are files to archive, process them one at at time390*/391while (next_file(arcn) == 0) {392/*393* check if this file meets user specified options match.394*/395if (sel_chk(arcn) != 0) {396ftree_notsel();397continue;398}399fd = -1;400if (uflag) {401/*402* only archive if this file is newer than a file with403* the same name that is already stored on the archive404*/405if ((res = chk_ftime(arcn)) < 0)406break;407if (res > 0)408continue;409}410411/*412* this file is considered selected now. see if this is a hard413* link to a file already stored414*/415ftree_sel(arcn);416if (hlk && (chk_lnk(arcn) < 0))417break;418419if ((arcn->type == PAX_REG) || (arcn->type == PAX_HRG) ||420(arcn->type == PAX_CTG)) {421/*422* we will have to read this file. by opening it now we423* can avoid writing a header to the archive for a file424* we were later unable to read (we also purge it from425* the link table).426*/427if ((fd = open(arcn->org_name, O_RDONLY, 0)) < 0) {428syswarn(1,errno, "Unable to open %s to read",429arcn->org_name);430purg_lnk(arcn);431continue;432}433}434435/*436* Now modify the name as requested by the user437*/438if ((res = mod_name(arcn)) < 0) {439/*440* name modification says to skip this file, close the441* file and purge link table entry442*/443rdfile_close(arcn, &fd);444purg_lnk(arcn);445break;446}447448if ((res > 0) || (docrc && (set_crc(arcn, fd) < 0))) {449/*450* unable to obtain the crc we need, close the file,451* purge link table entry452*/453rdfile_close(arcn, &fd);454purg_lnk(arcn);455continue;456}457458if (vflag) {459if (vflag > 1)460ls_list(arcn, now, listf);461else {462(void)fputs(arcn->name, listf);463vfpart = 1;464}465}466++flcnt;467468/*469* looks safe to store the file, have the format specific470* routine write routine store the file header on the archive471*/472if ((res = (*wrf)(arcn)) < 0) {473rdfile_close(arcn, &fd);474break;475}476wr_one = 1;477if (res > 0) {478/*479* format write says no file data needs to be stored480* so we are done messing with this file481*/482if (vflag && vfpart) {483(void)putc('\n', listf);484vfpart = 0;485}486rdfile_close(arcn, &fd);487continue;488}489490/*491* Add file data to the archive, quit on write error. if we492* cannot write the entire file contents to the archive we493* must pad the archive to replace the missing file data494* (otherwise during an extract the file header for the file495* which FOLLOWS this one will not be where we expect it to496* be).497*/498res = (*frmt->wr_data)(arcn, fd, &cnt);499rdfile_close(arcn, &fd);500if (vflag && vfpart) {501(void)putc('\n', listf);502vfpart = 0;503}504if (res < 0)505break;506507/*508* pad as required, cnt is number of bytes not written509*/510if (((cnt > 0) && (wr_skip(cnt) < 0)) ||511((arcn->pad > 0) && (wr_skip(arcn->pad) < 0)))512break;513}514515/*516* tell format to write trailer; pad to block boundary; reset directory517* mode/access times, and check if all patterns supplied by the user518* were matched. block off signals to avoid chance for multiple entry519* into the cleanup code520*/521if (wr_one) {522(*frmt->end_wr)();523wr_fin();524}525(void)sigprocmask(SIG_BLOCK, &s_mask, NULL);526ar_close();527if (tflag)528proc_dir();529ftree_chk();530}531532/*533* append()534* Add file to previously written archive. Archive format specified by the535* user must agree with archive. The archive is read first to collect536* modification times (if -u) and locate the archive trailer. The archive537* is positioned in front of the record with the trailer and wr_archive()538* is called to add the new members.539* PAX IMPLEMENTATION DETAIL NOTE:540* -u is implemented by adding the new members to the end of the archive.541* Care is taken so that these do not end up as links to the older542* version of the same file already stored in the archive. It is expected543* when extraction occurs these newer versions will over-write the older544* ones stored "earlier" in the archive (this may be a bad assumption as545* it depends on the implementation of the program doing the extraction).546* It is really difficult to splice in members without either re-writing547* the entire archive (from the point were the old version was), or having548* assistance of the format specification in terms of a special update549* header that invalidates a previous archive record. The POSIX spec left550* the method used to implement -u unspecified. This pax is able to551* over write existing files that it creates.552*/553554void555append(void)556{557ARCHD *arcn;558int res;559ARCHD archd;560FSUB *orgfrmt;561int udev;562off_t tlen;563564arcn = &archd;565orgfrmt = frmt;566567/*568* Do not allow an append operation if the actual archive is of a569* different format than the user specified format.570*/571if (get_arc() < 0)572return;573if ((orgfrmt != NULL) && (orgfrmt != frmt)) {574paxwarn(1, "Cannot mix current archive format %s with %s",575frmt->name, orgfrmt->name);576return;577}578579/*580* pass the format any options and start up format581*/582if (((*frmt->options)() < 0) || ((*frmt->st_rd)() < 0))583return;584585/*586* if we only are adding members that are newer, we need to save the587* mod times for all files we see.588*/589if (uflag && (ftime_start() < 0))590return;591592/*593* some archive formats encode hard links by recording the device and594* file serial number (inode) but copy the file anyway (multiple times)595* to the archive. When we append, we run the risk that newly added596* files may have the same device and inode numbers as those recorded597* on the archive but during a previous run. If this happens, when the598* archive is extracted we get INCORRECT hard links. We avoid this by599* remapping the device numbers so that newly added files will never600* use the same device number as one found on the archive. remapping601* allows new members to safely have links among themselves. remapping602* also avoids problems with file inode (serial number) truncations603* when the inode number is larger than storage space in the archive604* header. See the remap routines for more details.605*/606if ((udev = frmt->udev) && (dev_start() < 0))607return;608609/*610* reading the archive may take a long time. If verbose tell the user611*/612if (vflag) {613(void)fprintf(listf,614"%s: Reading archive to position at the end...", argv0);615vfpart = 1;616}617618/*619* step through the archive until the format says it is done620*/621while (next_head(arcn) == 0) {622/*623* check if this file meets user specified options.624*/625if (sel_chk(arcn) != 0) {626if (rd_skip(arcn->skip + arcn->pad) == 1)627break;628continue;629}630631if (uflag) {632/*633* see if this is the newest version of this file has634* already been seen, if so skip.635*/636if ((res = chk_ftime(arcn)) < 0)637break;638if (res > 0) {639if (rd_skip(arcn->skip + arcn->pad) == 1)640break;641continue;642}643}644645/*646* Store this device number. Device numbers seen during the647* read phase of append will cause newly appended files with a648* device number seen in the old part of the archive to be649* remapped to an unused device number.650*/651if ((udev && (add_dev(arcn) < 0)) ||652(rd_skip(arcn->skip + arcn->pad) == 1))653break;654}655656/*657* done, finish up read and get the number of bytes to back up so we658* can add new members. The format might have used the hard link table,659* purge it.660*/661tlen = (*frmt->end_rd)();662lnk_end();663664/*665* try to position for write, if this fails quit. if any error occurs,666* we will refuse to write667*/668if (appnd_start(tlen) < 0)669return;670671/*672* tell the user we are done reading.673*/674if (vflag && vfpart) {675(void)fputs("done.\n", listf);676vfpart = 0;677}678679/*680* go to the writing phase to add the new members681*/682wr_archive(arcn, 1);683}684685/*686* archive()687* write a new archive688*/689690void691archive(void)692{693ARCHD archd;694695/*696* if we only are adding members that are newer, we need to save the697* mod times for all files; set up for writing; pass the format any698* options write the archive699*/700if ((uflag && (ftime_start() < 0)) || (wr_start() < 0))701return;702if ((*frmt->options)() < 0)703return;704705wr_archive(&archd, 0);706}707708/*709* copy()710* copy files from one part of the file system to another. this does not711* use any archive storage. The EFFECT OF THE COPY IS THE SAME as if an712* archive was written and then extracted in the destination directory713* (except the files are forced to be under the destination directory).714*/715716void717copy(void)718{719ARCHD *arcn;720int res;721int fddest;722char *dest_pt;723int dlen;724int drem;725int fdsrc = -1;726struct stat sb;727ARCHD archd;728char dirbuf[PAXPATHLEN+1];729730arcn = &archd;731/*732* set up the destination dir path and make sure it is a directory. We733* make sure we have a trailing / on the destination734*/735dlen = l_strncpy(dirbuf, dirptr, sizeof(dirbuf) - 1);736dest_pt = dirbuf + dlen;737if (*(dest_pt-1) != '/') {738*dest_pt++ = '/';739++dlen;740}741*dest_pt = '\0';742drem = PAXPATHLEN - dlen;743744if (stat(dirptr, &sb) < 0) {745syswarn(1, errno, "Cannot access destination directory %s",746dirptr);747return;748}749if (!S_ISDIR(sb.st_mode)) {750paxwarn(1, "Destination is not a directory %s", dirptr);751return;752}753754/*755* start up the hard link table; file traversal routines and the756* modification time and access mode database757*/758if ((lnk_start() < 0) || (ftree_start() < 0) || (dir_start() < 0))759return;760761/*762* When we are doing interactive rename, we store the mapping of names763* so we can fix up hard links files later in the archive.764*/765if (iflag && (name_start() < 0))766return;767768/*769* set up to cp file trees770*/771cp_start();772773/*774* while there are files to archive, process them775*/776while (next_file(arcn) == 0) {777fdsrc = -1;778779/*780* check if this file meets user specified options781*/782if (sel_chk(arcn) != 0) {783ftree_notsel();784continue;785}786787/*788* if there is already a file in the destination directory with789* the same name and it is newer, skip the one stored on the790* archive.791* NOTE: this test is done BEFORE name modifications as792* specified by pax. this can be confusing to the user who793* might expect the test to be done on an existing file AFTER794* the name mod. In honesty the pax spec is probably flawed in795* this respect796*/797if (uflag || Dflag) {798/*799* create the destination name800*/801if (*(arcn->name) == '/')802res = 1;803else804res = 0;805if ((arcn->nlen - res) > drem) {806paxwarn(1, "Destination pathname too long %s",807arcn->name);808continue;809}810(void)strncpy(dest_pt, arcn->name + res, drem);811dirbuf[PAXPATHLEN] = '\0';812813/*814* if existing file is same age or newer skip815*/816res = lstat(dirbuf, &sb);817*dest_pt = '\0';818819if (res == 0) {820if (uflag && Dflag) {821if ((arcn->sb.st_mtime<=sb.st_mtime) &&822(arcn->sb.st_ctime<=sb.st_ctime))823continue;824} else if (Dflag) {825if (arcn->sb.st_ctime <= sb.st_ctime)826continue;827} else if (arcn->sb.st_mtime <= sb.st_mtime)828continue;829}830}831832/*833* this file is considered selected. See if this is a hard link834* to a previous file; modify the name as requested by the835* user; set the final destination.836*/837ftree_sel(arcn);838if ((chk_lnk(arcn) < 0) || ((res = mod_name(arcn)) < 0))839break;840if ((res > 0) || (set_dest(arcn, dirbuf, dlen) < 0)) {841/*842* skip file, purge from link table843*/844purg_lnk(arcn);845continue;846}847848/*849* Non standard -Y and -Z flag. When the existing file is850* same age or newer skip851*/852if ((Yflag || Zflag) && ((lstat(arcn->name, &sb) == 0))) {853if (Yflag && Zflag) {854if ((arcn->sb.st_mtime <= sb.st_mtime) &&855(arcn->sb.st_ctime <= sb.st_ctime))856continue;857} else if (Yflag) {858if (arcn->sb.st_ctime <= sb.st_ctime)859continue;860} else if (arcn->sb.st_mtime <= sb.st_mtime)861continue;862}863864if (vflag) {865(void)fputs(arcn->name, listf);866vfpart = 1;867}868++flcnt;869870/*871* try to create a hard link to the src file if requested872* but make sure we are not trying to overwrite ourselves.873*/874if (lflag)875res = cross_lnk(arcn);876else877res = chk_same(arcn);878if (res <= 0) {879if (vflag && vfpart) {880(void)putc('\n', listf);881vfpart = 0;882}883continue;884}885886/*887* have to create a new file888*/889if ((arcn->type != PAX_REG) && (arcn->type != PAX_CTG)) {890/*891* create a link or special file892*/893if ((arcn->type == PAX_HLK) || (arcn->type == PAX_HRG))894res = lnk_creat(arcn);895else896res = node_creat(arcn);897if (res < 0)898purg_lnk(arcn);899if (vflag && vfpart) {900(void)putc('\n', listf);901vfpart = 0;902}903continue;904}905906/*907* have to copy a regular file to the destination directory.908* first open source file and then create the destination file909*/910if ((fdsrc = open(arcn->org_name, O_RDONLY, 0)) < 0) {911syswarn(1, errno, "Unable to open %s to read",912arcn->org_name);913purg_lnk(arcn);914continue;915}916if ((fddest = file_creat(arcn)) < 0) {917rdfile_close(arcn, &fdsrc);918purg_lnk(arcn);919continue;920}921922/*923* copy source file data to the destination file924*/925cp_file(arcn, fdsrc, fddest);926file_close(arcn, fddest);927rdfile_close(arcn, &fdsrc);928929if (vflag && vfpart) {930(void)putc('\n', listf);931vfpart = 0;932}933}934935/*936* restore directory modes and times as required; make sure all937* patterns were selected block off signals to avoid chance for938* multiple entry into the cleanup code.939*/940(void)sigprocmask(SIG_BLOCK, &s_mask, NULL);941ar_close();942proc_dir();943ftree_chk();944}945946/*947* next_head()948* try to find a valid header in the archive. Uses format specific949* routines to extract the header and id the trailer. Trailers may be950* located within a valid header or in an invalid header (the location951* is format specific. The inhead field from the option table tells us952* where to look for the trailer).953* We keep reading (and resyncing) until we get enough contiguous data954* to check for a header. If we cannot find one, we shift by a byte955* add a new byte from the archive to the end of the buffer and try again.956* If we get a read error, we throw out what we have (as we must have957* contiguous data) and start over again.958* ASSUMED: headers fit within a BLKMULT header.959* Return:960* 0 if we got a header, -1 if we are unable to ever find another one961* (we reached the end of input, or we reached the limit on retries. see962* the specs for rd_wrbuf() for more details)963*/964965static int966next_head(ARCHD *arcn)967{968int ret;969char *hdend;970int res;971int shftsz;972int hsz;973int in_resync = 0; /* set when we are in resync mode */974int cnt = 0; /* counter for trailer function */975int first = 1; /* on 1st read, EOF isn't premature. */976977/*978* set up initial conditions, we want a whole frmt->hsz block as we979* have no data yet.980*/981res = hsz = frmt->hsz;982hdend = hdbuf;983shftsz = hsz - 1;984for(;;) {985/*986* keep looping until we get a contiguous FULL buffer987* (frmt->hsz is the proper size)988*/989for (;;) {990if ((ret = rd_wrbuf(hdend, res)) == res)991break;992993/*994* If we read 0 bytes (EOF) from an archive when we995* expect to find a header, we have stepped upon996* an archive without the customary block of zeroes997* end marker. It's just stupid to error out on998* them, so exit gracefully.999*/1000if (first && ret == 0)1001return(-1);1002first = 0;10031004/*1005* some kind of archive read problem, try to resync the1006* storage device, better give the user the bad news.1007*/1008if ((ret == 0) || (rd_sync() < 0)) {1009paxwarn(1,"Premature end of file on archive read");1010return(-1);1011}1012if (!in_resync) {1013if (act == APPND) {1014paxwarn(1,1015"Archive I/O error, cannot continue");1016return(-1);1017}1018paxwarn(1,"Archive I/O error. Trying to recover.");1019++in_resync;1020}10211022/*1023* oh well, throw it all out and start over1024*/1025res = hsz;1026hdend = hdbuf;1027}10281029/*1030* ok we have a contiguous buffer of the right size. Call the1031* format read routine. If this was not a valid header and this1032* format stores trailers outside of the header, call the1033* format specific trailer routine to check for a trailer. We1034* have to watch out that we do not mis-identify file data or1035* block padding as a header or trailer. Format specific1036* trailer functions must NOT check for the trailer while we1037* are running in resync mode. Some trailer functions may tell1038* us that this block cannot contain a valid header either, so1039* we then throw out the entire block and start over.1040*/1041if ((*frmt->rd)(arcn, hdbuf) == 0)1042break;10431044if (!frmt->inhead) {1045/*1046* this format has trailers outside of valid headers1047*/1048if ((ret = (*frmt->trail_tar)(hdbuf,in_resync,&cnt)) == 0){1049/*1050* valid trailer found, drain input as required1051*/1052ar_drain();1053return(-1);1054}10551056if (ret == 1) {1057/*1058* we are in resync and we were told to throw1059* the whole block out because none of the1060* bytes in this block can be used to form a1061* valid header1062*/1063res = hsz;1064hdend = hdbuf;1065continue;1066}1067}10681069/*1070* Brute force section.1071* not a valid header. We may be able to find a header yet. So1072* we shift over by one byte, and set up to read one byte at a1073* time from the archive and place it at the end of the buffer.1074* We will keep moving byte at a time until we find a header or1075* get a read error and have to start over.1076*/1077if (!in_resync) {1078if (act == APPND) {1079paxwarn(1,"Unable to append, archive header flaw");1080return(-1);1081}1082paxwarn(1,"Invalid header, starting valid header search.");1083++in_resync;1084}1085memmove(hdbuf, hdbuf+1, shftsz);1086res = 1;1087hdend = hdbuf + shftsz;1088}10891090/*1091* ok got a valid header, check for trailer if format encodes it in1092* the header.1093*/1094if (frmt->inhead && ((*frmt->trail_cpio)(arcn) == 0)) {1095/*1096* valid trailer found, drain input as required1097*/1098ar_drain();1099return(-1);1100}11011102++flcnt;1103return(0);1104}11051106/*1107* get_arc()1108* Figure out what format an archive is. Handles archive with flaws by1109* brute force searches for a legal header in any supported format. The1110* format id routines have to be careful to NOT mis-identify a format.1111* ASSUMED: headers fit within a BLKMULT header.1112* Return:1113* 0 if archive found -1 otherwise1114*/11151116static int1117get_arc(void)1118{1119int i;1120int hdsz = 0;1121int res;1122int minhd = BLKMULT;1123char *hdend;1124int notice = 0;11251126/*1127* find the smallest header size in all archive formats and then set up1128* to read the archive.1129*/1130for (i = 0; ford[i] >= 0; ++i) {1131if (fsub[ford[i]].hsz < minhd)1132minhd = fsub[ford[i]].hsz;1133}1134if (rd_start() < 0)1135return(-1);1136res = BLKMULT;1137hdsz = 0;1138hdend = hdbuf;1139for(;;) {1140for (;;) {1141/*1142* fill the buffer with at least the smallest header1143*/1144i = rd_wrbuf(hdend, res);1145if (i > 0)1146hdsz += i;1147if (hdsz >= minhd)1148break;11491150/*1151* if we cannot recover from a read error quit1152*/1153if ((i == 0) || (rd_sync() < 0))1154goto out;11551156/*1157* when we get an error none of the data we already1158* have can be used to create a legal header (we just1159* got an error in the middle), so we throw it all out1160* and refill the buffer with fresh data.1161*/1162res = BLKMULT;1163hdsz = 0;1164hdend = hdbuf;1165if (!notice) {1166if (act == APPND)1167return(-1);1168paxwarn(1,"Cannot identify format. Searching...");1169++notice;1170}1171}11721173/*1174* we have at least the size of the smallest header in any1175* archive format. Look to see if we have a match. The array1176* ford[] is used to specify the header id order to reduce the1177* chance of incorrectly id'ing a valid header (some formats1178* may be subsets of each other and the order would then be1179* important).1180*/1181for (i = 0; ford[i] >= 0; ++i) {1182if ((*fsub[ford[i]].id)(hdbuf, hdsz) < 0)1183continue;1184frmt = &(fsub[ford[i]]);1185/*1186* yuck, to avoid slow special case code in the extract1187* routines, just push this header back as if it was1188* not seen. We have left extra space at start of the1189* buffer for this purpose. This is a bit ugly, but1190* adding all the special case code is far worse.1191*/1192pback(hdbuf, hdsz);1193return(0);1194}11951196/*1197* We have a flawed archive, no match. we start searching, but1198* we never allow additions to flawed archives1199*/1200if (!notice) {1201if (act == APPND)1202return(-1);1203paxwarn(1, "Cannot identify format. Searching...");1204++notice;1205}12061207/*1208* brute force search for a header that we can id.1209* we shift through byte at a time. this is slow, but we cannot1210* determine the nature of the flaw in the archive in a1211* portable manner1212*/1213if (--hdsz > 0) {1214memmove(hdbuf, hdbuf+1, hdsz);1215res = BLKMULT - hdsz;1216hdend = hdbuf + hdsz;1217} else {1218res = BLKMULT;1219hdend = hdbuf;1220hdsz = 0;1221}1222}12231224out:1225/*1226* we cannot find a header, bow, apologize and quit1227*/1228paxwarn(1, "Sorry, unable to determine archive format.");1229return(-1);1230}123112321233