PostgreSQL Source Code  git master
pg_backup_tar.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_backup_tar.c
4  *
5  * This file is copied from the 'files' format file, but dumps data into
6  * one temp file then sends it to the output TAR archive.
7  *
8  * The tar format also includes a 'restore.sql' script which is there for
9  * the benefit of humans. This script is never used by pg_restore.
10  *
11  * NOTE: If you untar the created 'tar' file, the resulting files are
12  * compatible with the 'directory' format. Please keep the two formats in
13  * sync.
14  *
15  * See the headers to pg_backup_directory & pg_restore for more details.
16  *
17  * Copyright (c) 2000, Philip Warner
18  * Rights are granted to use this software in any way so long
19  * as this notice is not removed.
20  *
21  * The author is not responsible for loss or damages that may
22  * result from its use.
23  *
24  *
25  * IDENTIFICATION
26  * src/bin/pg_dump/pg_backup_tar.c
27  *
28  *-------------------------------------------------------------------------
29  */
30 #include "postgres_fe.h"
31 
32 #include <sys/stat.h>
33 #include <ctype.h>
34 #include <limits.h>
35 #include <unistd.h>
36 
37 #include "common/file_utils.h"
38 #include "fe_utils/string_utils.h"
39 #include "pg_backup_archiver.h"
40 #include "pg_backup_tar.h"
41 #include "pg_backup_utils.h"
42 #include "pgtar.h"
43 
44 static void _ArchiveEntry(ArchiveHandle *AH, TocEntry *te);
45 static void _StartData(ArchiveHandle *AH, TocEntry *te);
46 static void _WriteData(ArchiveHandle *AH, const void *data, size_t dLen);
47 static void _EndData(ArchiveHandle *AH, TocEntry *te);
48 static int _WriteByte(ArchiveHandle *AH, const int i);
49 static int _ReadByte(ArchiveHandle *);
50 static void _WriteBuf(ArchiveHandle *AH, const void *buf, size_t len);
51 static void _ReadBuf(ArchiveHandle *AH, void *buf, size_t len);
52 static void _CloseArchive(ArchiveHandle *AH);
53 static void _PrintTocData(ArchiveHandle *AH, TocEntry *te);
54 static void _WriteExtraToc(ArchiveHandle *AH, TocEntry *te);
55 static void _ReadExtraToc(ArchiveHandle *AH, TocEntry *te);
56 static void _PrintExtraToc(ArchiveHandle *AH, TocEntry *te);
57 
58 static void _StartBlobs(ArchiveHandle *AH, TocEntry *te);
59 static void _StartBlob(ArchiveHandle *AH, TocEntry *te, Oid oid);
60 static void _EndBlob(ArchiveHandle *AH, TocEntry *te, Oid oid);
61 static void _EndBlobs(ArchiveHandle *AH, TocEntry *te);
62 
63 #define K_STD_BUF_SIZE 1024
64 
65 
66 typedef struct
67 {
68 #ifdef HAVE_LIBZ
69  gzFile zFH;
70 #else
71  FILE *zFH;
72 #endif
73  FILE *nFH;
74  FILE *tarFH;
75  FILE *tmpFH;
76  char *targetFile;
77  char mode;
81 } TAR_MEMBER;
82 
83 typedef struct
84 {
85  int hasSeek;
86  pgoff_t filePos;
88  FILE *tarFH;
94 } lclContext;
95 
96 typedef struct
97 {
99  char *filename;
100 } lclTocEntry;
101 
102 static void _LoadBlobs(ArchiveHandle *AH);
103 
104 static TAR_MEMBER *tarOpen(ArchiveHandle *AH, const char *filename, char mode);
105 static void tarClose(ArchiveHandle *AH, TAR_MEMBER *TH);
106 
107 #ifdef __NOT_USED__
108 static char *tarGets(char *buf, size_t len, TAR_MEMBER *th);
109 #endif
110 static int tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...) pg_attribute_printf(3, 4);
111 
112 static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER *th);
113 static TAR_MEMBER *_tarPositionTo(ArchiveHandle *AH, const char *filename);
114 static size_t tarRead(void *buf, size_t len, TAR_MEMBER *th);
115 static size_t tarWrite(const void *buf, size_t len, TAR_MEMBER *th);
116 static void _tarWriteHeader(TAR_MEMBER *th);
117 static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER *th);
118 static size_t _tarReadRaw(ArchiveHandle *AH, void *buf, size_t len, TAR_MEMBER *th, FILE *fh);
119 
120 static size_t _scriptOut(ArchiveHandle *AH, const void *buf, size_t len);
121 
122 /*
123  * Initializer
124  */
125 void
127 {
128  lclContext *ctx;
129 
130  /* Assuming static functions, this can be copied for each format. */
131  AH->ArchiveEntryPtr = _ArchiveEntry;
132  AH->StartDataPtr = _StartData;
133  AH->WriteDataPtr = _WriteData;
134  AH->EndDataPtr = _EndData;
135  AH->WriteBytePtr = _WriteByte;
136  AH->ReadBytePtr = _ReadByte;
137  AH->WriteBufPtr = _WriteBuf;
138  AH->ReadBufPtr = _ReadBuf;
139  AH->ClosePtr = _CloseArchive;
140  AH->ReopenPtr = NULL;
141  AH->PrintTocDataPtr = _PrintTocData;
142  AH->ReadExtraTocPtr = _ReadExtraToc;
143  AH->WriteExtraTocPtr = _WriteExtraToc;
144  AH->PrintExtraTocPtr = _PrintExtraToc;
145 
146  AH->StartBlobsPtr = _StartBlobs;
147  AH->StartBlobPtr = _StartBlob;
148  AH->EndBlobPtr = _EndBlob;
149  AH->EndBlobsPtr = _EndBlobs;
150  AH->ClonePtr = NULL;
151  AH->DeClonePtr = NULL;
152 
153  AH->WorkerJobDumpPtr = NULL;
154  AH->WorkerJobRestorePtr = NULL;
155 
156  /*
157  * Set up some special context used in compressing data.
158  */
159  ctx = (lclContext *) pg_malloc0(sizeof(lclContext));
160  AH->formatData = (void *) ctx;
161  ctx->filePos = 0;
162  ctx->isSpecialScript = 0;
163 
164  /* Initialize LO buffering */
165  AH->lo_buf_size = LOBBUFSIZE;
166  AH->lo_buf = (void *) pg_malloc(LOBBUFSIZE);
167 
168  /*
169  * Now open the tar file, and load the TOC if we're in read mode.
170  */
171  if (AH->mode == archModeWrite)
172  {
173  if (AH->fSpec && strcmp(AH->fSpec, "") != 0)
174  {
175  ctx->tarFH = fopen(AH->fSpec, PG_BINARY_W);
176  if (ctx->tarFH == NULL)
177  fatal("could not open TOC file \"%s\" for output: %m",
178  AH->fSpec);
179  }
180  else
181  {
182  ctx->tarFH = stdout;
183  if (ctx->tarFH == NULL)
184  fatal("could not open TOC file for output: %m");
185  }
186 
187  ctx->tarFHpos = 0;
188 
189  /*
190  * Make unbuffered since we will dup() it, and the buffers screw each
191  * other
192  */
193  /* setvbuf(ctx->tarFH, NULL, _IONBF, 0); */
194 
195  ctx->hasSeek = checkSeek(ctx->tarFH);
196 
197  /*
198  * We don't support compression because reading the files back is not
199  * possible since gzdopen uses buffered IO which totally screws file
200  * positioning.
201  */
202  if (AH->compression != 0)
203  fatal("compression is not supported by tar archive format");
204  }
205  else
206  { /* Read Mode */
207  if (AH->fSpec && strcmp(AH->fSpec, "") != 0)
208  {
209  ctx->tarFH = fopen(AH->fSpec, PG_BINARY_R);
210  if (ctx->tarFH == NULL)
211  fatal("could not open TOC file \"%s\" for input: %m",
212  AH->fSpec);
213  }
214  else
215  {
216  ctx->tarFH = stdin;
217  if (ctx->tarFH == NULL)
218  fatal("could not open TOC file for input: %m");
219  }
220 
221  /*
222  * Make unbuffered since we will dup() it, and the buffers screw each
223  * other
224  */
225  /* setvbuf(ctx->tarFH, NULL, _IONBF, 0); */
226 
227  ctx->tarFHpos = 0;
228 
229  ctx->hasSeek = checkSeek(ctx->tarFH);
230 
231  /*
232  * Forcibly unmark the header as read since we use the lookahead
233  * buffer
234  */
235  AH->readHeader = 0;
236 
237  ctx->FH = (void *) tarOpen(AH, "toc.dat", 'r');
238  ReadHead(AH);
239  ReadToc(AH);
240  tarClose(AH, ctx->FH); /* Nothing else in the file... */
241  }
242 }
243 
244 /*
245  * - Start a new TOC entry
246  * Setup the output file name.
247  */
248 static void
250 {
251  lclTocEntry *ctx;
252  char fn[K_STD_BUF_SIZE];
253 
254  ctx = (lclTocEntry *) pg_malloc0(sizeof(lclTocEntry));
255  if (te->dataDumper != NULL)
256  {
257 #ifdef HAVE_LIBZ
258  if (AH->compression == 0)
259  sprintf(fn, "%d.dat", te->dumpId);
260  else
261  sprintf(fn, "%d.dat.gz", te->dumpId);
262 #else
263  sprintf(fn, "%d.dat", te->dumpId);
264 #endif
265  ctx->filename = pg_strdup(fn);
266  }
267  else
268  {
269  ctx->filename = NULL;
270  ctx->TH = NULL;
271  }
272  te->formatData = (void *) ctx;
273 }
274 
275 static void
277 {
278  lclTocEntry *ctx = (lclTocEntry *) te->formatData;
279 
280  if (ctx->filename)
281  WriteStr(AH, ctx->filename);
282  else
283  WriteStr(AH, "");
284 }
285 
286 static void
288 {
289  lclTocEntry *ctx = (lclTocEntry *) te->formatData;
290 
291  if (ctx == NULL)
292  {
293  ctx = (lclTocEntry *) pg_malloc0(sizeof(lclTocEntry));
294  te->formatData = (void *) ctx;
295  }
296 
297  ctx->filename = ReadStr(AH);
298  if (strlen(ctx->filename) == 0)
299  {
300  free(ctx->filename);
301  ctx->filename = NULL;
302  }
303  ctx->TH = NULL;
304 }
305 
306 static void
308 {
309  lclTocEntry *ctx = (lclTocEntry *) te->formatData;
310 
311  if (AH->public.verbose && ctx->filename != NULL)
312  ahprintf(AH, "-- File: %s\n", ctx->filename);
313 }
314 
315 static void
317 {
318  lclTocEntry *tctx = (lclTocEntry *) te->formatData;
319 
320  tctx->TH = tarOpen(AH, tctx->filename, 'w');
321 }
322 
323 static TAR_MEMBER *
324 tarOpen(ArchiveHandle *AH, const char *filename, char mode)
325 {
326  lclContext *ctx = (lclContext *) AH->formatData;
327  TAR_MEMBER *tm;
328 
329 #ifdef HAVE_LIBZ
330  char fmode[14];
331 #endif
332 
333  if (mode == 'r')
334  {
335  tm = _tarPositionTo(AH, filename);
336  if (!tm) /* Not found */
337  {
338  if (filename)
339  {
340  /*
341  * Couldn't find the requested file. Future: do SEEK(0) and
342  * retry.
343  */
344  fatal("could not find file \"%s\" in archive", filename);
345  }
346  else
347  {
348  /* Any file OK, none left, so return NULL */
349  return NULL;
350  }
351  }
352 
353 #ifdef HAVE_LIBZ
354 
355  if (AH->compression == 0)
356  tm->nFH = ctx->tarFH;
357  else
358  fatal("compression is not supported by tar archive format");
359  /* tm->zFH = gzdopen(dup(fileno(ctx->tarFH)), "rb"); */
360 #else
361  tm->nFH = ctx->tarFH;
362 #endif
363  }
364  else
365  {
366  int old_umask;
367 
368  tm = pg_malloc0(sizeof(TAR_MEMBER));
369 
370  /*
371  * POSIX does not require, but permits, tmpfile() to restrict file
372  * permissions. Given an OS crash after we write data, the filesystem
373  * might retain the data but forget tmpfile()'s unlink(). If so, the
374  * file mode protects confidentiality of the data written.
375  */
376  old_umask = umask(S_IRWXG | S_IRWXO);
377 
378 #ifndef WIN32
379  tm->tmpFH = tmpfile();
380 #else
381 
382  /*
383  * On WIN32, tmpfile() generates a filename in the root directory,
384  * which requires administrative permissions on certain systems. Loop
385  * until we find a unique file name we can create.
386  */
387  while (1)
388  {
389  char *name;
390  int fd;
391 
392  name = _tempnam(NULL, "pg_temp_");
393  if (name == NULL)
394  break;
395  fd = open(name, O_RDWR | O_CREAT | O_EXCL | O_BINARY |
396  O_TEMPORARY, S_IRUSR | S_IWUSR);
397  free(name);
398 
399  if (fd != -1) /* created a file */
400  {
401  tm->tmpFH = fdopen(fd, "w+b");
402  break;
403  }
404  else if (errno != EEXIST) /* failure other than file exists */
405  break;
406  }
407 #endif
408 
409  if (tm->tmpFH == NULL)
410  fatal("could not generate temporary file name: %m");
411 
412  umask(old_umask);
413 
414 #ifdef HAVE_LIBZ
415 
416  if (AH->compression != 0)
417  {
418  sprintf(fmode, "wb%d", AH->compression);
419  tm->zFH = gzdopen(dup(fileno(tm->tmpFH)), fmode);
420  if (tm->zFH == NULL)
421  fatal("could not open temporary file");
422  }
423  else
424  tm->nFH = tm->tmpFH;
425 #else
426 
427  tm->nFH = tm->tmpFH;
428 #endif
429 
430  tm->AH = AH;
431  tm->targetFile = pg_strdup(filename);
432  }
433 
434  tm->mode = mode;
435  tm->tarFH = ctx->tarFH;
436 
437  return tm;
438 }
439 
440 static void
442 {
443  /*
444  * Close the GZ file since we dup'd. This will flush the buffers.
445  */
446  if (AH->compression != 0)
447  if (GZCLOSE(th->zFH) != 0)
448  fatal("could not close tar member");
449 
450  if (th->mode == 'w')
451  _tarAddFile(AH, th); /* This will close the temp file */
452 
453  /*
454  * else Nothing to do for normal read since we don't dup() normal file
455  * handle, and we don't use temp files.
456  */
457 
458  if (th->targetFile)
459  free(th->targetFile);
460 
461  th->nFH = NULL;
462  th->zFH = NULL;
463 }
464 
465 #ifdef __NOT_USED__
466 static char *
467 tarGets(char *buf, size_t len, TAR_MEMBER *th)
468 {
469  char *s;
470  size_t cnt = 0;
471  char c = ' ';
472  int eof = 0;
473 
474  /* Can't read past logical EOF */
475  if (len > (th->fileLen - th->pos))
476  len = th->fileLen - th->pos;
477 
478  while (cnt < len && c != '\n')
479  {
480  if (_tarReadRaw(th->AH, &c, 1, th, NULL) <= 0)
481  {
482  eof = 1;
483  break;
484  }
485  buf[cnt++] = c;
486  }
487 
488  if (eof && cnt == 0)
489  s = NULL;
490  else
491  {
492  buf[cnt++] = '\0';
493  s = buf;
494  }
495 
496  if (s)
497  {
498  len = strlen(s);
499  th->pos += len;
500  }
501 
502  return s;
503 }
504 #endif
505 
506 /*
507  * Just read bytes from the archive. This is the low level read routine
508  * that is used for ALL reads on a tar file.
509  */
510 static size_t
511 _tarReadRaw(ArchiveHandle *AH, void *buf, size_t len, TAR_MEMBER *th, FILE *fh)
512 {
513  lclContext *ctx = (lclContext *) AH->formatData;
514  size_t avail;
515  size_t used = 0;
516  size_t res = 0;
517 
518  avail = AH->lookaheadLen - AH->lookaheadPos;
519  if (avail > 0)
520  {
521  /* We have some lookahead bytes to use */
522  if (avail >= len) /* Just use the lookahead buffer */
523  used = len;
524  else
525  used = avail;
526 
527  /* Copy, and adjust buffer pos */
528  memcpy(buf, AH->lookahead + AH->lookaheadPos, used);
529  AH->lookaheadPos += used;
530 
531  /* Adjust required length */
532  len -= used;
533  }
534 
535  /* Read the file if len > 0 */
536  if (len > 0)
537  {
538  if (fh)
539  {
540  res = fread(&((char *) buf)[used], 1, len, fh);
541  if (res != len && !feof(fh))
542  READ_ERROR_EXIT(fh);
543  }
544  else if (th)
545  {
546  if (th->zFH)
547  {
548  res = GZREAD(&((char *) buf)[used], 1, len, th->zFH);
549  if (res != len && !GZEOF(th->zFH))
550  {
551 #ifdef HAVE_LIBZ
552  int errnum;
553  const char *errmsg = gzerror(th->zFH, &errnum);
554 
555  fatal("could not read from input file: %s",
556  errnum == Z_ERRNO ? strerror(errno) : errmsg);
557 #else
558  fatal("could not read from input file: %s",
559  strerror(errno));
560 #endif
561  }
562  }
563  else
564  {
565  res = fread(&((char *) buf)[used], 1, len, th->nFH);
566  if (res != len && !feof(th->nFH))
567  READ_ERROR_EXIT(th->nFH);
568  }
569  }
570  else
571  fatal("internal error -- neither th nor fh specified in _tarReadRaw()");
572  }
573 
574  ctx->tarFHpos += res + used;
575 
576  return (res + used);
577 }
578 
579 static size_t
580 tarRead(void *buf, size_t len, TAR_MEMBER *th)
581 {
582  size_t res;
583 
584  if (th->pos + len > th->fileLen)
585  len = th->fileLen - th->pos;
586 
587  if (len <= 0)
588  return 0;
589 
590  res = _tarReadRaw(th->AH, buf, len, th, NULL);
591 
592  th->pos += res;
593 
594  return res;
595 }
596 
597 static size_t
598 tarWrite(const void *buf, size_t len, TAR_MEMBER *th)
599 {
600  size_t res;
601 
602  if (th->zFH != NULL)
603  res = GZWRITE(buf, 1, len, th->zFH);
604  else
605  res = fwrite(buf, 1, len, th->nFH);
606 
607  th->pos += res;
608  return res;
609 }
610 
611 static void
612 _WriteData(ArchiveHandle *AH, const void *data, size_t dLen)
613 {
614  lclTocEntry *tctx = (lclTocEntry *) AH->currToc->formatData;
615 
616  if (tarWrite(data, dLen, tctx->TH) != dLen)
618 }
619 
620 static void
622 {
623  lclTocEntry *tctx = (lclTocEntry *) te->formatData;
624 
625  /* Close the file */
626  tarClose(AH, tctx->TH);
627  tctx->TH = NULL;
628 }
629 
630 /*
631  * Print data for a given file
632  */
633 static void
635 {
636  lclContext *ctx = (lclContext *) AH->formatData;
637  char buf[4096];
638  size_t cnt;
639  TAR_MEMBER *th;
640 
641  if (!filename)
642  return;
643 
644  th = tarOpen(AH, filename, 'r');
645  ctx->FH = th;
646 
647  while ((cnt = tarRead(buf, 4095, th)) > 0)
648  {
649  buf[cnt] = '\0';
650  ahwrite(buf, 1, cnt, AH);
651  }
652 
653  tarClose(AH, th);
654 }
655 
656 
657 /*
658  * Print data for a given TOC entry
659 */
660 static void
662 {
663  lclContext *ctx = (lclContext *) AH->formatData;
664  lclTocEntry *tctx = (lclTocEntry *) te->formatData;
665  int pos1;
666 
667  if (!tctx->filename)
668  return;
669 
670  /*
671  * If we're writing the special restore.sql script, emit a suitable
672  * command to include each table's data from the corresponding file.
673  *
674  * In the COPY case this is a bit klugy because the regular COPY command
675  * was already printed before we get control.
676  */
677  if (ctx->isSpecialScript)
678  {
679  if (te->copyStmt)
680  {
681  /* Abort the COPY FROM stdin */
682  ahprintf(AH, "\\.\n");
683 
684  /*
685  * The COPY statement should look like "COPY ... FROM stdin;\n",
686  * see dumpTableData().
687  */
688  pos1 = (int) strlen(te->copyStmt) - 13;
689  if (pos1 < 6 || strncmp(te->copyStmt, "COPY ", 5) != 0 ||
690  strcmp(te->copyStmt + pos1, " FROM stdin;\n") != 0)
691  fatal("unexpected COPY statement syntax: \"%s\"",
692  te->copyStmt);
693 
694  /* Emit all but the FROM part ... */
695  ahwrite(te->copyStmt, 1, pos1, AH);
696  /* ... and insert modified FROM */
697  ahprintf(AH, " FROM '$$PATH$$/%s';\n\n", tctx->filename);
698  }
699  else
700  {
701  /* --inserts mode, no worries, just include the data file */
702  ahprintf(AH, "\\i $$PATH$$/%s\n\n", tctx->filename);
703  }
704 
705  return;
706  }
707 
708  if (strcmp(te->desc, "BLOBS") == 0)
709  _LoadBlobs(AH);
710  else
711  _PrintFileData(AH, tctx->filename);
712 }
713 
714 static void
716 {
717  Oid oid;
718  lclContext *ctx = (lclContext *) AH->formatData;
719  TAR_MEMBER *th;
720  size_t cnt;
721  bool foundBlob = false;
722  char buf[4096];
723 
724  StartRestoreBlobs(AH);
725 
726  th = tarOpen(AH, NULL, 'r'); /* Open next file */
727  while (th != NULL)
728  {
729  ctx->FH = th;
730 
731  if (strncmp(th->targetFile, "blob_", 5) == 0)
732  {
733  oid = atooid(&th->targetFile[5]);
734  if (oid != 0)
735  {
736  pg_log_info("restoring large object with OID %u", oid);
737 
738  StartRestoreBlob(AH, oid, AH->public.ropt->dropSchema);
739 
740  while ((cnt = tarRead(buf, 4095, th)) > 0)
741  {
742  buf[cnt] = '\0';
743  ahwrite(buf, 1, cnt, AH);
744  }
745  EndRestoreBlob(AH, oid);
746  foundBlob = true;
747  }
748  tarClose(AH, th);
749  }
750  else
751  {
752  tarClose(AH, th);
753 
754  /*
755  * Once we have found the first blob, stop at the first non-blob
756  * entry (which will be 'blobs.toc'). This coding would eat all
757  * the rest of the archive if there are no blobs ... but this
758  * function shouldn't be called at all in that case.
759  */
760  if (foundBlob)
761  break;
762  }
763 
764  th = tarOpen(AH, NULL, 'r');
765  }
766  EndRestoreBlobs(AH);
767 }
768 
769 
770 static int
771 _WriteByte(ArchiveHandle *AH, const int i)
772 {
773  lclContext *ctx = (lclContext *) AH->formatData;
774  char b = i; /* Avoid endian problems */
775 
776  if (tarWrite(&b, 1, ctx->FH) != 1)
778 
779  ctx->filePos += 1;
780  return 1;
781 }
782 
783 static int
785 {
786  lclContext *ctx = (lclContext *) AH->formatData;
787  size_t res;
788  unsigned char c;
789 
790  res = tarRead(&c, 1, ctx->FH);
791  if (res != 1)
792  /* We already would have exited for errors on reads, must be EOF */
793  fatal("could not read from input file: end of file");
794  ctx->filePos += 1;
795  return c;
796 }
797 
798 static void
799 _WriteBuf(ArchiveHandle *AH, const void *buf, size_t len)
800 {
801  lclContext *ctx = (lclContext *) AH->formatData;
802 
803  if (tarWrite(buf, len, ctx->FH) != len)
805 
806  ctx->filePos += len;
807 }
808 
809 static void
810 _ReadBuf(ArchiveHandle *AH, void *buf, size_t len)
811 {
812  lclContext *ctx = (lclContext *) AH->formatData;
813 
814  if (tarRead(buf, len, ctx->FH) != len)
815  /* We already would have exited for errors on reads, must be EOF */
816  fatal("could not read from input file: end of file");
817 
818  ctx->filePos += len;
819 }
820 
821 static void
823 {
824  lclContext *ctx = (lclContext *) AH->formatData;
825  TAR_MEMBER *th;
826  RestoreOptions *ropt;
827  RestoreOptions *savRopt;
828  DumpOptions *savDopt;
829  int savVerbose,
830  i;
831 
832  if (AH->mode == archModeWrite)
833  {
834  /*
835  * Write the Header & TOC to the archive FIRST
836  */
837  th = tarOpen(AH, "toc.dat", 'w');
838  ctx->FH = th;
839  WriteHead(AH);
840  WriteToc(AH);
841  tarClose(AH, th); /* Not needed any more */
842 
843  /*
844  * Now send the data (tables & blobs)
845  */
846  WriteDataChunks(AH, NULL);
847 
848  /*
849  * Now this format wants to append a script which does a full restore
850  * if the files have been extracted.
851  */
852  th = tarOpen(AH, "restore.sql", 'w');
853 
854  tarPrintf(AH, th, "--\n"
855  "-- NOTE:\n"
856  "--\n"
857  "-- File paths need to be edited. Search for $$PATH$$ and\n"
858  "-- replace it with the path to the directory containing\n"
859  "-- the extracted data files.\n"
860  "--\n");
861 
862  AH->CustomOutPtr = _scriptOut;
863 
864  ctx->isSpecialScript = 1;
865  ctx->scriptTH = th;
866 
867  ropt = NewRestoreOptions();
868  memcpy(ropt, AH->public.ropt, sizeof(RestoreOptions));
869  ropt->filename = NULL;
870  ropt->dropSchema = 1;
871  ropt->compression = 0;
872  ropt->superuser = NULL;
873  ropt->suppressDumpWarnings = true;
874 
875  savDopt = AH->public.dopt;
876  savRopt = AH->public.ropt;
877 
878  SetArchiveOptions((Archive *) AH, NULL, ropt);
879 
880  savVerbose = AH->public.verbose;
881  AH->public.verbose = 0;
882 
883  RestoreArchive((Archive *) AH);
884 
885  SetArchiveOptions((Archive *) AH, savDopt, savRopt);
886 
887  AH->public.verbose = savVerbose;
888 
889  tarClose(AH, th);
890 
891  ctx->isSpecialScript = 0;
892 
893  /*
894  * EOF marker for tar files is two blocks of NULLs.
895  */
896  for (i = 0; i < 512 * 2; i++)
897  {
898  if (fputc(0, ctx->tarFH) == EOF)
900  }
901 
902  /* Sync the output file if one is defined */
903  if (AH->dosync && AH->fSpec)
904  (void) fsync_fname(AH->fSpec, false);
905  }
906 
907  AH->FH = NULL;
908 }
909 
910 static size_t
911 _scriptOut(ArchiveHandle *AH, const void *buf, size_t len)
912 {
913  lclContext *ctx = (lclContext *) AH->formatData;
914 
915  return tarWrite(buf, len, ctx->scriptTH);
916 }
917 
918 /*
919  * BLOB support
920  */
921 
922 /*
923  * Called by the archiver when starting to save all BLOB DATA (not schema).
924  * This routine should save whatever format-specific information is needed
925  * to read the BLOBs back into memory.
926  *
927  * It is called just prior to the dumper's DataDumper routine.
928  *
929  * Optional, but strongly recommended.
930  *
931  */
932 static void
934 {
935  lclContext *ctx = (lclContext *) AH->formatData;
936  char fname[K_STD_BUF_SIZE];
937 
938  sprintf(fname, "blobs.toc");
939  ctx->blobToc = tarOpen(AH, fname, 'w');
940 }
941 
942 /*
943  * Called by the archiver when the dumper calls StartBlob.
944  *
945  * Mandatory.
946  *
947  * Must save the passed OID for retrieval at restore-time.
948  */
949 static void
951 {
952  lclContext *ctx = (lclContext *) AH->formatData;
953  lclTocEntry *tctx = (lclTocEntry *) te->formatData;
954  char fname[255];
955  char *sfx;
956 
957  if (oid == 0)
958  fatal("invalid OID for large object (%u)", oid);
959 
960  if (AH->compression != 0)
961  sfx = ".gz";
962  else
963  sfx = "";
964 
965  sprintf(fname, "blob_%u.dat%s", oid, sfx);
966 
967  tarPrintf(AH, ctx->blobToc, "%u %s\n", oid, fname);
968 
969  tctx->TH = tarOpen(AH, fname, 'w');
970 }
971 
972 /*
973  * Called by the archiver when the dumper calls EndBlob.
974  *
975  * Optional.
976  *
977  */
978 static void
980 {
981  lclTocEntry *tctx = (lclTocEntry *) te->formatData;
982 
983  tarClose(AH, tctx->TH);
984 }
985 
986 /*
987  * Called by the archiver when finishing saving all BLOB DATA.
988  *
989  * Optional.
990  *
991  */
992 static void
994 {
995  lclContext *ctx = (lclContext *) AH->formatData;
996 
997  /* Write out a fake zero OID to mark end-of-blobs. */
998  /* WriteInt(AH, 0); */
999 
1000  tarClose(AH, ctx->blobToc);
1001 }
1002 
1003 
1004 
1005 /*------------
1006  * TAR Support
1007  *------------
1008  */
1009 
1010 static int
1011 tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...)
1012 {
1013  int save_errno = errno;
1014  char *p;
1015  size_t len = 128; /* initial assumption about buffer size */
1016  size_t cnt;
1017 
1018  for (;;)
1019  {
1020  va_list args;
1021 
1022  /* Allocate work buffer. */
1023  p = (char *) pg_malloc(len);
1024 
1025  /* Try to format the data. */
1026  errno = save_errno;
1027  va_start(args, fmt);
1028  cnt = pvsnprintf(p, len, fmt, args);
1029  va_end(args);
1030 
1031  if (cnt < len)
1032  break; /* success */
1033 
1034  /* Release buffer and loop around to try again with larger len. */
1035  free(p);
1036  len = cnt;
1037  }
1038 
1039  cnt = tarWrite(p, cnt, th);
1040  free(p);
1041  return (int) cnt;
1042 }
1043 
1044 bool
1046 {
1047  int sum;
1048  int chk = tarChecksum(header);
1049 
1050  sum = read_tar_number(&header[148], 8);
1051 
1052  if (sum != chk)
1053  return false;
1054 
1055  /* POSIX tar format */
1056  if (memcmp(&header[257], "ustar\0", 6) == 0 &&
1057  memcmp(&header[263], "00", 2) == 0)
1058  return true;
1059  /* GNU tar format */
1060  if (memcmp(&header[257], "ustar \0", 8) == 0)
1061  return true;
1062  /* not-quite-POSIX format written by pre-9.3 pg_dump */
1063  if (memcmp(&header[257], "ustar00\0", 8) == 0)
1064  return true;
1065 
1066  return false;
1067 }
1068 
1069 /* Given the member, write the TAR header & copy the file */
1070 static void
1072 {
1073  lclContext *ctx = (lclContext *) AH->formatData;
1074  FILE *tmp = th->tmpFH; /* Grab it for convenience */
1075  char buf[32768];
1076  size_t cnt;
1077  pgoff_t len = 0;
1078  size_t res;
1079  size_t i,
1080  pad;
1081 
1082  /*
1083  * Find file len & go back to start.
1084  */
1085  fseeko(tmp, 0, SEEK_END);
1086  th->fileLen = ftello(tmp);
1087  if (th->fileLen < 0)
1088  fatal("could not determine seek position in archive file: %m");
1089  fseeko(tmp, 0, SEEK_SET);
1090 
1091  _tarWriteHeader(th);
1092 
1093  while ((cnt = fread(buf, 1, sizeof(buf), tmp)) > 0)
1094  {
1095  if ((res = fwrite(buf, 1, cnt, th->tarFH)) != cnt)
1097  len += res;
1098  }
1099  if (!feof(tmp))
1100  READ_ERROR_EXIT(tmp);
1101 
1102  if (fclose(tmp) != 0) /* This *should* delete it... */
1103  fatal("could not close temporary file: %m");
1104 
1105  if (len != th->fileLen)
1106  {
1107  char buf1[32],
1108  buf2[32];
1109 
1110  snprintf(buf1, sizeof(buf1), INT64_FORMAT, (int64) len);
1111  snprintf(buf2, sizeof(buf2), INT64_FORMAT, (int64) th->fileLen);
1112  fatal("actual file length (%s) does not match expected (%s)",
1113  buf1, buf2);
1114  }
1115 
1116  pad = ((len + 511) & ~511) - len;
1117  for (i = 0; i < pad; i++)
1118  {
1119  if (fputc('\0', th->tarFH) == EOF)
1121  }
1122 
1123  ctx->tarFHpos += len + pad;
1124 }
1125 
1126 /* Locate the file in the archive, read header and position to data */
1127 static TAR_MEMBER *
1129 {
1130  lclContext *ctx = (lclContext *) AH->formatData;
1131  TAR_MEMBER *th = pg_malloc0(sizeof(TAR_MEMBER));
1132  char c;
1133  char header[512];
1134  size_t i,
1135  len,
1136  blks;
1137  int id;
1138 
1139  th->AH = AH;
1140 
1141  /* Go to end of current file, if any */
1142  if (ctx->tarFHpos != 0)
1143  {
1144  char buf1[100],
1145  buf2[100];
1146 
1147  snprintf(buf1, sizeof(buf1), INT64_FORMAT, (int64) ctx->tarFHpos);
1148  snprintf(buf2, sizeof(buf2), INT64_FORMAT, (int64) ctx->tarNextMember);
1149  pg_log_debug("moving from position %s to next member at file position %s",
1150  buf1, buf2);
1151 
1152  while (ctx->tarFHpos < ctx->tarNextMember)
1153  _tarReadRaw(AH, &c, 1, NULL, ctx->tarFH);
1154  }
1155 
1156  {
1157  char buf[100];
1158 
1159  snprintf(buf, sizeof(buf), INT64_FORMAT, (int64) ctx->tarFHpos);
1160  pg_log_debug("now at file position %s", buf);
1161  }
1162 
1163  /* We are at the start of the file, or at the next member */
1164 
1165  /* Get the header */
1166  if (!_tarGetHeader(AH, th))
1167  {
1168  if (filename)
1169  fatal("could not find header for file \"%s\" in tar archive", filename);
1170  else
1171  {
1172  /*
1173  * We're just scanning the archive for the next file, so return
1174  * null
1175  */
1176  free(th);
1177  return NULL;
1178  }
1179  }
1180 
1181  while (filename != NULL && strcmp(th->targetFile, filename) != 0)
1182  {
1183  pg_log_debug("skipping tar member %s", th->targetFile);
1184 
1185  id = atoi(th->targetFile);
1186  if ((TocIDRequired(AH, id) & REQ_DATA) != 0)
1187  fatal("restoring data out of order is not supported in this archive format: "
1188  "\"%s\" is required, but comes before \"%s\" in the archive file.",
1189  th->targetFile, filename);
1190 
1191  /* Header doesn't match, so read to next header */
1192  len = ((th->fileLen + 511) & ~511); /* Padded length */
1193  blks = len >> 9; /* # of 512 byte blocks */
1194 
1195  for (i = 0; i < blks; i++)
1196  _tarReadRaw(AH, &header[0], 512, NULL, ctx->tarFH);
1197 
1198  if (!_tarGetHeader(AH, th))
1199  fatal("could not find header for file \"%s\" in tar archive", filename);
1200  }
1201 
1202  ctx->tarNextMember = ctx->tarFHpos + ((th->fileLen + 511) & ~511);
1203  th->pos = 0;
1204 
1205  return th;
1206 }
1207 
1208 /* Read & verify a header */
1209 static int
1211 {
1212  lclContext *ctx = (lclContext *) AH->formatData;
1213  char h[512];
1214  char tag[100 + 1];
1215  int sum,
1216  chk;
1217  pgoff_t len;
1218  pgoff_t hPos;
1219  bool gotBlock = false;
1220 
1221  while (!gotBlock)
1222  {
1223  /* Save the pos for reporting purposes */
1224  hPos = ctx->tarFHpos;
1225 
1226  /* Read a 512 byte block, return EOF, exit if short */
1227  len = _tarReadRaw(AH, h, 512, NULL, ctx->tarFH);
1228  if (len == 0) /* EOF */
1229  return 0;
1230 
1231  if (len != 512)
1232  fatal(ngettext("incomplete tar header found (%lu byte)",
1233  "incomplete tar header found (%lu bytes)",
1234  len),
1235  (unsigned long) len);
1236 
1237  /* Calc checksum */
1238  chk = tarChecksum(h);
1239  sum = read_tar_number(&h[148], 8);
1240 
1241  /*
1242  * If the checksum failed, see if it is a null block. If so, silently
1243  * continue to the next block.
1244  */
1245  if (chk == sum)
1246  gotBlock = true;
1247  else
1248  {
1249  int i;
1250 
1251  for (i = 0; i < 512; i++)
1252  {
1253  if (h[i] != 0)
1254  {
1255  gotBlock = true;
1256  break;
1257  }
1258  }
1259  }
1260  }
1261 
1262  /* Name field is 100 bytes, might not be null-terminated */
1263  strlcpy(tag, &h[0], 100 + 1);
1264 
1265  len = read_tar_number(&h[124], 12);
1266 
1267  {
1268  char posbuf[32];
1269  char lenbuf[32];
1270 
1271  snprintf(posbuf, sizeof(posbuf), UINT64_FORMAT, (uint64) hPos);
1272  snprintf(lenbuf, sizeof(lenbuf), UINT64_FORMAT, (uint64) len);
1273  pg_log_debug("TOC Entry %s at %s (length %s, checksum %d)",
1274  tag, posbuf, lenbuf, sum);
1275  }
1276 
1277  if (chk != sum)
1278  {
1279  char posbuf[32];
1280 
1281  snprintf(posbuf, sizeof(posbuf), UINT64_FORMAT,
1282  (uint64) ftello(ctx->tarFH));
1283  fatal("corrupt tar header found in %s (expected %d, computed %d) file position %s",
1284  tag, sum, chk, posbuf);
1285  }
1286 
1287  th->targetFile = pg_strdup(tag);
1288  th->fileLen = len;
1289 
1290  return 1;
1291 }
1292 
1293 
1294 static void
1296 {
1297  char h[512];
1298 
1299  tarCreateHeader(h, th->targetFile, NULL, th->fileLen,
1300  0600, 04000, 02000, time(NULL));
1301 
1302  /* Now write the completed header. */
1303  if (fwrite(h, 1, 512, th->tarFH) != 512)
1305 }
static int tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...) pg_attribute_printf(3
static void _LoadBlobs(ArchiveHandle *AH)
TAR_MEMBER * FH
Definition: pg_backup_tar.c:91
FILE * zFH
Definition: pg_backup_tar.c:71
void ReadToc(ArchiveHandle *AH)
#define TH
static void _StartData(ArchiveHandle *AH, TocEntry *te)
static PgChecksumMode mode
Definition: pg_checksums.c:61
void ReadHead(ArchiveHandle *AH)
static void _PrintFileData(ArchiveHandle *AH, char *filename)
TAR_MEMBER * blobToc
Definition: pg_backup_tar.c:87
TAR_MEMBER * scriptTH
Definition: pg_backup_tar.c:93
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
RestoreOptions * ropt
Definition: pg_backup.h:183
uint64 read_tar_number(const char *s, int len)
Definition: tar.c:58
static TAR_MEMBER * tarOpen(ArchiveHandle *AH, const char *filename, char mode)
pgoff_t tarFHpos
Definition: pg_backup_tar.c:89
void WriteDataChunks(ArchiveHandle *AH, ParallelState *pstate)
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:617
#define PG_BINARY_W
Definition: c.h:1225
void WriteToc(ArchiveHandle *AH)
ArchiveHandle * AH
Definition: pg_backup_tar.c:80
static void _EndBlob(ArchiveHandle *AH, TocEntry *te, Oid oid)
DataDumperPtr dataDumper
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_BINARY_R
Definition: c.h:1224
void InitArchiveFmt_Tar(ArchiveHandle *AH)
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void StartRestoreBlobs(ArchiveHandle *AH)
struct _tocEntry * currToc
RestoreOptions * NewRestoreOptions(void)
#define pg_attribute_printf(f, a)
Definition: c.h:132
pgoff_t tarNextMember
Definition: pg_backup_tar.c:90
static struct pg_tm tm
Definition: localtime.c:108
#define pgoff_t
Definition: win32_port.h:195
#define ftello(stream)
Definition: win32_port.h:204
#define sprintf
Definition: port.h:194
size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
Definition: psprintf.c:106
int isSpecialScript
Definition: pg_backup_tar.c:92
#define S_IWUSR
Definition: win32_port.h:263
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
DumpOptions * dopt
Definition: pg_backup.h:182
#define pg_log_debug(...)
Definition: logging.h:91
FILE * tarFH
Definition: pg_backup_tar.c:88
void StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
char * c
static void _StartBlobs(ArchiveHandle *AH, TocEntry *te)
static char * buf
Definition: pg_test_fsync.c:67
static void _WriteBuf(ArchiveHandle *AH, const void *buf, size_t len)
static TAR_MEMBER * _tarPositionTo(ArchiveHandle *AH, const char *filename)
#define GZEOF(fh)
#define S_IRWXG
Definition: win32_port.h:281
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static void tarClose(ArchiveHandle *AH, TAR_MEMBER *TH)
#define atooid(x)
Definition: postgres_ext.h:42
bool isValidTarHeader(char *header)
int ahprintf(ArchiveHandle *AH, const char *fmt,...)
static void _PrintExtraToc(ArchiveHandle *AH, TocEntry *te)
static void _EndBlobs(ArchiveHandle *AH, TocEntry *te)
#define GZWRITE(p, s, n, fh)
void EndRestoreBlobs(ArchiveHandle *AH)
enum tarError tarCreateHeader(char *h, const char *filename, const char *linktarget, pgoff_t size, mode_t mode, uid_t uid, gid_t gid, time_t mtime)
Definition: tar.c:114
#define ngettext(s, p, n)
Definition: c.h:1134
FILE * nFH
Definition: pg_backup_tar.c:73
int verbose
Definition: pg_backup.h:185
static size_t _scriptOut(ArchiveHandle *AH, const void *buf, size_t len)
#define fseeko(stream, offset, origin)
Definition: win32_port.h:201
int tarChecksum(char *header)
Definition: tar.c:90
pgoff_t pos
Definition: pg_backup_tar.c:78
static void * fn(void *arg)
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
CustomOutPtrType CustomOutPtr
static void _tarWriteHeader(TAR_MEMBER *th)
char * ReadStr(ArchiveHandle *AH)
teReqs TocIDRequired(ArchiveHandle *AH, DumpId id)
static void _EndData(ArchiveHandle *AH, TocEntry *te)
FILE * tmpFH
Definition: pg_backup_tar.c:75
pgoff_t fileLen
Definition: pg_backup_tar.c:79
#define strerror
Definition: port.h:205
static void _PrintTocData(ArchiveHandle *AH, TocEntry *te)
static void _ArchiveEntry(ArchiveHandle *AH, TocEntry *te)
#define fatal(...)
static void _StartBlob(ArchiveHandle *AH, TocEntry *te, Oid oid)
#define GZCLOSE(fh)
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:209
#define INT64_FORMAT
Definition: c.h:401
const char * name
Definition: encode.c:521
#define S_IRUSR
Definition: win32_port.h:260
static int static void _tarAddFile(ArchiveHandle *AH, TAR_MEMBER *th)
void WriteHead(ArchiveHandle *AH)
#define GZREAD(p, s, n, fh)
#define WRITE_ERROR_EXIT
static void _CloseArchive(ArchiveHandle *AH)
#define K_STD_BUF_SIZE
Definition: pg_backup_tar.c:63
static char * filename
Definition: pg_dumpall.c:90
static void _WriteData(ArchiveHandle *AH, const void *data, size_t dLen)
int errmsg(const char *fmt,...)
Definition: elog.c:822
void EndRestoreBlob(ArchiveHandle *AH, Oid oid)
void RestoreArchive(Archive *AH)
static size_t tarRead(void *buf, size_t len, TAR_MEMBER *th)
int i
size_t WriteStr(ArchiveHandle *AH, const char *c)
TAR_MEMBER * TH
Definition: pg_backup_tar.c:98
#define READ_ERROR_EXIT(fd)
static int _tarGetHeader(ArchiveHandle *AH, TAR_MEMBER *th)
void ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
bool checkSeek(FILE *fp)
static void _ReadBuf(ArchiveHandle *AH, void *buf, size_t len)
static void _WriteExtraToc(ArchiveHandle *AH, TocEntry *te)
pgoff_t filePos
static int _ReadByte(ArchiveHandle *)
static size_t tarWrite(const void *buf, size_t len, TAR_MEMBER *th)
FILE * tarFH
Definition: pg_backup_tar.c:74
#define snprintf
Definition: port.h:192
#define UINT64_FORMAT
Definition: c.h:402
#define LOBBUFSIZE
static int _WriteByte(ArchiveHandle *AH, const int i)
char * targetFile
Definition: pg_backup_tar.c:76
#define S_IRWXO
Definition: win32_port.h:293
#define pg_log_info(...)
Definition: logging.h:87
static void _ReadExtraToc(ArchiveHandle *AH, TocEntry *te)
void SetArchiveOptions(Archive *AH, DumpOptions *dopt, RestoreOptions *ropt)
static size_t _tarReadRaw(ArchiveHandle *AH, void *buf, size_t len, TAR_MEMBER *th, FILE *fh)