buffer.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. /* Buffer management for tar.
  2. Copyright 1988-2023 Free Software Foundation, Inc.
  3. This file is part of GNU tar.
  4. GNU tar is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. GNU tar is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. Written by John Gilmore, on 1985-08-25. */
  15. #include <system.h>
  16. #include <signal.h>
  17. #include <closeout.h>
  18. #include <fnmatch.h>
  19. #include <human.h>
  20. #include <quotearg.h>
  21. #include <verify.h>
  22. #include "common.h"
  23. #include <rmt.h>
  24. /* Work around GCC bug 109856. */
  25. # if 13 <= __GNUC__
  26. # pragma GCC diagnostic ignored "-Wnull-dereference"
  27. # endif
  28. /* Number of retries before giving up on read. */
  29. #define READ_ERROR_MAX 10
  30. /* Variables. */
  31. static tarlong prev_written; /* bytes written on previous volumes */
  32. static tarlong bytes_written; /* bytes written on this volume */
  33. static void *record_buffer[2]; /* allocated memory */
  34. static union block *record_buffer_aligned[2];
  35. static int record_index;
  36. /* FIXME: The following variables should ideally be static to this
  37. module. However, this cannot be done yet. The cleanup continues! */
  38. union block *record_start; /* start of record of archive */
  39. union block *record_end; /* last+1 block of archive record */
  40. union block *current_block; /* current block of archive */
  41. enum access_mode access_mode; /* how do we handle the archive */
  42. off_t records_read; /* number of records read from this archive */
  43. off_t records_written; /* likewise, for records written */
  44. extern off_t records_skipped; /* number of records skipped at the start
  45. of the archive, defined in delete.c */
  46. static off_t record_start_block; /* block ordinal at record_start */
  47. /* Where we write list messages (not errors, not interactions) to. */
  48. FILE *stdlis;
  49. static void backspace_output (void);
  50. /* PID of child program, if compress_option or remote archive access. */
  51. static pid_t child_pid;
  52. /* Error recovery stuff */
  53. static int read_error_count;
  54. /* Have we hit EOF yet? */
  55. static bool hit_eof;
  56. static bool read_full_records = false;
  57. /* We're reading, but we just read the last block and it's time to update.
  58. Declared in update.c
  59. FIXME: Either eliminate it or move it to common.h.
  60. */
  61. extern bool time_to_start_writing;
  62. bool write_archive_to_stdout;
  63. static void (*flush_write_ptr) (size_t);
  64. static void (*flush_read_ptr) (void);
  65. char *volume_label;
  66. char *continued_file_name;
  67. uintmax_t continued_file_size;
  68. uintmax_t continued_file_offset;
  69. static int volno = 1; /* which volume of a multi-volume tape we're
  70. on */
  71. static int global_volno = 1; /* volume number to print in external
  72. messages */
  73. bool write_archive_to_stdout;
  74. /* Multi-volume tracking support */
  75. /* When creating a multi-volume archive, each 'bufmap' represents
  76. a member stored (perhaps partly) in the current record buffer.
  77. Bufmaps are form a single-linked list in chronological order.
  78. After flushing the record to the output media, all bufmaps that
  79. represent fully written members are removed from the list, the
  80. nblocks and sizeleft values in the bufmap_head and start values
  81. in all remaining bufmaps are updated. The information stored
  82. in bufmap_head is used to form the volume header.
  83. When reading from a multi-volume archive, the list degrades to a
  84. single element, which keeps information about the member currently
  85. being read. In that case the sizeleft member is updated explicitly
  86. from the extractor code by calling the mv_size_left function. The
  87. information from bufmap_head is compared with the volume header data
  88. to ensure that subsequent volumes are fed in the right order.
  89. */
  90. struct bufmap
  91. {
  92. struct bufmap *next; /* Pointer to the next map entry */
  93. size_t start; /* Offset of the first data block */
  94. char *file_name; /* Name of the stored file */
  95. off_t sizetotal; /* Size of the stored file */
  96. off_t sizeleft; /* Size left to read/write */
  97. size_t nblocks; /* Number of blocks written since reset */
  98. };
  99. static struct bufmap *bufmap_head, *bufmap_tail;
  100. /* This variable, when set, inhibits updating the bufmap chain after
  101. a write. This is necessary when writing extended POSIX headers. */
  102. static int inhibit_map;
  103. void
  104. mv_begin_write (const char *file_name, off_t totsize, off_t sizeleft)
  105. {
  106. if (multi_volume_option)
  107. {
  108. struct bufmap *bp = xmalloc (sizeof bp[0]);
  109. if (bufmap_tail)
  110. bufmap_tail->next = bp;
  111. else
  112. bufmap_head = bp;
  113. bufmap_tail = bp;
  114. bp->next = NULL;
  115. bp->start = current_block - record_start;
  116. bp->file_name = xstrdup (file_name);
  117. bp->sizetotal = totsize;
  118. bp->sizeleft = sizeleft;
  119. bp->nblocks = 0;
  120. }
  121. }
  122. static struct bufmap *
  123. bufmap_locate (size_t off)
  124. {
  125. struct bufmap *map;
  126. for (map = bufmap_head; map; map = map->next)
  127. {
  128. if (!map->next || off < map->next->start * BLOCKSIZE)
  129. break;
  130. }
  131. return map;
  132. }
  133. static void
  134. bufmap_free (struct bufmap *mark)
  135. {
  136. struct bufmap *map;
  137. for (map = bufmap_head; map && map != mark; )
  138. {
  139. struct bufmap *next = map->next;
  140. free (map->file_name);
  141. free (map);
  142. map = next;
  143. }
  144. bufmap_head = map;
  145. if (!bufmap_head)
  146. bufmap_tail = bufmap_head;
  147. }
  148. static void
  149. bufmap_reset (struct bufmap *map, ssize_t fixup)
  150. {
  151. bufmap_free (map);
  152. if (map)
  153. {
  154. for (; map; map = map->next)
  155. {
  156. map->start += fixup;
  157. map->nblocks = 0;
  158. }
  159. }
  160. }
  161. static struct tar_stat_info dummy;
  162. void
  163. buffer_write_global_xheader (void)
  164. {
  165. xheader_write_global (&dummy.xhdr);
  166. }
  167. void
  168. mv_begin_read (struct tar_stat_info *st)
  169. {
  170. mv_begin_write (st->orig_file_name, st->stat.st_size, st->stat.st_size);
  171. }
  172. void
  173. mv_end (void)
  174. {
  175. if (multi_volume_option)
  176. bufmap_free (NULL);
  177. }
  178. void
  179. mv_size_left (off_t size)
  180. {
  181. if (bufmap_head)
  182. bufmap_head->sizeleft = size;
  183. }
  184. /* Functions. */
  185. void
  186. clear_read_error_count (void)
  187. {
  188. read_error_count = 0;
  189. }
  190. /* Time-related functions */
  191. static double duration;
  192. void
  193. set_start_time (void)
  194. {
  195. gettime (&start_time);
  196. volume_start_time = start_time;
  197. last_stat_time = start_time;
  198. }
  199. static void
  200. set_volume_start_time (void)
  201. {
  202. gettime (&volume_start_time);
  203. last_stat_time = volume_start_time;
  204. }
  205. double
  206. compute_duration (void)
  207. {
  208. struct timespec now;
  209. gettime (&now);
  210. duration += ((now.tv_sec - last_stat_time.tv_sec)
  211. + (now.tv_nsec - last_stat_time.tv_nsec) / 1e9);
  212. gettime (&last_stat_time);
  213. return duration;
  214. }
  215. /* Compression detection */
  216. enum compress_type {
  217. ct_none, /* Unknown compression type */
  218. ct_tar, /* Plain tar file */
  219. ct_compress,
  220. ct_gzip,
  221. ct_bzip2,
  222. ct_lzip,
  223. ct_lzma,
  224. ct_lzop,
  225. ct_xz,
  226. ct_zstd
  227. };
  228. static enum compress_type archive_compression_type = ct_none;
  229. struct zip_magic
  230. {
  231. enum compress_type type;
  232. size_t length;
  233. char const *magic;
  234. };
  235. struct zip_program
  236. {
  237. enum compress_type type;
  238. char const *program;
  239. char const *option;
  240. };
  241. static struct zip_magic const magic[] = {
  242. { ct_none, 0, 0 },
  243. { ct_tar, 0, 0 },
  244. { ct_compress, 2, "\037\235" },
  245. { ct_gzip, 2, "\037\213" },
  246. { ct_bzip2, 3, "BZh" },
  247. { ct_lzip, 4, "LZIP" },
  248. { ct_lzma, 6, "\xFFLZMA" },
  249. { ct_lzma, 3, "\x5d\x00\x00" },
  250. { ct_lzop, 4, "\211LZO" },
  251. { ct_xz, 6, "\xFD" "7zXZ" },
  252. { ct_zstd, 4, "\x28\xB5\x2F\xFD" },
  253. };
  254. #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
  255. static struct zip_program zip_program[] = {
  256. { ct_compress, COMPRESS_PROGRAM, "-Z" },
  257. { ct_compress, GZIP_PROGRAM, "-z" },
  258. { ct_gzip, GZIP_PROGRAM, "-z" },
  259. { ct_bzip2, BZIP2_PROGRAM, "-j" },
  260. { ct_bzip2, "lbzip2", "-j" },
  261. { ct_lzip, LZIP_PROGRAM, "--lzip" },
  262. { ct_lzma, LZMA_PROGRAM, "--lzma" },
  263. { ct_lzma, XZ_PROGRAM, "-J" },
  264. { ct_lzop, LZOP_PROGRAM, "--lzop" },
  265. { ct_xz, XZ_PROGRAM, "-J" },
  266. { ct_zstd, ZSTD_PROGRAM, "--zstd" },
  267. };
  268. enum { n_zip_programs = sizeof zip_program / sizeof *zip_program };
  269. static struct zip_program const *
  270. find_zip_program (enum compress_type type, int *pstate)
  271. {
  272. int i;
  273. for (i = *pstate; i < n_zip_programs; i++)
  274. {
  275. if (zip_program[i].type == type)
  276. {
  277. *pstate = i + 1;
  278. return zip_program + i;
  279. }
  280. }
  281. *pstate = i;
  282. return NULL;
  283. }
  284. const char *
  285. first_decompress_program (int *pstate)
  286. {
  287. struct zip_program const *zp;
  288. *pstate = n_zip_programs;
  289. if (use_compress_program_option)
  290. return use_compress_program_option;
  291. if (archive_compression_type == ct_none)
  292. return NULL;
  293. *pstate = 0;
  294. zp = find_zip_program (archive_compression_type, pstate);
  295. return zp ? zp->program : NULL;
  296. }
  297. const char *
  298. next_decompress_program (int *pstate)
  299. {
  300. struct zip_program const *zp;
  301. zp = find_zip_program (archive_compression_type, pstate);
  302. return zp ? zp->program : NULL;
  303. }
  304. static const char *
  305. compress_option (enum compress_type type)
  306. {
  307. struct zip_program const *zp;
  308. int i = 0;
  309. zp = find_zip_program (type, &i);
  310. return zp ? zp->option : NULL;
  311. }
  312. /* Check if the file ARCHIVE is a compressed archive. */
  313. static enum compress_type
  314. check_compressed_archive (bool *pshort)
  315. {
  316. struct zip_magic const *p;
  317. bool sfr;
  318. bool temp;
  319. if (!pshort)
  320. pshort = &temp;
  321. /* Prepare global data needed for find_next_block: */
  322. record_end = record_start; /* set up for 1st record = # 0 */
  323. sfr = read_full_records;
  324. read_full_records = true; /* Suppress fatal error on reading a partial
  325. record */
  326. *pshort = find_next_block () == 0;
  327. /* Restore global values */
  328. read_full_records = sfr;
  329. if (record_start != record_end /* no files smaller than BLOCKSIZE */
  330. && (strcmp (record_start->header.magic, TMAGIC) == 0
  331. || strcmp (record_start->buffer + offsetof (struct posix_header,
  332. magic),
  333. OLDGNU_MAGIC) == 0)
  334. && tar_checksum (record_start, true) == HEADER_SUCCESS)
  335. /* Probably a valid header */
  336. return ct_tar;
  337. for (p = magic + 2; p < magic + NMAGIC; p++)
  338. if (memcmp (record_start->buffer, p->magic, p->length) == 0)
  339. return p->type;
  340. return ct_none;
  341. }
  342. /* Open an archive named archive_name_array[0]. Detect if it is
  343. a compressed archive of known type and use corresponding decompression
  344. program if so */
  345. static int
  346. open_compressed_archive (void)
  347. {
  348. archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
  349. MODE_RW, rsh_command_option);
  350. if (archive == -1)
  351. return archive;
  352. if (!multi_volume_option)
  353. {
  354. if (!use_compress_program_option)
  355. {
  356. bool shortfile;
  357. enum compress_type type = check_compressed_archive (&shortfile);
  358. switch (type)
  359. {
  360. case ct_tar:
  361. if (shortfile)
  362. ERROR ((0, 0, _("This does not look like a tar archive")));
  363. return archive;
  364. case ct_none:
  365. if (shortfile)
  366. ERROR ((0, 0, _("This does not look like a tar archive")));
  367. set_compression_program_by_suffix (archive_name_array[0], NULL);
  368. if (!use_compress_program_option)
  369. return archive;
  370. break;
  371. default:
  372. archive_compression_type = type;
  373. break;
  374. }
  375. }
  376. /* FD is not needed any more */
  377. rmtclose (archive);
  378. hit_eof = false; /* It might have been set by find_next_block in
  379. check_compressed_archive */
  380. /* Open compressed archive */
  381. child_pid = sys_child_open_for_uncompress ();
  382. read_full_records = true;
  383. }
  384. records_read = 0;
  385. record_end = record_start; /* set up for 1st record = # 0 */
  386. return archive;
  387. }
  388. static int
  389. print_stats (FILE *fp, const char *text, tarlong numbytes)
  390. {
  391. char abbr[LONGEST_HUMAN_READABLE + 1];
  392. char rate[LONGEST_HUMAN_READABLE + 1];
  393. int n = 0;
  394. int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
  395. if (text && text[0])
  396. n += fprintf (fp, "%s: ", gettext (text));
  397. return n + fprintf (fp, TARLONG_FORMAT " (%s, %s/s)",
  398. numbytes,
  399. human_readable (numbytes, abbr, human_opts, 1, 1),
  400. (0 < duration && numbytes / duration < (uintmax_t) -1
  401. ? human_readable (numbytes / duration, rate, human_opts, 1, 1)
  402. : "?"));
  403. }
  404. /* Format totals to file FP. FORMATS is an array of strings to output
  405. before each data item (bytes read, written, deleted, in that order).
  406. EOR is a delimiter to output after each item (used only if deleting
  407. from the archive), EOL is a delimiter to add at the end of the output
  408. line. */
  409. int
  410. format_total_stats (FILE *fp, char const *const *formats, int eor, int eol)
  411. {
  412. int n;
  413. switch (subcommand_option)
  414. {
  415. case CREATE_SUBCOMMAND:
  416. case CAT_SUBCOMMAND:
  417. case UPDATE_SUBCOMMAND:
  418. case APPEND_SUBCOMMAND:
  419. n = print_stats (fp, formats[TF_WRITE],
  420. prev_written + bytes_written);
  421. break;
  422. case DELETE_SUBCOMMAND:
  423. {
  424. char buf[UINTMAX_STRSIZE_BOUND];
  425. n = print_stats (fp, formats[TF_READ],
  426. records_read * record_size);
  427. fputc (eor, fp);
  428. n++;
  429. n += print_stats (fp, formats[TF_WRITE],
  430. prev_written + bytes_written);
  431. fputc (eor, fp);
  432. n++;
  433. if (formats[TF_DELETED] && formats[TF_DELETED][0])
  434. n += fprintf (fp, "%s: ", gettext (formats[TF_DELETED]));
  435. n += fprintf (fp, "%s",
  436. STRINGIFY_BIGINT ((records_read - records_skipped)
  437. * record_size
  438. - (prev_written + bytes_written), buf));
  439. }
  440. break;
  441. case EXTRACT_SUBCOMMAND:
  442. case LIST_SUBCOMMAND:
  443. case DIFF_SUBCOMMAND:
  444. n = print_stats (fp, _(formats[TF_READ]),
  445. records_read * record_size);
  446. break;
  447. default:
  448. abort ();
  449. }
  450. if (eol)
  451. {
  452. fputc (eol, fp);
  453. n++;
  454. }
  455. return n;
  456. }
  457. static char const *const default_total_format[] = {
  458. N_("Total bytes read"),
  459. /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*". */
  460. N_("Total bytes written"),
  461. N_("Total bytes deleted")
  462. };
  463. void
  464. print_total_stats (void)
  465. {
  466. format_total_stats (stderr, default_total_format, '\n', '\n');
  467. }
  468. /* Compute and return the block ordinal at current_block. */
  469. off_t
  470. current_block_ordinal (void)
  471. {
  472. return record_start_block + (current_block - record_start);
  473. }
  474. /* If the EOF flag is set, reset it, as well as current_block, etc. */
  475. void
  476. reset_eof (void)
  477. {
  478. if (hit_eof)
  479. {
  480. hit_eof = false;
  481. current_block = record_start;
  482. record_end = record_start + blocking_factor;
  483. access_mode = ACCESS_WRITE;
  484. }
  485. }
  486. /* Return the location of the next available input or output block.
  487. Return zero for EOF. Once we have returned zero, we just keep returning
  488. it, to avoid accidentally going on to the next file on the tape. */
  489. union block *
  490. find_next_block (void)
  491. {
  492. if (current_block == record_end)
  493. {
  494. if (hit_eof)
  495. return 0;
  496. flush_archive ();
  497. if (current_block == record_end)
  498. {
  499. hit_eof = true;
  500. return 0;
  501. }
  502. }
  503. return current_block;
  504. }
  505. /* Indicate that we have used all blocks up thru BLOCK. */
  506. void
  507. set_next_block_after (union block *block)
  508. {
  509. while (block >= current_block)
  510. current_block++;
  511. /* Do *not* flush the archive here. If we do, the same argument to
  512. set_next_block_after could mean the next block (if the input record
  513. is exactly one block long), which is not what is intended. */
  514. if (current_block > record_end)
  515. abort ();
  516. }
  517. /* Return the number of bytes comprising the space between POINTER
  518. through the end of the current buffer of blocks. This space is
  519. available for filling with data, or taking data from. POINTER is
  520. usually (but not always) the result of previous find_next_block call. */
  521. size_t
  522. available_space_after (union block *pointer)
  523. {
  524. return record_end->buffer - pointer->buffer;
  525. }
  526. /* Close file having descriptor FD, and abort if close unsuccessful. */
  527. void
  528. xclose (int fd)
  529. {
  530. if (close (fd) != 0)
  531. close_error (_("(pipe)"));
  532. }
  533. static void
  534. init_buffer (void)
  535. {
  536. if (! record_buffer_aligned[record_index])
  537. record_buffer_aligned[record_index] =
  538. page_aligned_alloc (&record_buffer[record_index], record_size);
  539. record_start = record_buffer_aligned[record_index];
  540. current_block = record_start;
  541. record_end = record_start + blocking_factor;
  542. }
  543. static void
  544. check_tty (enum access_mode mode)
  545. {
  546. /* Refuse to read archive from and write it to a tty. */
  547. if (strcmp (archive_name_array[0], "-") == 0
  548. && isatty (mode == ACCESS_READ ? STDIN_FILENO : STDOUT_FILENO))
  549. {
  550. FATAL_ERROR ((0, 0,
  551. mode == ACCESS_READ
  552. ? _("Refusing to read archive contents from terminal "
  553. "(missing -f option?)")
  554. : _("Refusing to write archive contents to terminal "
  555. "(missing -f option?)")));
  556. }
  557. }
  558. /* Fetch the status of the archive, accessed via WANTED_STATUS. */
  559. static void
  560. get_archive_status (enum access_mode wanted_access, bool backed_up_flag)
  561. {
  562. if (!sys_get_archive_stat ())
  563. {
  564. int saved_errno = errno;
  565. if (backed_up_flag)
  566. undo_last_backup ();
  567. errno = saved_errno;
  568. open_fatal (archive_name_array[0]);
  569. }
  570. seekable_archive
  571. = (! (multi_volume_option || use_compress_program_option)
  572. && (seek_option < 0
  573. ? (_isrmt (archive)
  574. || S_ISREG (archive_stat.st_mode)
  575. || S_ISBLK (archive_stat.st_mode))
  576. : seek_option));
  577. if (wanted_access != ACCESS_READ)
  578. sys_detect_dev_null_output ();
  579. SET_BINARY_MODE (archive);
  580. }
  581. /* Open an archive file. The argument specifies whether we are
  582. reading or writing, or both. */
  583. static void
  584. _open_archive (enum access_mode wanted_access)
  585. {
  586. bool backed_up_flag = false;
  587. if (record_size == 0)
  588. FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
  589. if (archive_names == 0)
  590. FATAL_ERROR ((0, 0, _("No archive name given")));
  591. tar_stat_destroy (&current_stat_info);
  592. record_index = 0;
  593. init_buffer ();
  594. /* When updating the archive, we start with reading. */
  595. access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
  596. check_tty (access_mode);
  597. read_full_records = read_full_records_option;
  598. records_read = 0;
  599. if (use_compress_program_option)
  600. {
  601. switch (wanted_access)
  602. {
  603. case ACCESS_READ:
  604. child_pid = sys_child_open_for_uncompress ();
  605. read_full_records = true;
  606. record_end = record_start; /* set up for 1st record = # 0 */
  607. break;
  608. case ACCESS_WRITE:
  609. child_pid = sys_child_open_for_compress ();
  610. break;
  611. case ACCESS_UPDATE:
  612. abort (); /* Should not happen */
  613. break;
  614. }
  615. if (!index_file_name
  616. && wanted_access == ACCESS_WRITE
  617. && strcmp (archive_name_array[0], "-") == 0)
  618. stdlis = stderr;
  619. }
  620. else if (strcmp (archive_name_array[0], "-") == 0)
  621. {
  622. read_full_records = true; /* could be a pipe, be safe */
  623. if (verify_option)
  624. FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
  625. switch (wanted_access)
  626. {
  627. case ACCESS_READ:
  628. {
  629. bool shortfile;
  630. enum compress_type type;
  631. archive = STDIN_FILENO;
  632. type = check_compressed_archive (&shortfile);
  633. if (type != ct_tar && type != ct_none)
  634. FATAL_ERROR ((0, 0,
  635. _("Archive is compressed. Use %s option"),
  636. compress_option (type)));
  637. if (shortfile)
  638. ERROR ((0, 0, _("This does not look like a tar archive")));
  639. }
  640. break;
  641. case ACCESS_WRITE:
  642. archive = STDOUT_FILENO;
  643. if (!index_file_name)
  644. stdlis = stderr;
  645. break;
  646. case ACCESS_UPDATE:
  647. archive = STDIN_FILENO;
  648. write_archive_to_stdout = true;
  649. record_end = record_start; /* set up for 1st record = # 0 */
  650. if (!index_file_name)
  651. stdlis = stderr;
  652. break;
  653. }
  654. }
  655. else
  656. switch (wanted_access)
  657. {
  658. case ACCESS_READ:
  659. archive = open_compressed_archive ();
  660. break;
  661. case ACCESS_WRITE:
  662. if (backup_option)
  663. {
  664. maybe_backup_file (archive_name_array[0], 1);
  665. backed_up_flag = true;
  666. }
  667. if (verify_option)
  668. archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
  669. MODE_RW, rsh_command_option);
  670. else
  671. archive = rmtcreat (archive_name_array[0], MODE_RW,
  672. rsh_command_option);
  673. break;
  674. case ACCESS_UPDATE:
  675. archive = rmtopen (archive_name_array[0],
  676. O_RDWR | O_CREAT | O_BINARY,
  677. MODE_RW, rsh_command_option);
  678. switch (check_compressed_archive (NULL))
  679. {
  680. case ct_none:
  681. case ct_tar:
  682. break;
  683. default:
  684. FATAL_ERROR ((0, 0,
  685. _("Cannot update compressed archives")));
  686. }
  687. break;
  688. }
  689. get_archive_status (wanted_access, backed_up_flag);
  690. switch (wanted_access)
  691. {
  692. case ACCESS_READ:
  693. find_next_block (); /* read it in, check for EOF */
  694. break;
  695. case ACCESS_UPDATE:
  696. case ACCESS_WRITE:
  697. records_written = 0;
  698. break;
  699. }
  700. }
  701. /* Perform a write to flush the buffer. */
  702. static ssize_t
  703. _flush_write (void)
  704. {
  705. ssize_t status;
  706. checkpoint_run (true);
  707. if (tape_length_option && tape_length_option <= bytes_written)
  708. {
  709. errno = ENOSPC;
  710. status = 0;
  711. }
  712. else if (dev_null_output)
  713. status = record_size;
  714. else
  715. status = sys_write_archive_buffer ();
  716. if (status && multi_volume_option && !inhibit_map)
  717. {
  718. struct bufmap *map = bufmap_locate (status);
  719. if (map)
  720. {
  721. size_t delta = status - map->start * BLOCKSIZE;
  722. ssize_t diff;
  723. map->nblocks += delta / BLOCKSIZE;
  724. if (delta > map->sizeleft)
  725. delta = map->sizeleft;
  726. map->sizeleft -= delta;
  727. if (map->sizeleft == 0)
  728. {
  729. diff = map->start + map->nblocks;
  730. map = map->next;
  731. }
  732. else
  733. diff = map->start;
  734. bufmap_reset (map, - diff);
  735. }
  736. }
  737. return status;
  738. }
  739. /* Handle write errors on the archive. Write errors are always fatal.
  740. Hitting the end of a volume does not cause a write error unless the
  741. write was the first record of the volume. */
  742. void
  743. archive_write_error (ssize_t status)
  744. {
  745. /* It might be useful to know how much was written before the error
  746. occurred. */
  747. if (totals_option)
  748. {
  749. int e = errno;
  750. print_total_stats ();
  751. errno = e;
  752. }
  753. write_fatal_details (*archive_name_cursor, status, record_size);
  754. }
  755. /* Handle read errors on the archive. If the read should be retried,
  756. return to the caller. */
  757. void
  758. archive_read_error (void)
  759. {
  760. read_error (*archive_name_cursor);
  761. if (record_start_block == 0)
  762. FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
  763. /* Read error in mid archive. We retry up to READ_ERROR_MAX times and
  764. then give up on reading the archive. */
  765. if (read_error_count++ > READ_ERROR_MAX)
  766. FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
  767. return;
  768. }
  769. static bool
  770. archive_is_dev (void)
  771. {
  772. struct stat st;
  773. if (fstat (archive, &st))
  774. {
  775. stat_diag (*archive_name_cursor);
  776. return false;
  777. }
  778. return S_ISBLK (st.st_mode) || S_ISCHR (st.st_mode);
  779. }
  780. static void
  781. short_read (size_t status)
  782. {
  783. size_t left; /* bytes left */
  784. char *more; /* pointer to next byte to read */
  785. more = record_start->buffer + status;
  786. left = record_size - status;
  787. if (left && left % BLOCKSIZE == 0
  788. && (warning_option & WARN_RECORD_SIZE)
  789. && record_start_block == 0 && status != 0
  790. && archive_is_dev ())
  791. {
  792. unsigned long rsize = status / BLOCKSIZE;
  793. WARN ((0, 0,
  794. ngettext ("Record size = %lu block",
  795. "Record size = %lu blocks",
  796. rsize),
  797. rsize));
  798. }
  799. while (left % BLOCKSIZE != 0
  800. || (left && status && read_full_records))
  801. {
  802. if (status)
  803. while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
  804. archive_read_error ();
  805. if (status == 0)
  806. break;
  807. if (! read_full_records)
  808. {
  809. unsigned long rest = record_size - left;
  810. FATAL_ERROR ((0, 0,
  811. ngettext ("Unaligned block (%lu byte) in archive",
  812. "Unaligned block (%lu bytes) in archive",
  813. rest),
  814. rest));
  815. }
  816. left -= status;
  817. more += status;
  818. }
  819. record_end = record_start + (record_size - left) / BLOCKSIZE;
  820. if (left == 0)
  821. records_read++;
  822. }
  823. /* Flush the current buffer to/from the archive. */
  824. void
  825. flush_archive (void)
  826. {
  827. size_t buffer_level;
  828. if (access_mode == ACCESS_READ && time_to_start_writing)
  829. {
  830. access_mode = ACCESS_WRITE;
  831. time_to_start_writing = false;
  832. backspace_output ();
  833. if (record_end - record_start < blocking_factor)
  834. {
  835. memset (record_end, 0,
  836. (blocking_factor - (record_end - record_start))
  837. * BLOCKSIZE);
  838. record_end = record_start + blocking_factor;
  839. return;
  840. }
  841. }
  842. buffer_level = current_block->buffer - record_start->buffer;
  843. record_start_block += record_end - record_start;
  844. current_block = record_start;
  845. record_end = record_start + blocking_factor;
  846. switch (access_mode)
  847. {
  848. case ACCESS_READ:
  849. flush_read ();
  850. break;
  851. case ACCESS_WRITE:
  852. flush_write_ptr (buffer_level);
  853. break;
  854. case ACCESS_UPDATE:
  855. abort ();
  856. }
  857. }
  858. /* Backspace the archive descriptor by one record worth. If it's a
  859. tape, MTIOCTOP will work. If it's something else, try to seek on
  860. it. If we can't seek, we lose! */
  861. static void
  862. backspace_output (void)
  863. {
  864. if (mtioseek (false, -1))
  865. return;
  866. {
  867. off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
  868. /* Seek back to the beginning of this record and start writing there. */
  869. position -= record_end->buffer - record_start->buffer;
  870. if (position < 0)
  871. position = 0;
  872. if (rmtlseek (archive, position, SEEK_SET) != position)
  873. {
  874. /* Lseek failed. Try a different method. */
  875. WARN ((0, 0,
  876. _("Cannot backspace archive file; it may be unreadable without -i")));
  877. /* Replace the first part of the record with NULs. */
  878. if (record_start->buffer != output_start)
  879. memset (record_start->buffer, 0,
  880. output_start - record_start->buffer);
  881. }
  882. }
  883. }
  884. off_t
  885. seek_archive (off_t size)
  886. {
  887. off_t start = current_block_ordinal ();
  888. off_t offset;
  889. off_t nrec, nblk;
  890. off_t skipped = (blocking_factor - (current_block - record_start))
  891. * BLOCKSIZE;
  892. if (size <= skipped)
  893. return 0;
  894. /* Compute number of records to skip */
  895. nrec = (size - skipped) / record_size;
  896. if (nrec == 0)
  897. return 0;
  898. offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
  899. if (offset < 0)
  900. return offset;
  901. if (offset % record_size)
  902. FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
  903. /* Convert to number of records */
  904. offset /= BLOCKSIZE;
  905. /* Compute number of skipped blocks */
  906. nblk = offset - start;
  907. /* Update buffering info */
  908. records_read += nblk / blocking_factor;
  909. record_start_block = offset - blocking_factor;
  910. current_block = record_end;
  911. return nblk;
  912. }
  913. /* Close the archive file. */
  914. void
  915. close_archive (void)
  916. {
  917. if (time_to_start_writing || access_mode == ACCESS_WRITE)
  918. {
  919. do
  920. flush_archive ();
  921. while (current_block > record_start);
  922. }
  923. compute_duration ();
  924. if (verify_option)
  925. verify_volume ();
  926. if (rmtclose (archive) != 0)
  927. close_error (*archive_name_cursor);
  928. sys_wait_for_child (child_pid, hit_eof);
  929. tar_stat_destroy (&current_stat_info);
  930. free (record_buffer[0]);
  931. free (record_buffer[1]);
  932. bufmap_free (NULL);
  933. }
  934. void
  935. write_fatal_details (char const *name, ssize_t status, size_t size)
  936. {
  937. write_error_details (name, status, size);
  938. if (rmtclose (archive) != 0)
  939. close_error (*archive_name_cursor);
  940. sys_wait_for_child (child_pid, false);
  941. fatal_exit ();
  942. }
  943. /* Called to initialize the global volume number. */
  944. void
  945. init_volume_number (void)
  946. {
  947. FILE *file = fopen (volno_file_option, "r");
  948. if (file)
  949. {
  950. if (fscanf (file, "%d", &global_volno) != 1
  951. || global_volno < 0)
  952. FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
  953. quotearg_colon (volno_file_option)));
  954. if (ferror (file))
  955. read_error (volno_file_option);
  956. if (fclose (file) != 0)
  957. close_error (volno_file_option);
  958. }
  959. else if (errno != ENOENT)
  960. open_error (volno_file_option);
  961. }
  962. /* Called to write out the closing global volume number. */
  963. void
  964. closeout_volume_number (void)
  965. {
  966. FILE *file = fopen (volno_file_option, "w");
  967. if (file)
  968. {
  969. fprintf (file, "%d\n", global_volno);
  970. if (ferror (file))
  971. write_error (volno_file_option);
  972. if (fclose (file) != 0)
  973. close_error (volno_file_option);
  974. }
  975. else
  976. open_error (volno_file_option);
  977. }
  978. static void
  979. increase_volume_number (void)
  980. {
  981. global_volno++;
  982. if (global_volno < 0)
  983. FATAL_ERROR ((0, 0, _("Volume number overflow")));
  984. volno++;
  985. }
  986. static void
  987. change_tape_menu (FILE *read_file)
  988. {
  989. char *input_buffer = NULL;
  990. size_t size = 0;
  991. bool stop = false;
  992. while (!stop)
  993. {
  994. fputc ('\007', stderr);
  995. fprintf (stderr,
  996. _("Prepare volume #%d for %s and hit return: "),
  997. global_volno + 1, quote (*archive_name_cursor));
  998. fflush (stderr);
  999. if (getline (&input_buffer, &size, read_file) <= 0)
  1000. {
  1001. WARN ((0, 0, _("EOF where user reply was expected")));
  1002. if (subcommand_option != EXTRACT_SUBCOMMAND
  1003. && subcommand_option != LIST_SUBCOMMAND
  1004. && subcommand_option != DIFF_SUBCOMMAND)
  1005. WARN ((0, 0, _("WARNING: Archive is incomplete")));
  1006. fatal_exit ();
  1007. }
  1008. if (input_buffer[0] == '\n'
  1009. || input_buffer[0] == 'y'
  1010. || input_buffer[0] == 'Y')
  1011. break;
  1012. switch (input_buffer[0])
  1013. {
  1014. case '?':
  1015. {
  1016. fprintf (stderr, _("\
  1017. n name Give a new file name for the next (and subsequent) volume(s)\n\
  1018. q Abort tar\n\
  1019. y or newline Continue operation\n"));
  1020. if (!restrict_option)
  1021. fprintf (stderr, _(" ! Spawn a subshell\n"));
  1022. fprintf (stderr, _(" ? Print this list\n"));
  1023. }
  1024. break;
  1025. case 'q':
  1026. /* Quit. */
  1027. WARN ((0, 0, _("No new volume; exiting.\n")));
  1028. if (subcommand_option != EXTRACT_SUBCOMMAND
  1029. && subcommand_option != LIST_SUBCOMMAND
  1030. && subcommand_option != DIFF_SUBCOMMAND)
  1031. WARN ((0, 0, _("WARNING: Archive is incomplete")));
  1032. fatal_exit ();
  1033. case 'n':
  1034. /* Get new file name. */
  1035. {
  1036. char *name;
  1037. char *cursor;
  1038. for (name = input_buffer + 1;
  1039. *name == ' ' || *name == '\t';
  1040. name++)
  1041. ;
  1042. for (cursor = name; *cursor && *cursor != '\n'; cursor++)
  1043. ;
  1044. *cursor = '\0';
  1045. if (name[0])
  1046. {
  1047. /* FIXME: the following allocation is never reclaimed. */
  1048. *archive_name_cursor = xstrdup (name);
  1049. stop = true;
  1050. }
  1051. else
  1052. fprintf (stderr, "%s",
  1053. _("File name not specified. Try again.\n"));
  1054. }
  1055. break;
  1056. case '!':
  1057. if (!restrict_option)
  1058. {
  1059. sys_spawn_shell ();
  1060. break;
  1061. }
  1062. FALLTHROUGH;
  1063. default:
  1064. fprintf (stderr, _("Invalid input. Type ? for help.\n"));
  1065. }
  1066. }
  1067. free (input_buffer);
  1068. }
  1069. /* We've hit the end of the old volume. Close it and open the next one.
  1070. Return nonzero on success.
  1071. */
  1072. static bool
  1073. new_volume (enum access_mode mode)
  1074. {
  1075. static FILE *read_file;
  1076. static int looped;
  1077. int prompt;
  1078. if (!read_file && !info_script_option)
  1079. /* FIXME: if fopen is used, it will never be closed. */
  1080. read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
  1081. if (now_verifying)
  1082. return false;
  1083. if (verify_option)
  1084. verify_volume ();
  1085. assign_null (&volume_label);
  1086. assign_null (&continued_file_name);
  1087. continued_file_size = continued_file_offset = 0;
  1088. current_block = record_start;
  1089. if (rmtclose (archive) != 0)
  1090. close_error (*archive_name_cursor);
  1091. archive_name_cursor++;
  1092. if (archive_name_cursor == archive_name_array + archive_names)
  1093. {
  1094. archive_name_cursor = archive_name_array;
  1095. looped = 1;
  1096. }
  1097. prompt = looped;
  1098. tryagain:
  1099. if (prompt)
  1100. {
  1101. /* We have to prompt from now on. */
  1102. if (info_script_option)
  1103. {
  1104. if (volno_file_option)
  1105. closeout_volume_number ();
  1106. if (sys_exec_info_script (archive_name_cursor, global_volno+1))
  1107. FATAL_ERROR ((0, 0, _("%s command failed"),
  1108. quote (info_script_option)));
  1109. }
  1110. else
  1111. change_tape_menu (read_file);
  1112. }
  1113. if (strcmp (archive_name_cursor[0], "-") == 0)
  1114. {
  1115. read_full_records = true;
  1116. archive = STDIN_FILENO;
  1117. }
  1118. else if (verify_option)
  1119. archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
  1120. rsh_command_option);
  1121. else
  1122. switch (mode)
  1123. {
  1124. case ACCESS_READ:
  1125. archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
  1126. rsh_command_option);
  1127. break;
  1128. case ACCESS_WRITE:
  1129. if (backup_option)
  1130. maybe_backup_file (*archive_name_cursor, 1);
  1131. archive = rmtcreat (*archive_name_cursor, MODE_RW,
  1132. rsh_command_option);
  1133. break;
  1134. case ACCESS_UPDATE:
  1135. archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
  1136. rsh_command_option);
  1137. break;
  1138. }
  1139. if (archive < 0)
  1140. {
  1141. open_warn (*archive_name_cursor);
  1142. if (!verify_option && mode == ACCESS_WRITE && backup_option)
  1143. undo_last_backup ();
  1144. prompt = 1;
  1145. goto tryagain;
  1146. }
  1147. get_archive_status (mode, false);
  1148. return true;
  1149. }
  1150. static bool
  1151. read_header0 (struct tar_stat_info *info)
  1152. {
  1153. enum read_header rc;
  1154. tar_stat_init (info);
  1155. rc = read_header (&current_header, info, read_header_auto);
  1156. if (rc == HEADER_SUCCESS)
  1157. {
  1158. set_next_block_after (current_header);
  1159. return true;
  1160. }
  1161. ERROR ((0, 0, _("This does not look like a tar archive")));
  1162. return false;
  1163. }
  1164. static bool
  1165. try_new_volume (void)
  1166. {
  1167. size_t status;
  1168. union block *header;
  1169. enum access_mode acc;
  1170. switch (subcommand_option)
  1171. {
  1172. case APPEND_SUBCOMMAND:
  1173. case CAT_SUBCOMMAND:
  1174. case UPDATE_SUBCOMMAND:
  1175. acc = ACCESS_UPDATE;
  1176. break;
  1177. default:
  1178. acc = ACCESS_READ;
  1179. break;
  1180. }
  1181. if (!new_volume (acc))
  1182. return true;
  1183. while ((status = rmtread (archive, record_start->buffer, record_size))
  1184. == SAFE_READ_ERROR)
  1185. archive_read_error ();
  1186. if (status != record_size)
  1187. short_read (status);
  1188. header = find_next_block ();
  1189. if (!header)
  1190. {
  1191. WARN ((0, 0, _("This does not look like a tar archive")));
  1192. return false;
  1193. }
  1194. switch (header->header.typeflag)
  1195. {
  1196. case XGLTYPE:
  1197. {
  1198. tar_stat_init (&dummy);
  1199. if (read_header (&header, &dummy, read_header_x_global)
  1200. != HEADER_SUCCESS_EXTENDED)
  1201. {
  1202. WARN ((0, 0, _("This does not look like a tar archive")));
  1203. return false;
  1204. }
  1205. xheader_decode (&dummy); /* decodes values from the global header */
  1206. tar_stat_destroy (&dummy);
  1207. /* The initial global header must be immediately followed by
  1208. an extended PAX header for the first member in this volume.
  1209. However, in some cases tar may split volumes in the middle
  1210. of a PAX header. This is incorrect, and should be fixed
  1211. in the future versions. In the meantime we must be
  1212. prepared to correctly list and extract such archives.
  1213. If this happens, the following call to read_header returns
  1214. HEADER_FAILURE, which is ignored.
  1215. See also tests/multiv07.at */
  1216. switch (read_header (&header, &dummy, read_header_auto))
  1217. {
  1218. case HEADER_SUCCESS:
  1219. set_next_block_after (header);
  1220. break;
  1221. case HEADER_FAILURE:
  1222. break;
  1223. default:
  1224. WARN ((0, 0, _("This does not look like a tar archive")));
  1225. return false;
  1226. }
  1227. break;
  1228. }
  1229. case GNUTYPE_VOLHDR:
  1230. if (!read_header0 (&dummy))
  1231. return false;
  1232. tar_stat_destroy (&dummy);
  1233. ASSIGN_STRING_N (&volume_label, current_header->header.name);
  1234. set_next_block_after (header);
  1235. header = find_next_block ();
  1236. if (! (header && header->header.typeflag == GNUTYPE_MULTIVOL))
  1237. break;
  1238. FALLTHROUGH;
  1239. case GNUTYPE_MULTIVOL:
  1240. if (!read_header0 (&dummy))
  1241. return false;
  1242. tar_stat_destroy (&dummy);
  1243. ASSIGN_STRING_N (&continued_file_name, current_header->header.name);
  1244. continued_file_size =
  1245. UINTMAX_FROM_HEADER (current_header->header.size);
  1246. continued_file_offset =
  1247. UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset);
  1248. break;
  1249. default:
  1250. break;
  1251. }
  1252. if (bufmap_head)
  1253. {
  1254. uintmax_t s;
  1255. if (!continued_file_name)
  1256. {
  1257. WARN ((0, 0, _("%s is not continued on this volume"),
  1258. quote (bufmap_head->file_name)));
  1259. return false;
  1260. }
  1261. if (strcmp (continued_file_name, bufmap_head->file_name))
  1262. {
  1263. if ((archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
  1264. && strlen (bufmap_head->file_name) >= NAME_FIELD_SIZE
  1265. && strncmp (continued_file_name, bufmap_head->file_name,
  1266. NAME_FIELD_SIZE) == 0)
  1267. WARN ((0, 0,
  1268. _("%s is possibly continued on this volume: header contains truncated name"),
  1269. quote (bufmap_head->file_name)));
  1270. else
  1271. {
  1272. WARN ((0, 0, _("%s is not continued on this volume"),
  1273. quote (bufmap_head->file_name)));
  1274. return false;
  1275. }
  1276. }
  1277. s = continued_file_size + continued_file_offset;
  1278. if (bufmap_head->sizetotal != s || s < continued_file_offset)
  1279. {
  1280. char totsizebuf[UINTMAX_STRSIZE_BOUND];
  1281. char s1buf[UINTMAX_STRSIZE_BOUND];
  1282. char s2buf[UINTMAX_STRSIZE_BOUND];
  1283. WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
  1284. quote (continued_file_name),
  1285. STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
  1286. STRINGIFY_BIGINT (continued_file_size, s1buf),
  1287. STRINGIFY_BIGINT (continued_file_offset, s2buf)));
  1288. return false;
  1289. }
  1290. if (bufmap_head->sizetotal - bufmap_head->sizeleft !=
  1291. continued_file_offset)
  1292. {
  1293. char totsizebuf[UINTMAX_STRSIZE_BOUND];
  1294. char s1buf[UINTMAX_STRSIZE_BOUND];
  1295. char s2buf[UINTMAX_STRSIZE_BOUND];
  1296. WARN ((0, 0, _("This volume is out of sequence (%s - %s != %s)"),
  1297. STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
  1298. STRINGIFY_BIGINT (bufmap_head->sizeleft, s1buf),
  1299. STRINGIFY_BIGINT (continued_file_offset, s2buf)));
  1300. return false;
  1301. }
  1302. }
  1303. increase_volume_number ();
  1304. return true;
  1305. }
  1306. #define VOLUME_TEXT " Volume "
  1307. #define VOLUME_TEXT_LEN (sizeof VOLUME_TEXT - 1)
  1308. char *
  1309. drop_volume_label_suffix (const char *label)
  1310. {
  1311. const char *p;
  1312. size_t len = strlen (label);
  1313. if (len < 1)
  1314. return NULL;
  1315. for (p = label + len - 1; p > label && isdigit ((unsigned char) *p); p--)
  1316. ;
  1317. if (p > label && p - (VOLUME_TEXT_LEN - 1) > label)
  1318. {
  1319. p -= VOLUME_TEXT_LEN - 1;
  1320. if (memcmp (p, VOLUME_TEXT, VOLUME_TEXT_LEN) == 0)
  1321. {
  1322. char *s = xmalloc ((len = p - label) + 1);
  1323. memcpy (s, label, len);
  1324. s[len] = 0;
  1325. return s;
  1326. }
  1327. }
  1328. return NULL;
  1329. }
  1330. /* Check LABEL against the volume label, seen as a globbing
  1331. pattern. Return true if the pattern matches. In case of failure,
  1332. retry matching a volume sequence number before giving up in
  1333. multi-volume mode. */
  1334. static bool
  1335. check_label_pattern (const char *label)
  1336. {
  1337. char *string;
  1338. bool result = false;
  1339. if (fnmatch (volume_label_option, label, 0) == 0)
  1340. return true;
  1341. if (!multi_volume_option)
  1342. return false;
  1343. string = drop_volume_label_suffix (label);
  1344. if (string)
  1345. {
  1346. result = fnmatch (string, volume_label_option, 0) == 0;
  1347. free (string);
  1348. }
  1349. return result;
  1350. }
  1351. /* Check if the next block contains a volume label and if this matches
  1352. the one given in the command line */
  1353. static void
  1354. match_volume_label (void)
  1355. {
  1356. if (!volume_label)
  1357. {
  1358. union block *label = find_next_block ();
  1359. if (!label)
  1360. FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
  1361. quote (volume_label_option)));
  1362. if (label->header.typeflag == GNUTYPE_VOLHDR)
  1363. {
  1364. ASSIGN_STRING_N (&volume_label, label->header.name);
  1365. }
  1366. else if (label->header.typeflag == XGLTYPE)
  1367. {
  1368. struct tar_stat_info st;
  1369. tar_stat_init (&st);
  1370. xheader_read (&st.xhdr, label,
  1371. OFF_FROM_HEADER (label->header.size));
  1372. xheader_decode (&st);
  1373. tar_stat_destroy (&st);
  1374. }
  1375. }
  1376. if (!volume_label)
  1377. FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
  1378. quote (volume_label_option)));
  1379. if (!check_label_pattern (volume_label))
  1380. FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
  1381. quote_n (0, volume_label),
  1382. quote_n (1, volume_label_option)));
  1383. }
  1384. /* Mark the archive with volume label STR. */
  1385. static void
  1386. _write_volume_label (const char *str)
  1387. {
  1388. if (archive_format == POSIX_FORMAT)
  1389. xheader_store ("GNU.volume.label", &dummy, str);
  1390. else
  1391. {
  1392. union block *label = find_next_block ();
  1393. assume (label);
  1394. memset (label, 0, BLOCKSIZE);
  1395. strcpy (label->header.name, str);
  1396. assign_string (&current_stat_info.file_name, label->header.name);
  1397. current_stat_info.had_trailing_slash =
  1398. strip_trailing_slashes (current_stat_info.file_name);
  1399. label->header.typeflag = GNUTYPE_VOLHDR;
  1400. TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
  1401. finish_header (&current_stat_info, label, -1);
  1402. set_next_block_after (label);
  1403. }
  1404. }
  1405. #define VOL_SUFFIX "Volume"
  1406. /* Add a volume label to a part of multi-volume archive */
  1407. static void
  1408. add_volume_label (void)
  1409. {
  1410. char buf[UINTMAX_STRSIZE_BOUND];
  1411. char *p = STRINGIFY_BIGINT (volno, buf);
  1412. char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
  1413. + strlen (p) + 2);
  1414. sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
  1415. _write_volume_label (s);
  1416. free (s);
  1417. }
  1418. static void
  1419. add_chunk_header (struct bufmap *map)
  1420. {
  1421. if (archive_format == POSIX_FORMAT)
  1422. {
  1423. union block *blk;
  1424. struct tar_stat_info st;
  1425. memset (&st, 0, sizeof st);
  1426. st.orig_file_name = st.file_name = map->file_name;
  1427. st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
  1428. st.stat.st_uid = getuid ();
  1429. st.stat.st_gid = getgid ();
  1430. st.orig_file_name = xheader_format_name (&st,
  1431. "%d/GNUFileParts/%f.%n",
  1432. volno);
  1433. st.file_name = st.orig_file_name;
  1434. st.archive_file_size = st.stat.st_size = map->sizeleft;
  1435. blk = start_header (&st);
  1436. if (!blk)
  1437. abort (); /* FIXME */
  1438. simple_finish_header (write_extended (false, &st, blk));
  1439. free (st.orig_file_name);
  1440. }
  1441. }
  1442. /* Add a volume label to the current archive */
  1443. static void
  1444. write_volume_label (void)
  1445. {
  1446. if (multi_volume_option)
  1447. add_volume_label ();
  1448. else
  1449. _write_volume_label (volume_label_option);
  1450. }
  1451. /* Write GNU multi-volume header */
  1452. static void
  1453. gnu_add_multi_volume_header (struct bufmap *map)
  1454. {
  1455. int tmp;
  1456. union block *block = find_next_block ();
  1457. size_t len = strlen (map->file_name);
  1458. if (len > NAME_FIELD_SIZE)
  1459. {
  1460. WARN ((0, 0,
  1461. _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
  1462. quotearg_colon (map->file_name)));
  1463. len = NAME_FIELD_SIZE;
  1464. }
  1465. memset (block, 0, BLOCKSIZE);
  1466. memcpy (block->header.name, map->file_name, len);
  1467. block->header.typeflag = GNUTYPE_MULTIVOL;
  1468. OFF_TO_CHARS (map->sizeleft, block->header.size);
  1469. OFF_TO_CHARS (map->sizetotal - map->sizeleft,
  1470. block->oldgnu_header.offset);
  1471. tmp = verbose_option;
  1472. verbose_option = 0;
  1473. finish_header (&current_stat_info, block, -1);
  1474. verbose_option = tmp;
  1475. set_next_block_after (block);
  1476. }
  1477. /* Add a multi volume header to the current archive. The exact header format
  1478. depends on the archive format. */
  1479. static void
  1480. add_multi_volume_header (struct bufmap *map)
  1481. {
  1482. if (archive_format == POSIX_FORMAT)
  1483. {
  1484. off_t d = map->sizetotal - map->sizeleft;
  1485. xheader_store ("GNU.volume.filename", &dummy, map->file_name);
  1486. xheader_store ("GNU.volume.size", &dummy, &map->sizeleft);
  1487. xheader_store ("GNU.volume.offset", &dummy, &d);
  1488. }
  1489. else
  1490. gnu_add_multi_volume_header (map);
  1491. }
  1492. /* Low-level flush functions */
  1493. /* Simple flush read (no multi-volume or label extensions) */
  1494. static void
  1495. simple_flush_read (void)
  1496. {
  1497. size_t status; /* result from system call */
  1498. checkpoint_run (false);
  1499. /* Clear the count of errors. This only applies to a single call to
  1500. flush_read. */
  1501. read_error_count = 0; /* clear error count */
  1502. if (write_archive_to_stdout && record_start_block != 0)
  1503. {
  1504. archive = STDOUT_FILENO;
  1505. status = sys_write_archive_buffer ();
  1506. archive = STDIN_FILENO;
  1507. if (status != record_size)
  1508. archive_write_error (status);
  1509. }
  1510. for (;;)
  1511. {
  1512. status = rmtread (archive, record_start->buffer, record_size);
  1513. if (status == record_size)
  1514. {
  1515. records_read++;
  1516. return;
  1517. }
  1518. if (status == SAFE_READ_ERROR)
  1519. {
  1520. archive_read_error ();
  1521. continue; /* try again */
  1522. }
  1523. break;
  1524. }
  1525. short_read (status);
  1526. }
  1527. /* Simple flush write (no multi-volume or label extensions) */
  1528. static void
  1529. simple_flush_write (MAYBE_UNUSED size_t level)
  1530. {
  1531. ssize_t status;
  1532. status = _flush_write ();
  1533. if (status != record_size)
  1534. archive_write_error (status);
  1535. else
  1536. {
  1537. records_written++;
  1538. bytes_written += status;
  1539. }
  1540. }
  1541. /* GNU flush functions. These support multi-volume and archive labels in
  1542. GNU and PAX archive formats. */
  1543. static void
  1544. _gnu_flush_read (void)
  1545. {
  1546. size_t status; /* result from system call */
  1547. checkpoint_run (false);
  1548. /* Clear the count of errors. This only applies to a single call to
  1549. flush_read. */
  1550. read_error_count = 0; /* clear error count */
  1551. if (write_archive_to_stdout && record_start_block != 0)
  1552. {
  1553. archive = STDOUT_FILENO;
  1554. status = sys_write_archive_buffer ();
  1555. archive = STDIN_FILENO;
  1556. if (status != record_size)
  1557. archive_write_error (status);
  1558. }
  1559. for (;;)
  1560. {
  1561. status = rmtread (archive, record_start->buffer, record_size);
  1562. if (status == record_size)
  1563. {
  1564. records_read++;
  1565. return;
  1566. }
  1567. /* The condition below used to include
  1568. || (status > 0 && !read_full_records)
  1569. This is incorrect since even if new_volume() succeeds, the
  1570. subsequent call to rmtread will overwrite the chunk of data
  1571. already read in the buffer, so the processing will fail */
  1572. if ((status == 0
  1573. || (status == SAFE_READ_ERROR && errno == ENOSPC))
  1574. && multi_volume_option)
  1575. {
  1576. while (!try_new_volume ())
  1577. ;
  1578. if (current_block == record_end)
  1579. /* Necessary for blocking_factor == 1 */
  1580. flush_archive();
  1581. return;
  1582. }
  1583. else if (status == SAFE_READ_ERROR)
  1584. {
  1585. archive_read_error ();
  1586. continue;
  1587. }
  1588. break;
  1589. }
  1590. short_read (status);
  1591. }
  1592. static void
  1593. gnu_flush_read (void)
  1594. {
  1595. flush_read_ptr = simple_flush_read; /* Avoid recursion */
  1596. _gnu_flush_read ();
  1597. flush_read_ptr = gnu_flush_read;
  1598. }
  1599. static void
  1600. _gnu_flush_write (size_t buffer_level)
  1601. {
  1602. ssize_t status;
  1603. union block *header;
  1604. char *copy_ptr;
  1605. size_t copy_size;
  1606. size_t bufsize;
  1607. struct bufmap *map;
  1608. status = _flush_write ();
  1609. if (status != record_size && !multi_volume_option)
  1610. archive_write_error (status);
  1611. else
  1612. {
  1613. if (status)
  1614. records_written++;
  1615. bytes_written += status;
  1616. }
  1617. if (status == record_size)
  1618. {
  1619. return;
  1620. }
  1621. map = bufmap_locate (status);
  1622. if (status % BLOCKSIZE)
  1623. {
  1624. ERROR ((0, 0, _("write did not end on a block boundary")));
  1625. archive_write_error (status);
  1626. }
  1627. /* In multi-volume mode. */
  1628. /* ENXIO is for the UNIX PC. */
  1629. if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
  1630. archive_write_error (status);
  1631. if (!new_volume (ACCESS_WRITE))
  1632. return;
  1633. tar_stat_destroy (&dummy);
  1634. increase_volume_number ();
  1635. prev_written += bytes_written;
  1636. bytes_written = 0;
  1637. copy_ptr = record_start->buffer + status;
  1638. copy_size = buffer_level - status;
  1639. /* Switch to the next buffer */
  1640. record_index = !record_index;
  1641. init_buffer ();
  1642. inhibit_map = 1;
  1643. if (volume_label_option)
  1644. add_volume_label ();
  1645. if (map)
  1646. add_multi_volume_header (map);
  1647. write_extended (true, &dummy, find_next_block ());
  1648. tar_stat_destroy (&dummy);
  1649. if (map)
  1650. add_chunk_header (map);
  1651. header = find_next_block ();
  1652. bufmap_reset (map, header - record_start);
  1653. bufsize = available_space_after (header);
  1654. inhibit_map = 0;
  1655. while (bufsize < copy_size)
  1656. {
  1657. memcpy (header->buffer, copy_ptr, bufsize);
  1658. copy_ptr += bufsize;
  1659. copy_size -= bufsize;
  1660. set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
  1661. header = find_next_block ();
  1662. bufsize = available_space_after (header);
  1663. }
  1664. memcpy (header->buffer, copy_ptr, copy_size);
  1665. memset (header->buffer + copy_size, 0, bufsize - copy_size);
  1666. set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
  1667. find_next_block ();
  1668. }
  1669. static void
  1670. gnu_flush_write (size_t buffer_level)
  1671. {
  1672. flush_write_ptr = simple_flush_write; /* Avoid recursion */
  1673. _gnu_flush_write (buffer_level);
  1674. flush_write_ptr = gnu_flush_write;
  1675. }
  1676. void
  1677. flush_read (void)
  1678. {
  1679. flush_read_ptr ();
  1680. }
  1681. void
  1682. flush_write (void)
  1683. {
  1684. flush_write_ptr (record_size);
  1685. }
  1686. void
  1687. open_archive (enum access_mode wanted_access)
  1688. {
  1689. flush_read_ptr = gnu_flush_read;
  1690. flush_write_ptr = gnu_flush_write;
  1691. _open_archive (wanted_access);
  1692. switch (wanted_access)
  1693. {
  1694. case ACCESS_READ:
  1695. case ACCESS_UPDATE:
  1696. if (volume_label_option)
  1697. match_volume_label ();
  1698. break;
  1699. case ACCESS_WRITE:
  1700. records_written = 0;
  1701. if (volume_label_option)
  1702. write_volume_label ();
  1703. break;
  1704. }
  1705. set_volume_start_time ();
  1706. }