]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_backup_archiver.c
Fix pg_restore to process BLOB COMMENT entries correctly; they aren't
[postgresql] / src / bin / pg_dump / pg_backup_archiver.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_backup_archiver.c
4  *
5  *      Private implementation of the archiver routines.
6  *
7  *      See the headers to pg_restore for more details.
8  *
9  * Copyright (c) 2000, Philip Warner
10  *      Rights are granted to use this software in any way so long
11  *      as this notice is not removed.
12  *
13  *      The author is not responsible for loss or damages that may
14  *      result from its use.
15  *
16  *
17  * IDENTIFICATION
18  *              $PostgreSQL: pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.129 2006/05/24 21:20:11 tgl Exp $
19  *
20  *-------------------------------------------------------------------------
21  */
22
23 #include "pg_backup.h"
24 #include "pg_dump.h"
25 #include "pg_backup_archiver.h"
26 #include "pg_backup_db.h"
27 #include "dumputils.h"
28
29 #include <ctype.h>
30
31 #ifndef WIN32_CLIENT_ONLY
32 #include <unistd.h>
33 #endif
34
35 #ifdef WIN32
36 #include <io.h>
37 #endif
38
39 #include "pqexpbuffer.h"
40 #include "libpq/libpq-fs.h"
41
42
43 const char *progname;
44
45 static char *modulename = gettext_noop("archiver");
46
47
48 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
49                  const int compression, ArchiveMode mode);
50 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
51                                           ArchiveHandle *AH);
52 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
53
54
55 static void _doSetFixedOutputState(ArchiveHandle *AH);
56 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
57 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
58 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
59 static void _becomeUser(ArchiveHandle *AH, const char *user);
60 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
61 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
62 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
63
64 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
65 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
66 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
67 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
68 static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
69 static int      _discoverArchiveFormat(ArchiveHandle *AH);
70
71 static void dump_lo_buf(ArchiveHandle *AH);
72 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
73 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
74
75 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
76
77
78 /*
79  *      Wrapper functions.
80  *
81  *      The objective it to make writing new formats and dumpers as simple
82  *      as possible, if necessary at the expense of extra function calls etc.
83  *
84  */
85
86
87 /* Create a new archive */
88 /* Public */
89 Archive *
90 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
91                           const int compression)
92
93 {
94         ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
95
96         return (Archive *) AH;
97 }
98
99 /* Open an existing archive */
100 /* Public */
101 Archive *
102 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
103 {
104         ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
105
106         return (Archive *) AH;
107 }
108
109 /* Public */
110 void
111 CloseArchive(Archive *AHX)
112 {
113         int                     res = 0;
114         ArchiveHandle *AH = (ArchiveHandle *) AHX;
115
116         (*AH->ClosePtr) (AH);
117
118         /* Close the output */
119         if (AH->gzOut)
120                 res = GZCLOSE(AH->OF);
121         else if (AH->OF != stdout)
122                 res = fclose(AH->OF);
123
124         if (res != 0)
125                 die_horribly(AH, modulename, "could not close output file: %s\n",
126                                          strerror(errno));
127 }
128
129 /* Public */
130 void
131 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
132 {
133         ArchiveHandle *AH = (ArchiveHandle *) AHX;
134         TocEntry   *te;
135         teReqs          reqs;
136         OutputContext sav;
137         bool            defnDumped;
138
139         AH->ropt = ropt;
140         AH->stage = STAGE_INITIALIZING;
141
142         /*
143          * Check for nonsensical option combinations.
144          *
145          * NB: create+dropSchema is useless because if you're creating the DB,
146          * there's no need to drop individual items in it.  Moreover, if we tried
147          * to do that then we'd issue the drops in the database initially
148          * connected to, not the one we will create, which is very bad...
149          */
150         if (ropt->create && ropt->dropSchema)
151                 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
152
153         /*
154          * If we're using a DB connection, then connect it.
155          */
156         if (ropt->useDB)
157         {
158                 ahlog(AH, 1, "connecting to database for restore\n");
159                 if (AH->version < K_VERS_1_3)
160                         die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
161
162                 /* XXX Should get this from the archive */
163                 AHX->minRemoteVersion = 070100;
164                 AHX->maxRemoteVersion = 999999;
165
166                 ConnectDatabase(AHX, ropt->dbname,
167                                                 ropt->pghost, ropt->pgport, ropt->username,
168                                                 ropt->requirePassword, ropt->ignoreVersion);
169
170                 /*
171                  * If we're talking to the DB directly, don't send comments since they
172                  * obscure SQL when displaying errors
173                  */
174                 AH->noTocComments = 1;
175         }
176
177         /*
178          * Work out if we have an implied data-only restore. This can happen if
179          * the dump was data only or if the user has used a toc list to exclude
180          * all of the schema data. All we do is look for schema entries - if none
181          * are found then we set the dataOnly flag.
182          *
183          * We could scan for wanted TABLE entries, but that is not the same as
184          * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
185          */
186         if (!ropt->dataOnly)
187         {
188                 int                     impliedDataOnly = 1;
189
190                 for (te = AH->toc->next; te != AH->toc; te = te->next)
191                 {
192                         reqs = _tocEntryRequired(te, ropt, true);
193                         if ((reqs & REQ_SCHEMA) != 0)
194                         {                                       /* It's schema, and it's wanted */
195                                 impliedDataOnly = 0;
196                                 break;
197                         }
198                 }
199                 if (impliedDataOnly)
200                 {
201                         ropt->dataOnly = impliedDataOnly;
202                         ahlog(AH, 1, "implied data-only restore\n");
203                 }
204         }
205
206         /*
207          * Setup the output file if necessary.
208          */
209         if (ropt->filename || ropt->compression)
210                 sav = SetOutput(AH, ropt->filename, ropt->compression);
211
212         ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
213
214         if (AH->public.verbose)
215                 dumpTimestamp(AH, "Started on", AH->createDate);
216
217         if (ropt->single_txn)
218         {
219                 if (AH->connection)
220                         StartTransaction(AH);
221                 else
222                         ahprintf(AH, "BEGIN;\n\n");
223         }
224
225         /*
226          * Establish important parameter values right away.
227          */
228         _doSetFixedOutputState(AH);
229
230         AH->stage = STAGE_PROCESSING;
231
232         /*
233          * Drop the items at the start, in reverse order
234          */
235         if (ropt->dropSchema)
236         {
237                 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
238                 {
239                         AH->currentTE = te;
240
241                         reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
242                         if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
243                         {
244                                 /* We want the schema */
245                                 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
246                                 /* Select owner and schema as necessary */
247                                 _becomeOwner(AH, te);
248                                 _selectOutputSchema(AH, te->namespace);
249                                 /* Drop it */
250                                 ahprintf(AH, "%s", te->dropStmt);
251                         }
252                 }
253         }
254
255         /*
256          * Now process each non-ACL TOC entry
257          */
258         for (te = AH->toc->next; te != AH->toc; te = te->next)
259         {
260                 AH->currentTE = te;
261
262                 /* Work out what, if anything, we want from this entry */
263                 reqs = _tocEntryRequired(te, ropt, false);
264
265                 /* Dump any relevant dump warnings to stderr */
266                 if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
267                 {
268                         if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
269                                 write_msg(modulename, "warning from original dump file: %s\n", te->defn);
270                         else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
271                                 write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
272                 }
273
274                 defnDumped = false;
275
276                 if ((reqs & REQ_SCHEMA) != 0)   /* We want the schema */
277                 {
278                         ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
279
280                         _printTocEntry(AH, te, ropt, false, false);
281                         defnDumped = true;
282
283                         /* If we created a DB, connect to it... */
284                         if (strcmp(te->desc, "DATABASE") == 0)
285                         {
286                                 ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
287                                 _reconnectToDB(AH, te->tag);
288                         }
289                 }
290
291                 /*
292                  * If we have a data component, then process it
293                  */
294                 if ((reqs & REQ_DATA) != 0)
295                 {
296                         /*
297                          * hadDumper will be set if there is genuine data component for
298                          * this node. Otherwise, we need to check the defn field for
299                          * statements that need to be executed in data-only restores.
300                          */
301                         if (te->hadDumper)
302                         {
303                                 /*
304                                  * If we can output the data, then restore it.
305                                  */
306                                 if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
307                                 {
308 #ifndef HAVE_LIBZ
309                                         if (AH->compression != 0)
310                                                 die_horribly(AH, modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
311 #endif
312
313                                         _printTocEntry(AH, te, ropt, true, false);
314
315                                         if (strcmp(te->desc, "BLOBS") == 0 ||
316                                                 strcmp(te->desc, "BLOB COMMENTS") == 0)
317                                         {
318                                                 ahlog(AH, 1, "restoring %s\n", te->desc);
319
320                                                 _selectOutputSchema(AH, "pg_catalog");
321
322                                                 (*AH->PrintTocDataPtr) (AH, te, ropt);
323                                         }
324                                         else
325                                         {
326                                                 _disableTriggersIfNecessary(AH, te, ropt);
327
328                                                 /* Select owner and schema as necessary */
329                                                 _becomeOwner(AH, te);
330                                                 _selectOutputSchema(AH, te->namespace);
331
332                                                 ahlog(AH, 1, "restoring data for table \"%s\"\n",
333                                                           te->tag);
334
335                                                 /*
336                                                  * If we have a copy statement, use it. As of V1.3,
337                                                  * these are separate to allow easy import from
338                                                  * withing a database connection. Pre 1.3 archives can
339                                                  * not use DB connections and are sent to output only.
340                                                  *
341                                                  * For V1.3+, the table data MUST have a copy
342                                                  * statement so that we can go into appropriate mode
343                                                  * with libpq.
344                                                  */
345                                                 if (te->copyStmt && strlen(te->copyStmt) > 0)
346                                                 {
347                                                         ahprintf(AH, "%s", te->copyStmt);
348                                                         AH->writingCopyData = true;
349                                                 }
350
351                                                 (*AH->PrintTocDataPtr) (AH, te, ropt);
352
353                                                 AH->writingCopyData = false;
354
355                                                 _enableTriggersIfNecessary(AH, te, ropt);
356                                         }
357                                 }
358                         }
359                         else if (!defnDumped)
360                         {
361                                 /* If we haven't already dumped the defn part, do so now */
362                                 ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
363                                 _printTocEntry(AH, te, ropt, false, false);
364                         }
365                 }
366         }                                                       /* end loop over TOC entries */
367
368         /*
369          * Scan TOC again to output ownership commands and ACLs
370          */
371         for (te = AH->toc->next; te != AH->toc; te = te->next)
372         {
373                 AH->currentTE = te;
374
375                 /* Work out what, if anything, we want from this entry */
376                 reqs = _tocEntryRequired(te, ropt, true);
377
378                 if ((reqs & REQ_SCHEMA) != 0)   /* We want the schema */
379                 {
380                         ahlog(AH, 1, "setting owner and privileges for %s %s\n",
381                                   te->desc, te->tag);
382                         _printTocEntry(AH, te, ropt, false, true);
383                 }
384         }
385
386         if (ropt->single_txn)
387         {
388                 if (AH->connection)
389                         CommitTransaction(AH);
390                 else
391                         ahprintf(AH, "COMMIT;\n\n");
392         }
393
394         if (AH->public.verbose)
395                 dumpTimestamp(AH, "Completed on", time(NULL));
396
397         ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
398
399         /*
400          * Clean up & we're done.
401          */
402         AH->stage = STAGE_FINALIZING;
403
404         if (ropt->filename || ropt->compression)
405                 ResetOutput(AH, sav);
406
407         if (ropt->useDB)
408         {
409                 PQfinish(AH->connection);
410                 AH->connection = NULL;
411         }
412 }
413
414 /*
415  * Allocate a new RestoreOptions block.
416  * This is mainly so we can initialize it, but also for future expansion,
417  */
418 RestoreOptions *
419 NewRestoreOptions(void)
420 {
421         RestoreOptions *opts;
422
423         opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
424
425         opts->format = archUnknown;
426         opts->suppressDumpWarnings = false;
427         opts->exit_on_error = false;
428
429         return opts;
430 }
431
432 static void
433 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
434 {
435         /* This hack is only needed in a data-only restore */
436         if (!ropt->dataOnly || !ropt->disable_triggers)
437                 return;
438
439         ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
440
441         /*
442          * Become superuser if possible, since they are the only ones who can
443          * disable constraint triggers.  If -S was not given, assume the initial
444          * user identity is a superuser.  (XXX would it be better to become the
445          * table owner?)
446          */
447         _becomeUser(AH, ropt->superuser);
448
449         /*
450          * Disable them.
451          */
452         _selectOutputSchema(AH, te->namespace);
453
454         ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
455                          fmtId(te->tag));
456 }
457
458 static void
459 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
460 {
461         /* This hack is only needed in a data-only restore */
462         if (!ropt->dataOnly || !ropt->disable_triggers)
463                 return;
464
465         ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
466
467         /*
468          * Become superuser if possible, since they are the only ones who can
469          * disable constraint triggers.  If -S was not given, assume the initial
470          * user identity is a superuser.  (XXX would it be better to become the
471          * table owner?)
472          */
473         _becomeUser(AH, ropt->superuser);
474
475         /*
476          * Enable them.
477          */
478         _selectOutputSchema(AH, te->namespace);
479
480         ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
481                          fmtId(te->tag));
482 }
483
484 /*
485  * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
486  */
487
488 /* Public */
489 size_t
490 WriteData(Archive *AHX, const void *data, size_t dLen)
491 {
492         ArchiveHandle *AH = (ArchiveHandle *) AHX;
493
494         if (!AH->currToc)
495                 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
496
497         return (*AH->WriteDataPtr) (AH, data, dLen);
498 }
499
500 /*
501  * Create a new TOC entry. The TOC was designed as a TOC, but is now the
502  * repository for all metadata. But the name has stuck.
503  */
504
505 /* Public */
506 void
507 ArchiveEntry(Archive *AHX,
508                          CatalogId catalogId, DumpId dumpId,
509                          const char *tag,
510                          const char *namespace,
511                          const char *tablespace,
512                          const char *owner, bool withOids,
513                          const char *desc, const char *defn,
514                          const char *dropStmt, const char *copyStmt,
515                          const DumpId *deps, int nDeps,
516                          DataDumperPtr dumpFn, void *dumpArg)
517 {
518         ArchiveHandle *AH = (ArchiveHandle *) AHX;
519         TocEntry   *newToc;
520
521         newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
522         if (!newToc)
523                 die_horribly(AH, modulename, "out of memory\n");
524
525         AH->tocCount++;
526         if (dumpId > AH->maxDumpId)
527                 AH->maxDumpId = dumpId;
528
529         newToc->prev = AH->toc->prev;
530         newToc->next = AH->toc;
531         AH->toc->prev->next = newToc;
532         AH->toc->prev = newToc;
533
534         newToc->catalogId = catalogId;
535         newToc->dumpId = dumpId;
536
537         newToc->tag = strdup(tag);
538         newToc->namespace = namespace ? strdup(namespace) : NULL;
539         newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
540         newToc->owner = strdup(owner);
541         newToc->withOids = withOids;
542         newToc->desc = strdup(desc);
543         newToc->defn = strdup(defn);
544         newToc->dropStmt = strdup(dropStmt);
545         newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
546
547         if (nDeps > 0)
548         {
549                 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
550                 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
551                 newToc->nDeps = nDeps;
552         }
553         else
554         {
555                 newToc->dependencies = NULL;
556                 newToc->nDeps = 0;
557         }
558
559         newToc->dataDumper = dumpFn;
560         newToc->dataDumperArg = dumpArg;
561         newToc->hadDumper = dumpFn ? true : false;
562
563         newToc->formatData = NULL;
564
565         if (AH->ArchiveEntryPtr !=NULL)
566                 (*AH->ArchiveEntryPtr) (AH, newToc);
567 }
568
569 /* Public */
570 void
571 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
572 {
573         ArchiveHandle *AH = (ArchiveHandle *) AHX;
574         TocEntry   *te = AH->toc->next;
575         OutputContext sav;
576         char       *fmtName;
577
578         if (ropt->filename)
579                 sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
580
581         ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
582         ahprintf(AH, ";     dbname: %s\n;     TOC Entries: %d\n;     Compression: %d\n",
583                          AH->archdbname, AH->tocCount, AH->compression);
584
585         switch (AH->format)
586         {
587                 case archFiles:
588                         fmtName = "FILES";
589                         break;
590                 case archCustom:
591                         fmtName = "CUSTOM";
592                         break;
593                 case archTar:
594                         fmtName = "TAR";
595                         break;
596                 default:
597                         fmtName = "UNKNOWN";
598         }
599
600         ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
601         ahprintf(AH, ";     Format: %s\n", fmtName);
602         ahprintf(AH, ";     Integer: %d bytes\n", (int) AH->intSize);
603         ahprintf(AH, ";     Offset: %d bytes\n", (int) AH->offSize);
604         if (AH->archiveRemoteVersion)
605                 ahprintf(AH, ";     Dumped from database version: %s\n",
606                                  AH->archiveRemoteVersion);
607         if (AH->archiveDumpVersion)
608                 ahprintf(AH, ";     Dumped by pg_dump version: %s\n",
609                                  AH->archiveDumpVersion);
610
611         ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
612
613         while (te != AH->toc)
614         {
615                 if (_tocEntryRequired(te, ropt, true) != 0)
616                         ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
617                                          te->catalogId.tableoid, te->catalogId.oid,
618                                          te->desc, te->namespace ? te->namespace : "-",
619                                          te->tag, te->owner);
620                 te = te->next;
621         }
622
623         if (ropt->filename)
624                 ResetOutput(AH, sav);
625 }
626
627 /***********
628  * BLOB Archival
629  ***********/
630
631 /* Called by a dumper to signal start of a BLOB */
632 int
633 StartBlob(Archive *AHX, Oid oid)
634 {
635         ArchiveHandle *AH = (ArchiveHandle *) AHX;
636
637         if (!AH->StartBlobPtr)
638                 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
639
640         (*AH->StartBlobPtr) (AH, AH->currToc, oid);
641
642         return 1;
643 }
644
645 /* Called by a dumper to signal end of a BLOB */
646 int
647 EndBlob(Archive *AHX, Oid oid)
648 {
649         ArchiveHandle *AH = (ArchiveHandle *) AHX;
650
651         if (AH->EndBlobPtr)
652                 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
653
654         return 1;
655 }
656
657 /**********
658  * BLOB Restoration
659  **********/
660
661 /*
662  * Called by a format handler before any blobs are restored
663  */
664 void
665 StartRestoreBlobs(ArchiveHandle *AH)
666 {
667         if (!AH->ropt->single_txn)
668         {
669                 if (AH->connection)
670                         StartTransaction(AH);
671                 else
672                         ahprintf(AH, "BEGIN;\n\n");
673         }
674
675         AH->blobCount = 0;
676 }
677
678 /*
679  * Called by a format handler after all blobs are restored
680  */
681 void
682 EndRestoreBlobs(ArchiveHandle *AH)
683 {
684         if (!AH->ropt->single_txn)
685         {
686                 if (AH->connection)
687                         CommitTransaction(AH);
688                 else
689                         ahprintf(AH, "COMMIT;\n\n");
690         }
691
692         ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
693 }
694
695
696 /*
697  * Called by a format handler to initiate restoration of a blob
698  */
699 void
700 StartRestoreBlob(ArchiveHandle *AH, Oid oid)
701 {
702         Oid                     loOid;
703
704         AH->blobCount++;
705
706         /* Initialize the LO Buffer */
707         AH->lo_buf_used = 0;
708
709         ahlog(AH, 2, "restoring large object with OID %u\n", oid);
710
711         if (AH->connection)
712         {
713                 loOid = lo_create(AH->connection, oid);
714                 if (loOid == 0 || loOid != oid)
715                         die_horribly(AH, modulename, "could not create large object %u\n",
716                                                  oid);
717
718                 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
719                 if (AH->loFd == -1)
720                         die_horribly(AH, modulename, "could not open large object\n");
721         }
722         else
723         {
724                 ahprintf(AH, "SELECT lo_open(lo_create(%u), %d);\n", oid, INV_WRITE);
725         }
726
727         AH->writingBlob = 1;
728 }
729
730 void
731 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
732 {
733         if (AH->lo_buf_used > 0)
734         {
735                 /* Write remaining bytes from the LO buffer */
736                 dump_lo_buf(AH);
737         }
738
739         AH->writingBlob = 0;
740
741         if (AH->connection)
742         {
743                 lo_close(AH->connection, AH->loFd);
744                 AH->loFd = -1;
745         }
746         else
747         {
748                 ahprintf(AH, "SELECT lo_close(0);\n\n");
749         }
750 }
751
752 /***********
753  * Sorting and Reordering
754  ***********/
755
756 void
757 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
758 {
759         ArchiveHandle *AH = (ArchiveHandle *) AHX;
760         FILE       *fh;
761         char            buf[1024];
762         char       *cmnt;
763         char       *endptr;
764         DumpId          id;
765         TocEntry   *te;
766         TocEntry   *tePrev;
767
768         /* Allocate space for the 'wanted' array, and init it */
769         ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
770         memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
771         ropt->limitToList = true;
772
773         /* Set prev entry as head of list */
774         tePrev = AH->toc;
775
776         /* Setup the file */
777         fh = fopen(ropt->tocFile, PG_BINARY_R);
778         if (!fh)
779                 die_horribly(AH, modulename, "could not open TOC file: %s\n",
780                                          strerror(errno));
781
782         while (fgets(buf, sizeof(buf), fh) != NULL)
783         {
784                 /* Truncate line at comment, if any */
785                 cmnt = strchr(buf, ';');
786                 if (cmnt != NULL)
787                         cmnt[0] = '\0';
788
789                 /* Ignore if all blank */
790                 if (strspn(buf, " \t\r") == strlen(buf))
791                         continue;
792
793                 /* Get an ID, check it's valid and not already seen */
794                 id = strtol(buf, &endptr, 10);
795                 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
796                         ropt->idWanted[id - 1])
797                 {
798                         write_msg(modulename, "WARNING: line ignored: %s\n", buf);
799                         continue;
800                 }
801
802                 /* Find TOC entry */
803                 te = getTocEntryByDumpId(AH, id);
804                 if (!te)
805                         die_horribly(AH, modulename, "could not find entry for ID %d\n",
806                                                  id);
807
808                 ropt->idWanted[id - 1] = true;
809
810                 _moveAfter(AH, tePrev, te);
811                 tePrev = te;
812         }
813
814         if (fclose(fh) != 0)
815                 die_horribly(AH, modulename, "could not close TOC file: %s\n",
816                                          strerror(errno));
817 }
818
819 /**********************
820  * 'Convenience functions that look like standard IO functions
821  * for writing data when in dump mode.
822  **********************/
823
824 /* Public */
825 int
826 archputs(const char *s, Archive *AH)
827 {
828         return WriteData(AH, s, strlen(s));
829 }
830
831 /* Public */
832 int
833 archprintf(Archive *AH, const char *fmt,...)
834 {
835         char       *p = NULL;
836         va_list         ap;
837         int                     bSize = strlen(fmt) + 256;
838         int                     cnt = -1;
839
840         /*
841          * This is paranoid: deal with the possibility that vsnprintf is willing
842          * to ignore trailing null or returns > 0 even if string does not fit. It
843          * may be the case that it returns cnt = bufsize
844          */
845         while (cnt < 0 || cnt >= (bSize - 1))
846         {
847                 if (p != NULL)
848                         free(p);
849                 bSize *= 2;
850                 p = (char *) malloc(bSize);
851                 if (p == NULL)
852                         exit_horribly(AH, modulename, "out of memory\n");
853                 va_start(ap, fmt);
854                 cnt = vsnprintf(p, bSize, fmt, ap);
855                 va_end(ap);
856         }
857         WriteData(AH, p, cnt);
858         free(p);
859         return cnt;
860 }
861
862
863 /*******************************
864  * Stuff below here should be 'private' to the archiver routines
865  *******************************/
866
867 OutputContext
868 SetOutput(ArchiveHandle *AH, char *filename, int compression)
869 {
870         OutputContext sav;
871         int                     fn;
872
873         /* Replace the AH output file handle */
874         sav.OF = AH->OF;
875         sav.gzOut = AH->gzOut;
876
877         if (filename)
878                 fn = -1;
879         else if (AH->FH)
880                 fn = fileno(AH->FH);
881         else if (AH->fSpec)
882         {
883                 fn = -1;
884                 filename = AH->fSpec;
885         }
886         else
887                 fn = fileno(stdout);
888
889         /* If compression explicitly requested, use gzopen */
890 #ifdef HAVE_LIBZ
891         if (compression != 0)
892         {
893                 char            fmode[10];
894
895                 /* Don't use PG_BINARY_x since this is zlib */
896                 sprintf(fmode, "wb%d", compression);
897                 if (fn >= 0)
898                         AH->OF = gzdopen(dup(fn), fmode);
899                 else
900                         AH->OF = gzopen(filename, fmode);
901                 AH->gzOut = 1;
902         }
903         else
904 #endif
905         {                                                       /* Use fopen */
906                 if (fn >= 0)
907                         AH->OF = fdopen(dup(fn), PG_BINARY_W);
908                 else
909                         AH->OF = fopen(filename, PG_BINARY_W);
910                 AH->gzOut = 0;
911         }
912
913         if (!AH->OF)
914                 die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
915
916         return sav;
917 }
918
919 void
920 ResetOutput(ArchiveHandle *AH, OutputContext sav)
921 {
922         int                     res;
923
924         if (AH->gzOut)
925                 res = GZCLOSE(AH->OF);
926         else
927                 res = fclose(AH->OF);
928
929         if (res != 0)
930                 die_horribly(AH, modulename, "could not close output file: %s\n",
931                                          strerror(errno));
932
933         AH->gzOut = sav.gzOut;
934         AH->OF = sav.OF;
935 }
936
937
938
939 /*
940  *      Print formatted text to the output file (usually stdout).
941  */
942 int
943 ahprintf(ArchiveHandle *AH, const char *fmt,...)
944 {
945         char       *p = NULL;
946         va_list         ap;
947         int                     bSize = strlen(fmt) + 256;              /* Should be enough */
948         int                     cnt = -1;
949
950         /*
951          * This is paranoid: deal with the possibility that vsnprintf is willing
952          * to ignore trailing null
953          */
954
955         /*
956          * or returns > 0 even if string does not fit. It may be the case that it
957          * returns cnt = bufsize
958          */
959         while (cnt < 0 || cnt >= (bSize - 1))
960         {
961                 if (p != NULL)
962                         free(p);
963                 bSize *= 2;
964                 p = (char *) malloc(bSize);
965                 if (p == NULL)
966                         die_horribly(AH, modulename, "out of memory\n");
967                 va_start(ap, fmt);
968                 cnt = vsnprintf(p, bSize, fmt, ap);
969                 va_end(ap);
970         }
971         ahwrite(p, 1, cnt, AH);
972         free(p);
973         return cnt;
974 }
975
976 void
977 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
978 {
979         va_list         ap;
980
981         if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
982                 return;
983
984         va_start(ap, fmt);
985         _write_msg(NULL, fmt, ap);
986         va_end(ap);
987 }
988
989 /*
990  * Single place for logic which says 'We are restoring to a direct DB connection'.
991  */
992 int
993 RestoringToDB(ArchiveHandle *AH)
994 {
995         return (AH->ropt && AH->ropt->useDB && AH->connection);
996 }
997
998 /*
999  * Dump the current contents of the LO data buffer while writing a BLOB
1000  */
1001 static void
1002 dump_lo_buf(ArchiveHandle *AH)
1003 {
1004         if (AH->connection)
1005         {
1006                 size_t          res;
1007
1008                 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1009                 ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
1010                           (unsigned long) AH->lo_buf_used, (unsigned long) res);
1011                 if (res != AH->lo_buf_used)
1012                         die_horribly(AH, modulename,
1013                         "could not write to large object (result: %lu, expected: %lu)\n",
1014                                            (unsigned long) res, (unsigned long) AH->lo_buf_used);
1015         }
1016         else
1017         {
1018                 unsigned char *str;
1019                 size_t          len;
1020
1021                 str = PQescapeBytea((const unsigned char *) AH->lo_buf,
1022                                                         AH->lo_buf_used, &len);
1023                 if (!str)
1024                         die_horribly(AH, modulename, "out of memory\n");
1025
1026                 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1027                 AH->writingBlob = 0;
1028                 ahprintf(AH, "SELECT lowrite(0, '%s');\n", str);
1029                 AH->writingBlob = 1;
1030
1031                 free(str);
1032         }
1033         AH->lo_buf_used = 0;
1034 }
1035
1036
1037 /*
1038  *      Write buffer to the output file (usually stdout). This is user for
1039  *      outputting 'restore' scripts etc. It is even possible for an archive
1040  *      format to create a custom output routine to 'fake' a restore if it
1041  *      wants to generate a script (see TAR output).
1042  */
1043 int
1044 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1045 {
1046         size_t          res;
1047
1048         if (AH->writingBlob)
1049         {
1050                 size_t          remaining = size * nmemb;
1051
1052                 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1053                 {
1054                         size_t          avail = AH->lo_buf_size - AH->lo_buf_used;
1055
1056                         memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1057                         ptr = (const void *) ((const char *) ptr + avail);
1058                         remaining -= avail;
1059                         AH->lo_buf_used += avail;
1060                         dump_lo_buf(AH);
1061                 }
1062
1063                 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1064                 AH->lo_buf_used += remaining;
1065
1066                 return size * nmemb;
1067         }
1068         else if (AH->gzOut)
1069         {
1070                 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1071                 if (res != (nmemb * size))
1072                         die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1073                 return res;
1074         }
1075         else if (AH->CustomOutPtr)
1076         {
1077                 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1078
1079                 if (res != (nmemb * size))
1080                         die_horribly(AH, modulename, "could not write to custom output routine\n");
1081                 return res;
1082         }
1083         else
1084         {
1085                 /*
1086                  * If we're doing a restore, and it's direct to DB, and we're
1087                  * connected then send it to the DB.
1088                  */
1089                 if (RestoringToDB(AH))
1090                         return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb);            /* Always 1, currently */
1091                 else
1092                 {
1093                         res = fwrite((void *) ptr, size, nmemb, AH->OF);
1094                         if (res != nmemb)
1095                                 die_horribly(AH, modulename, "could not write to output file: %s\n",
1096                                                          strerror(errno));
1097                         return res;
1098                 }
1099         }
1100 }
1101
1102 /* Common exit code */
1103 static void
1104 _write_msg(const char *modulename, const char *fmt, va_list ap)
1105 {
1106         if (modulename)
1107                 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1108         else
1109                 fprintf(stderr, "%s: ", progname);
1110         vfprintf(stderr, _(fmt), ap);
1111 }
1112
1113 void
1114 write_msg(const char *modulename, const char *fmt,...)
1115 {
1116         va_list         ap;
1117
1118         va_start(ap, fmt);
1119         _write_msg(modulename, fmt, ap);
1120         va_end(ap);
1121 }
1122
1123
1124 static void
1125 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1126 {
1127         _write_msg(modulename, fmt, ap);
1128
1129         if (AH)
1130         {
1131                 if (AH->public.verbose)
1132                         write_msg(NULL, "*** aborted because of error\n");
1133                 if (AH->connection)
1134                         PQfinish(AH->connection);
1135         }
1136
1137         exit(1);
1138 }
1139
1140 /* External use */
1141 void
1142 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1143 {
1144         va_list         ap;
1145
1146         va_start(ap, fmt);
1147         _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1148         va_end(ap);
1149 }
1150
1151 /* Archiver use (just different arg declaration) */
1152 void
1153 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1154 {
1155         va_list         ap;
1156
1157         va_start(ap, fmt);
1158         _die_horribly(AH, modulename, fmt, ap);
1159         va_end(ap);
1160 }
1161
1162 /* on some error, we may decide to go on... */
1163 void
1164 warn_or_die_horribly(ArchiveHandle *AH,
1165                                          const char *modulename, const char *fmt,...)
1166 {
1167         va_list         ap;
1168
1169         switch (AH->stage)
1170         {
1171
1172                 case STAGE_NONE:
1173                         /* Do nothing special */
1174                         break;
1175
1176                 case STAGE_INITIALIZING:
1177                         if (AH->stage != AH->lastErrorStage)
1178                                 write_msg(modulename, "Error while INITIALIZING:\n");
1179                         break;
1180
1181                 case STAGE_PROCESSING:
1182                         if (AH->stage != AH->lastErrorStage)
1183                                 write_msg(modulename, "Error while PROCESSING TOC:\n");
1184                         break;
1185
1186                 case STAGE_FINALIZING:
1187                         if (AH->stage != AH->lastErrorStage)
1188                                 write_msg(modulename, "Error while FINALIZING:\n");
1189                         break;
1190         }
1191         if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1192         {
1193                 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1194                                   AH->currentTE->dumpId,
1195                          AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1196                           AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1197         }
1198         AH->lastErrorStage = AH->stage;
1199         AH->lastErrorTE = AH->currentTE;
1200
1201         va_start(ap, fmt);
1202         if (AH->public.exit_on_error)
1203                 _die_horribly(AH, modulename, fmt, ap);
1204         else
1205         {
1206                 _write_msg(modulename, fmt, ap);
1207                 AH->public.n_errors++;
1208         }
1209         va_end(ap);
1210 }
1211
1212 static void
1213 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1214 {
1215         te->prev->next = te->next;
1216         te->next->prev = te->prev;
1217
1218         te->prev = pos;
1219         te->next = pos->next;
1220
1221         pos->next->prev = te;
1222         pos->next = te;
1223 }
1224
1225 #ifdef NOT_USED
1226
1227 static void
1228 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1229 {
1230         te->prev->next = te->next;
1231         te->next->prev = te->prev;
1232
1233         te->prev = pos->prev;
1234         te->next = pos;
1235         pos->prev->next = te;
1236         pos->prev = te;
1237 }
1238 #endif
1239
1240 static TocEntry *
1241 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1242 {
1243         TocEntry   *te;
1244
1245         te = AH->toc->next;
1246         while (te != AH->toc)
1247         {
1248                 if (te->dumpId == id)
1249                         return te;
1250                 te = te->next;
1251         }
1252         return NULL;
1253 }
1254
1255 teReqs
1256 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1257 {
1258         TocEntry   *te = getTocEntryByDumpId(AH, id);
1259
1260         if (!te)
1261                 return 0;
1262
1263         return _tocEntryRequired(te, ropt, true);
1264 }
1265
1266 size_t
1267 WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
1268 {
1269         int                     off;
1270
1271         /* Save the flag */
1272         (*AH->WriteBytePtr) (AH, wasSet);
1273
1274         /* Write out off_t smallest byte first, prevents endian mismatch */
1275         for (off = 0; off < sizeof(off_t); off++)
1276         {
1277                 (*AH->WriteBytePtr) (AH, o & 0xFF);
1278                 o >>= 8;
1279         }
1280         return sizeof(off_t) + 1;
1281 }
1282
1283 int
1284 ReadOffset(ArchiveHandle *AH, off_t *o)
1285 {
1286         int                     i;
1287         int                     off;
1288         int                     offsetFlg;
1289
1290         /* Initialize to zero */
1291         *o = 0;
1292
1293         /* Check for old version */
1294         if (AH->version < K_VERS_1_7)
1295         {
1296                 /* Prior versions wrote offsets using WriteInt */
1297                 i = ReadInt(AH);
1298                 /* -1 means not set */
1299                 if (i < 0)
1300                         return K_OFFSET_POS_NOT_SET;
1301                 else if (i == 0)
1302                         return K_OFFSET_NO_DATA;
1303
1304                 /* Cast to off_t because it was written as an int. */
1305                 *o = (off_t) i;
1306                 return K_OFFSET_POS_SET;
1307         }
1308
1309         /*
1310          * Read the flag indicating the state of the data pointer. Check if valid
1311          * and die if not.
1312          *
1313          * This used to be handled by a negative or zero pointer, now we use an
1314          * extra byte specifically for the state.
1315          */
1316         offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1317
1318         switch (offsetFlg)
1319         {
1320                 case K_OFFSET_POS_NOT_SET:
1321                 case K_OFFSET_NO_DATA:
1322                 case K_OFFSET_POS_SET:
1323
1324                         break;
1325
1326                 default:
1327                         die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1328         }
1329
1330         /*
1331          * Read the bytes
1332          */
1333         for (off = 0; off < AH->offSize; off++)
1334         {
1335                 if (off < sizeof(off_t))
1336                         *o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1337                 else
1338                 {
1339                         if ((*AH->ReadBytePtr) (AH) != 0)
1340                                 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1341                 }
1342         }
1343
1344         return offsetFlg;
1345 }
1346
1347 size_t
1348 WriteInt(ArchiveHandle *AH, int i)
1349 {
1350         int                     b;
1351
1352         /*
1353          * This is a bit yucky, but I don't want to make the binary format very
1354          * dependent on representation, and not knowing much about it, I write out
1355          * a sign byte. If you change this, don't forget to change the file
1356          * version #, and modify readInt to read the new format AS WELL AS the old
1357          * formats.
1358          */
1359
1360         /* SIGN byte */
1361         if (i < 0)
1362         {
1363                 (*AH->WriteBytePtr) (AH, 1);
1364                 i = -i;
1365         }
1366         else
1367                 (*AH->WriteBytePtr) (AH, 0);
1368
1369         for (b = 0; b < AH->intSize; b++)
1370         {
1371                 (*AH->WriteBytePtr) (AH, i & 0xFF);
1372                 i >>= 8;
1373         }
1374
1375         return AH->intSize + 1;
1376 }
1377
1378 int
1379 ReadInt(ArchiveHandle *AH)
1380 {
1381         int                     res = 0;
1382         int                     bv,
1383                                 b;
1384         int                     sign = 0;               /* Default positive */
1385         int                     bitShift = 0;
1386
1387         if (AH->version > K_VERS_1_0)
1388                 /* Read a sign byte */
1389                 sign = (*AH->ReadBytePtr) (AH);
1390
1391         for (b = 0; b < AH->intSize; b++)
1392         {
1393                 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1394                 if (bv != 0)
1395                         res = res + (bv << bitShift);
1396                 bitShift += 8;
1397         }
1398
1399         if (sign)
1400                 res = -res;
1401
1402         return res;
1403 }
1404
1405 size_t
1406 WriteStr(ArchiveHandle *AH, const char *c)
1407 {
1408         size_t          res;
1409
1410         if (c)
1411         {
1412                 res = WriteInt(AH, strlen(c));
1413                 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1414         }
1415         else
1416                 res = WriteInt(AH, -1);
1417
1418         return res;
1419 }
1420
1421 char *
1422 ReadStr(ArchiveHandle *AH)
1423 {
1424         char       *buf;
1425         int                     l;
1426
1427         l = ReadInt(AH);
1428         if (l == -1)
1429                 buf = NULL;
1430         else
1431         {
1432                 buf = (char *) malloc(l + 1);
1433                 if (!buf)
1434                         die_horribly(AH, modulename, "out of memory\n");
1435
1436                 (*AH->ReadBufPtr) (AH, (void *) buf, l);
1437                 buf[l] = '\0';
1438         }
1439
1440         return buf;
1441 }
1442
1443 static int
1444 _discoverArchiveFormat(ArchiveHandle *AH)
1445 {
1446         FILE       *fh;
1447         char            sig[6];                 /* More than enough */
1448         size_t          cnt;
1449         int                     wantClose = 0;
1450
1451 #if 0
1452         write_msg(modulename, "attempting to ascertain archive format\n");
1453 #endif
1454
1455         if (AH->lookahead)
1456                 free(AH->lookahead);
1457
1458         AH->lookaheadSize = 512;
1459         AH->lookahead = calloc(1, 512);
1460         AH->lookaheadLen = 0;
1461         AH->lookaheadPos = 0;
1462
1463         if (AH->fSpec)
1464         {
1465                 wantClose = 1;
1466                 fh = fopen(AH->fSpec, PG_BINARY_R);
1467         }
1468         else
1469                 fh = stdin;
1470
1471         if (!fh)
1472                 die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
1473
1474         cnt = fread(sig, 1, 5, fh);
1475
1476         if (cnt != 5)
1477         {
1478                 if (ferror(fh))
1479                         die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1480                 else
1481                         die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1482                                                  (unsigned long) cnt);
1483         }
1484
1485         /* Save it, just in case we need it later */
1486         strncpy(&AH->lookahead[0], sig, 5);
1487         AH->lookaheadLen = 5;
1488
1489         if (strncmp(sig, "PGDMP", 5) == 0)
1490         {
1491                 AH->vmaj = fgetc(fh);
1492                 AH->vmin = fgetc(fh);
1493
1494                 /* Save these too... */
1495                 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1496                 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1497
1498                 /* Check header version; varies from V1.0 */
1499                 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))                /* Version > 1.0 */
1500                 {
1501                         AH->vrev = fgetc(fh);
1502                         AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1503                 }
1504                 else
1505                         AH->vrev = 0;
1506
1507                 /* Make a convenient integer <maj><min><rev>00 */
1508                 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1509
1510                 AH->intSize = fgetc(fh);
1511                 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1512
1513                 if (AH->version >= K_VERS_1_7)
1514                 {
1515                         AH->offSize = fgetc(fh);
1516                         AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1517                 }
1518                 else
1519                         AH->offSize = AH->intSize;
1520
1521                 AH->format = fgetc(fh);
1522                 AH->lookahead[AH->lookaheadLen++] = AH->format;
1523         }
1524         else
1525         {
1526                 /*
1527                  * *Maybe* we have a tar archive format file... So, read first 512
1528                  * byte header...
1529                  */
1530                 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1531                 AH->lookaheadLen += cnt;
1532
1533                 if (AH->lookaheadLen != 512)
1534                         die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1535
1536                 if (!isValidTarHeader(AH->lookahead))
1537                         die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1538
1539                 AH->format = archTar;
1540         }
1541
1542         /* If we can't seek, then mark the header as read */
1543         if (fseeko(fh, 0, SEEK_SET) != 0)
1544         {
1545                 /*
1546                  * NOTE: Formats that use the lookahead buffer can unset this in their
1547                  * Init routine.
1548                  */
1549                 AH->readHeader = 1;
1550         }
1551         else
1552                 AH->lookaheadLen = 0;   /* Don't bother since we've reset the file */
1553
1554 #if 0
1555         write_msg(modulename, "read %lu bytes into lookahead buffer\n",
1556                           (unsigned long) AH->lookaheadLen);
1557 #endif
1558
1559         /* Close the file */
1560         if (wantClose)
1561                 if (fclose(fh) != 0)
1562                         die_horribly(AH, modulename, "could not close input file: %s\n",
1563                                                  strerror(errno));
1564
1565         return AH->format;
1566 }
1567
1568
1569 /*
1570  * Allocate an archive handle
1571  */
1572 static ArchiveHandle *
1573 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1574                  const int compression, ArchiveMode mode)
1575 {
1576         ArchiveHandle *AH;
1577
1578 #if 0
1579         write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1580 #endif
1581
1582         AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1583         if (!AH)
1584                 die_horribly(AH, modulename, "out of memory\n");
1585
1586         /* AH->debugLevel = 100; */
1587
1588         AH->vmaj = K_VERS_MAJOR;
1589         AH->vmin = K_VERS_MINOR;
1590         AH->vrev = K_VERS_REV;
1591
1592         AH->createDate = time(NULL);
1593
1594         AH->intSize = sizeof(int);
1595         AH->offSize = sizeof(off_t);
1596         if (FileSpec)
1597         {
1598                 AH->fSpec = strdup(FileSpec);
1599
1600                 /*
1601                  * Not used; maybe later....
1602                  *
1603                  * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1604                  * i--) if (AH->workDir[i-1] == '/')
1605                  */
1606         }
1607         else
1608                 AH->fSpec = NULL;
1609
1610         AH->currUser = strdup("");      /* So it's valid, but we can free() it later
1611                                                                  * if necessary */
1612         AH->currSchema = strdup("");    /* ditto */
1613         AH->currWithOids = -1;          /* force SET */
1614
1615         AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1616         if (!AH->toc)
1617                 die_horribly(AH, modulename, "out of memory\n");
1618
1619         AH->toc->next = AH->toc;
1620         AH->toc->prev = AH->toc;
1621
1622         AH->mode = mode;
1623         AH->compression = compression;
1624
1625         AH->pgCopyBuf = createPQExpBuffer();
1626         AH->sqlBuf = createPQExpBuffer();
1627
1628         /* Open stdout with no compression for AH output handle */
1629         AH->gzOut = 0;
1630         AH->OF = stdout;
1631
1632         /*
1633          * On Windows, we need to use binary mode to read/write non-text archive
1634          * formats.  Force stdin/stdout into binary mode if that is what we are
1635          * using.
1636          */
1637 #ifdef WIN32
1638         if (fmt != archNull &&
1639                 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1640         {
1641                 if (mode == archModeWrite)
1642                         setmode(fileno(stdout), O_BINARY);
1643                 else
1644                         setmode(fileno(stdin), O_BINARY);
1645         }
1646 #endif
1647
1648 #if 0
1649         write_msg(modulename, "archive format is %d\n", fmt);
1650 #endif
1651
1652         if (fmt == archUnknown)
1653                 AH->format = _discoverArchiveFormat(AH);
1654         else
1655                 AH->format = fmt;
1656
1657         switch (AH->format)
1658         {
1659                 case archCustom:
1660                         InitArchiveFmt_Custom(AH);
1661                         break;
1662
1663                 case archFiles:
1664                         InitArchiveFmt_Files(AH);
1665                         break;
1666
1667                 case archNull:
1668                         InitArchiveFmt_Null(AH);
1669                         break;
1670
1671                 case archTar:
1672                         InitArchiveFmt_Tar(AH);
1673                         break;
1674
1675                 default:
1676                         die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1677         }
1678
1679         /* sql error handling */
1680         AH->public.exit_on_error = true;
1681         AH->public.n_errors = 0;
1682
1683         return AH;
1684 }
1685
1686
1687 void
1688 WriteDataChunks(ArchiveHandle *AH)
1689 {
1690         TocEntry   *te = AH->toc->next;
1691         StartDataPtr startPtr;
1692         EndDataPtr      endPtr;
1693
1694         while (te != AH->toc)
1695         {
1696                 if (te->dataDumper != NULL)
1697                 {
1698                         AH->currToc = te;
1699                         /* printf("Writing data for %d (%x)\n", te->id, te); */
1700
1701                         if (strcmp(te->desc, "BLOBS") == 0)
1702                         {
1703                                 startPtr = AH->StartBlobsPtr;
1704                                 endPtr = AH->EndBlobsPtr;
1705                         }
1706                         else
1707                         {
1708                                 startPtr = AH->StartDataPtr;
1709                                 endPtr = AH->EndDataPtr;
1710                         }
1711
1712                         if (startPtr != NULL)
1713                                 (*startPtr) (AH, te);
1714
1715                         /*
1716                          * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
1717                          */
1718
1719                         /*
1720                          * The user-provided DataDumper routine needs to call
1721                          * AH->WriteData
1722                          */
1723                         (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
1724
1725                         if (endPtr != NULL)
1726                                 (*endPtr) (AH, te);
1727                         AH->currToc = NULL;
1728                 }
1729                 te = te->next;
1730         }
1731 }
1732
1733 void
1734 WriteToc(ArchiveHandle *AH)
1735 {
1736         TocEntry   *te;
1737         char            workbuf[32];
1738         int                     i;
1739
1740         /* printf("%d TOC Entries to save\n", AH->tocCount); */
1741
1742         WriteInt(AH, AH->tocCount);
1743
1744         for (te = AH->toc->next; te != AH->toc; te = te->next)
1745         {
1746                 WriteInt(AH, te->dumpId);
1747                 WriteInt(AH, te->dataDumper ? 1 : 0);
1748
1749                 /* OID is recorded as a string for historical reasons */
1750                 sprintf(workbuf, "%u", te->catalogId.tableoid);
1751                 WriteStr(AH, workbuf);
1752                 sprintf(workbuf, "%u", te->catalogId.oid);
1753                 WriteStr(AH, workbuf);
1754
1755                 WriteStr(AH, te->tag);
1756                 WriteStr(AH, te->desc);
1757                 WriteStr(AH, te->defn);
1758                 WriteStr(AH, te->dropStmt);
1759                 WriteStr(AH, te->copyStmt);
1760                 WriteStr(AH, te->namespace);
1761                 WriteStr(AH, te->tablespace);
1762                 WriteStr(AH, te->owner);
1763                 WriteStr(AH, te->withOids ? "true" : "false");
1764
1765                 /* Dump list of dependencies */
1766                 for (i = 0; i < te->nDeps; i++)
1767                 {
1768                         sprintf(workbuf, "%d", te->dependencies[i]);
1769                         WriteStr(AH, workbuf);
1770                 }
1771                 WriteStr(AH, NULL);             /* Terminate List */
1772
1773                 if (AH->WriteExtraTocPtr)
1774                         (*AH->WriteExtraTocPtr) (AH, te);
1775         }
1776 }
1777
1778 void
1779 ReadToc(ArchiveHandle *AH)
1780 {
1781         int                     i;
1782         char       *tmp;
1783         DumpId     *deps;
1784         int                     depIdx;
1785         int                     depSize;
1786
1787         TocEntry   *te = AH->toc->next;
1788
1789         AH->tocCount = ReadInt(AH);
1790         AH->maxDumpId = 0;
1791
1792         for (i = 0; i < AH->tocCount; i++)
1793         {
1794                 te = (TocEntry *) calloc(1, sizeof(TocEntry));
1795                 te->dumpId = ReadInt(AH);
1796
1797                 if (te->dumpId > AH->maxDumpId)
1798                         AH->maxDumpId = te->dumpId;
1799
1800                 /* Sanity check */
1801                 if (te->dumpId <= 0)
1802                         die_horribly(AH, modulename,
1803                                            "entry ID %d out of range -- perhaps a corrupt TOC\n",
1804                                                  te->dumpId);
1805
1806                 te->hadDumper = ReadInt(AH);
1807
1808                 if (AH->version >= K_VERS_1_8)
1809                 {
1810                         tmp = ReadStr(AH);
1811                         sscanf(tmp, "%u", &te->catalogId.tableoid);
1812                         free(tmp);
1813                 }
1814                 else
1815                         te->catalogId.tableoid = InvalidOid;
1816                 tmp = ReadStr(AH);
1817                 sscanf(tmp, "%u", &te->catalogId.oid);
1818                 free(tmp);
1819
1820                 te->tag = ReadStr(AH);
1821                 te->desc = ReadStr(AH);
1822                 te->defn = ReadStr(AH);
1823                 te->dropStmt = ReadStr(AH);
1824
1825                 if (AH->version >= K_VERS_1_3)
1826                         te->copyStmt = ReadStr(AH);
1827
1828                 if (AH->version >= K_VERS_1_6)
1829                         te->namespace = ReadStr(AH);
1830
1831                 if (AH->version >= K_VERS_1_10)
1832                         te->tablespace = ReadStr(AH);
1833
1834                 te->owner = ReadStr(AH);
1835                 if (AH->version >= K_VERS_1_9)
1836                 {
1837                         if (strcmp(ReadStr(AH), "true") == 0)
1838                                 te->withOids = true;
1839                         else
1840                                 te->withOids = false;
1841                 }
1842                 else
1843                         te->withOids = true;
1844
1845                 /* Read TOC entry dependencies */
1846                 if (AH->version >= K_VERS_1_5)
1847                 {
1848                         depSize = 100;
1849                         deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1850                         depIdx = 0;
1851                         for (;;)
1852                         {
1853                                 tmp = ReadStr(AH);
1854                                 if (!tmp)
1855                                         break;          /* end of list */
1856                                 if (depIdx >= depSize)
1857                                 {
1858                                         depSize *= 2;
1859                                         deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1860                                 }
1861                                 sscanf(tmp, "%d", &deps[depIdx]);
1862                                 free(tmp);
1863                                 depIdx++;
1864                         }
1865
1866                         if (depIdx > 0)         /* We have a non-null entry */
1867                         {
1868                                 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
1869                                 te->dependencies = deps;
1870                                 te->nDeps = depIdx;
1871                         }
1872                         else
1873                         {
1874                                 free(deps);
1875                                 te->dependencies = NULL;
1876                                 te->nDeps = 0;
1877                         }
1878                 }
1879                 else
1880                 {
1881                         te->dependencies = NULL;
1882                         te->nDeps = 0;
1883                 }
1884
1885                 if (AH->ReadExtraTocPtr)
1886                         (*AH->ReadExtraTocPtr) (AH, te);
1887
1888                 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
1889                           i, te->dumpId, te->desc, te->tag);
1890
1891                 te->prev = AH->toc->prev;
1892                 AH->toc->prev->next = te;
1893                 AH->toc->prev = te;
1894                 te->next = AH->toc;
1895         }
1896 }
1897
1898 static teReqs
1899 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
1900 {
1901         teReqs          res = REQ_ALL;
1902
1903         /* ENCODING objects are dumped specially, so always reject here */
1904         if (strcmp(te->desc, "ENCODING") == 0)
1905                 return 0;
1906
1907         /* If it's an ACL, maybe ignore it */
1908         if ((!include_acls || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1909                 return 0;
1910
1911         if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1912                 return 0;
1913
1914         /* Check options for selective dump/restore */
1915         if (ropt->schemaNames)
1916         {
1917                 /* If no namespace is specified, it means all. */
1918                 if (!te->namespace)
1919                         return 0;
1920                 if (strcmp(ropt->schemaNames, te->namespace) != 0)
1921                         return 0;
1922         }
1923
1924         if (ropt->selTypes)
1925         {
1926                 if (strcmp(te->desc, "TABLE") == 0 ||
1927                         strcmp(te->desc, "TABLE DATA") == 0)
1928                 {
1929                         if (!ropt->selTable)
1930                                 return 0;
1931                         if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1932                                 return 0;
1933                 }
1934                 else if (strcmp(te->desc, "INDEX") == 0)
1935                 {
1936                         if (!ropt->selIndex)
1937                                 return 0;
1938                         if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
1939                                 return 0;
1940                 }
1941                 else if (strcmp(te->desc, "FUNCTION") == 0)
1942                 {
1943                         if (!ropt->selFunction)
1944                                 return 0;
1945                         if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
1946                                 return 0;
1947                 }
1948                 else if (strcmp(te->desc, "TRIGGER") == 0)
1949                 {
1950                         if (!ropt->selTrigger)
1951                                 return 0;
1952                         if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
1953                                 return 0;
1954                 }
1955                 else
1956                         return 0;
1957         }
1958
1959         /*
1960          * Check if we had a dataDumper. Indicates if the entry is schema or data
1961          */
1962         if (!te->hadDumper)
1963         {
1964                 /*
1965                  * Special Case: If 'SEQUENCE SET' then it is considered a data entry
1966                  */
1967                 if (strcmp(te->desc, "SEQUENCE SET") == 0)
1968                         res = res & REQ_DATA;
1969                 else
1970                         res = res & ~REQ_DATA;
1971         }
1972
1973         /*
1974          * Special case: <Init> type with <Max OID> tag; this is obsolete and we
1975          * always ignore it.
1976          */
1977         if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
1978                 return 0;
1979
1980         /* Mask it if we only want schema */
1981         if (ropt->schemaOnly)
1982                 res = res & REQ_SCHEMA;
1983
1984         /* Mask it we only want data */
1985         if (ropt->dataOnly)
1986                 res = res & REQ_DATA;
1987
1988         /* Mask it if we don't have a schema contribution */
1989         if (!te->defn || strlen(te->defn) == 0)
1990                 res = res & ~REQ_SCHEMA;
1991
1992         /* Finally, if we used a list, limit based on that as well */
1993         if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
1994                 return 0;
1995
1996         return res;
1997 }
1998
1999 /*
2000  * Issue SET commands for parameters that we want to have set the same way
2001  * at all times during execution of a restore script.
2002  */
2003 static void
2004 _doSetFixedOutputState(ArchiveHandle *AH)
2005 {
2006         TocEntry   *te;
2007
2008         /* If we have an encoding setting, emit that */
2009         te = AH->toc->next;
2010         while (te != AH->toc)
2011         {
2012                 if (strcmp(te->desc, "ENCODING") == 0)
2013                 {
2014                         ahprintf(AH, "%s", te->defn);
2015                         break;
2016                 }
2017                 te = te->next;
2018         }
2019
2020         /* Make sure function checking is disabled */
2021         ahprintf(AH, "SET check_function_bodies = false;\n");
2022
2023         /* Avoid annoying notices etc */
2024         ahprintf(AH, "SET client_min_messages = warning;\n");
2025
2026         ahprintf(AH, "\n");
2027 }
2028
2029 /*
2030  * Issue a SET SESSION AUTHORIZATION command.  Caller is responsible
2031  * for updating state if appropriate.  If user is NULL or an empty string,
2032  * the specification DEFAULT will be used.
2033  */
2034 static void
2035 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2036 {
2037         PQExpBuffer cmd = createPQExpBuffer();
2038
2039         appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2040
2041         /*
2042          * SQL requires a string literal here.  Might as well be correct.
2043          */
2044         if (user && *user)
2045                 appendStringLiteral(cmd, user, false);
2046         else
2047                 appendPQExpBuffer(cmd, "DEFAULT");
2048         appendPQExpBuffer(cmd, ";");
2049
2050         if (RestoringToDB(AH))
2051         {
2052                 PGresult   *res;
2053
2054                 res = PQexec(AH->connection, cmd->data);
2055
2056                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2057                         /* NOT warn_or_die_horribly... use -O instead to skip this. */
2058                         die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2059                                                  user, PQerrorMessage(AH->connection));
2060
2061                 PQclear(res);
2062         }
2063         else
2064                 ahprintf(AH, "%s\n\n", cmd->data);
2065
2066         destroyPQExpBuffer(cmd);
2067 }
2068
2069
2070 /*
2071  * Issue a SET default_with_oids command.  Caller is responsible
2072  * for updating state if appropriate.
2073  */
2074 static void
2075 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2076 {
2077         PQExpBuffer cmd = createPQExpBuffer();
2078
2079         appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2080                                           "true" : "false");
2081
2082         if (RestoringToDB(AH))
2083         {
2084                 PGresult   *res;
2085
2086                 res = PQexec(AH->connection, cmd->data);
2087
2088                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2089                         warn_or_die_horribly(AH, modulename,
2090                                                                  "could not set default_with_oids: %s",
2091                                                                  PQerrorMessage(AH->connection));
2092
2093                 PQclear(res);
2094         }
2095         else
2096                 ahprintf(AH, "%s\n\n", cmd->data);
2097
2098         destroyPQExpBuffer(cmd);
2099 }
2100
2101
2102 /*
2103  * Issue the commands to connect to the specified database.
2104  *
2105  * If we're currently restoring right into a database, this will
2106  * actually establish a connection. Otherwise it puts a \connect into
2107  * the script output.
2108  *
2109  * NULL dbname implies reconnecting to the current DB (pretty useless).
2110  */
2111 static void
2112 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2113 {
2114         if (RestoringToDB(AH))
2115                 ReconnectToServer(AH, dbname, NULL);
2116         else
2117         {
2118                 PQExpBuffer qry = createPQExpBuffer();
2119
2120                 appendPQExpBuffer(qry, "\\connect %s\n\n",
2121                                                   dbname ? fmtId(dbname) : "-");
2122                 ahprintf(AH, "%s", qry->data);
2123                 destroyPQExpBuffer(qry);
2124         }
2125
2126         /*
2127          * NOTE: currUser keeps track of what the imaginary session user in our
2128          * script is.  It's now effectively reset to the original userID.
2129          */
2130         if (AH->currUser)
2131                 free(AH->currUser);
2132
2133         AH->currUser = strdup("");
2134
2135         /* don't assume we still know the output schema */
2136         if (AH->currSchema)
2137                 free(AH->currSchema);
2138         AH->currSchema = strdup("");
2139         AH->currWithOids = -1;
2140
2141         /* re-establish fixed state */
2142         _doSetFixedOutputState(AH);
2143 }
2144
2145 /*
2146  * Become the specified user, and update state to avoid redundant commands
2147  *
2148  * NULL or empty argument is taken to mean restoring the session default
2149  */
2150 static void
2151 _becomeUser(ArchiveHandle *AH, const char *user)
2152 {
2153         if (!user)
2154                 user = "";                              /* avoid null pointers */
2155
2156         if (AH->currUser && strcmp(AH->currUser, user) == 0)
2157                 return;                                 /* no need to do anything */
2158
2159         _doSetSessionAuth(AH, user);
2160
2161         /*
2162          * NOTE: currUser keeps track of what the imaginary session user in our
2163          * script is
2164          */
2165         if (AH->currUser)
2166                 free(AH->currUser);
2167
2168         AH->currUser = strdup(user);
2169 }
2170
2171 /*
2172  * Become the owner of the the given TOC entry object.  If
2173  * changes in ownership are not allowed, this doesn't do anything.
2174  */
2175 static void
2176 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2177 {
2178         if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2179                 return;
2180
2181         _becomeUser(AH, te->owner);
2182 }
2183
2184
2185 /*
2186  * Set the proper default_with_oids value for the table.
2187  */
2188 static void
2189 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2190 {
2191         if (AH->currWithOids != te->withOids)
2192         {
2193                 _doSetWithOids(AH, te->withOids);
2194                 AH->currWithOids = te->withOids;
2195         }
2196 }
2197
2198
2199 /*
2200  * Issue the commands to select the specified schema as the current schema
2201  * in the target database.
2202  */
2203 static void
2204 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2205 {
2206         PQExpBuffer qry;
2207
2208         if (!schemaName || *schemaName == '\0' ||
2209                 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2210                 return;                                 /* no need to do anything */
2211
2212         qry = createPQExpBuffer();
2213
2214         appendPQExpBuffer(qry, "SET search_path = %s",
2215                                           fmtId(schemaName));
2216         if (strcmp(schemaName, "pg_catalog") != 0)
2217                 appendPQExpBuffer(qry, ", pg_catalog");
2218
2219         if (RestoringToDB(AH))
2220         {
2221                 PGresult   *res;
2222
2223                 res = PQexec(AH->connection, qry->data);
2224
2225                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2226                         warn_or_die_horribly(AH, modulename,
2227                                                                  "could not set search_path to \"%s\": %s",
2228                                                                  schemaName, PQerrorMessage(AH->connection));
2229
2230                 PQclear(res);
2231         }
2232         else
2233                 ahprintf(AH, "%s;\n\n", qry->data);
2234
2235         if (AH->currSchema)
2236                 free(AH->currSchema);
2237         AH->currSchema = strdup(schemaName);
2238
2239         destroyPQExpBuffer(qry);
2240 }
2241
2242 /*
2243  * Issue the commands to select the specified tablespace as the current one
2244  * in the target database.
2245  */
2246 static void
2247 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2248 {
2249         PQExpBuffer qry;
2250         const char *want,
2251                            *have;
2252
2253         have = AH->currTablespace;
2254         want = tablespace;
2255
2256         /* no need to do anything for non-tablespace object */
2257         if (!want)
2258                 return;
2259
2260         if (have && strcmp(want, have) == 0)
2261                 return;                                 /* no need to do anything */
2262
2263         qry = createPQExpBuffer();
2264
2265         if (strcmp(want, "") == 0)
2266         {
2267                 /* We want the tablespace to be the database's default */
2268                 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2269         }
2270         else
2271         {
2272                 /* We want an explicit tablespace */
2273                 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2274         }
2275
2276         if (RestoringToDB(AH))
2277         {
2278                 PGresult   *res;
2279
2280                 res = PQexec(AH->connection, qry->data);
2281
2282                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2283                         warn_or_die_horribly(AH, modulename,
2284                                                                  "could not set default_tablespace to %s: %s",
2285                                                                  fmtId(want), PQerrorMessage(AH->connection));
2286
2287                 PQclear(res);
2288         }
2289         else
2290                 ahprintf(AH, "%s;\n\n", qry->data);
2291
2292         if (AH->currTablespace)
2293                 free(AH->currTablespace);
2294         AH->currTablespace = strdup(want);
2295
2296         destroyPQExpBuffer(qry);
2297 }
2298
2299 /*
2300  * Extract an object description for a TOC entry, and append it to buf.
2301  *
2302  * This is not quite as general as it may seem, since it really only
2303  * handles constructing the right thing to put into ALTER ... OWNER TO.
2304  *
2305  * The whole thing is pretty grotty, but we are kind of stuck since the
2306  * information used is all that's available in older dump files.
2307  */
2308 static void
2309 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2310 {
2311         const char *type = te->desc;
2312
2313         /* Use ALTER TABLE for views and sequences */
2314         if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2315                 type = "TABLE";
2316
2317         /* objects named by a schema and name */
2318         if (strcmp(type, "CONVERSION") == 0 ||
2319                 strcmp(type, "DOMAIN") == 0 ||
2320                 strcmp(type, "TABLE") == 0 ||
2321                 strcmp(type, "TYPE") == 0)
2322         {
2323                 appendPQExpBuffer(buf, "%s ", type);
2324                 if (te->namespace && te->namespace[0])  /* is null pre-7.3 */
2325                         appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2326
2327                 /*
2328                  * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2329                  * into te->tag for an index. This check is heuristic, so make its
2330                  * scope as narrow as possible.
2331                  */
2332                 if (AH->version < K_VERS_1_7 &&
2333                         te->tag[0] == '"' &&
2334                         te->tag[strlen(te->tag) - 1] == '"' &&
2335                         strcmp(type, "INDEX") == 0)
2336                         appendPQExpBuffer(buf, "%s", te->tag);
2337                 else
2338                         appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2339                 return;
2340         }
2341
2342         /* objects named by just a name */
2343         if (strcmp(type, "DATABASE") == 0 ||
2344                 strcmp(type, "SCHEMA") == 0)
2345         {
2346                 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2347                 return;
2348         }
2349
2350         /*
2351          * These object types require additional decoration.  Fortunately, the
2352          * information needed is exactly what's in the DROP command.
2353          */
2354         if (strcmp(type, "AGGREGATE") == 0 ||
2355                 strcmp(type, "FUNCTION") == 0 ||
2356                 strcmp(type, "OPERATOR") == 0 ||
2357                 strcmp(type, "OPERATOR CLASS") == 0)
2358         {
2359                 /* Chop "DROP " off the front and make a modifiable copy */
2360                 char       *first = strdup(te->dropStmt + 5);
2361                 char       *last;
2362
2363                 /* point to last character in string */
2364                 last = first + strlen(first) - 1;
2365
2366                 /* Strip off any ';' or '\n' at the end */
2367                 while (last >= first && (*last == '\n' || *last == ';'))
2368                         last--;
2369                 *(last + 1) = '\0';
2370
2371                 appendPQExpBufferStr(buf, first);
2372
2373                 free(first);
2374                 return;
2375         }
2376
2377         write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2378                           type);
2379 }
2380
2381 static void
2382 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2383 {
2384         /* ACLs are dumped only during acl pass */
2385         if (acl_pass)
2386         {
2387                 if (strcmp(te->desc, "ACL") != 0)
2388                         return;
2389         }
2390         else
2391         {
2392                 if (strcmp(te->desc, "ACL") == 0)
2393                         return;
2394         }
2395
2396         /*
2397          * Avoid dumping the public schema, as it will already be created ...
2398          * unless we are using --clean mode, in which case it's been deleted and
2399          * we'd better recreate it.
2400          */
2401         if (!ropt->dropSchema &&
2402                 strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
2403                 return;
2404
2405         /* Select owner, schema, and tablespace as necessary */
2406         _becomeOwner(AH, te);
2407         _selectOutputSchema(AH, te->namespace);
2408         _selectTablespace(AH, te->tablespace);
2409
2410         /* Set up OID mode too */
2411         if (strcmp(te->desc, "TABLE") == 0)
2412                 _setWithOids(AH, te);
2413
2414         /* Emit header comment for item */
2415         if (!AH->noTocComments)
2416         {
2417                 const char *pfx;
2418
2419                 if (isData)
2420                         pfx = "Data for ";
2421                 else
2422                         pfx = "";
2423
2424                 ahprintf(AH, "--\n");
2425                 if (AH->public.verbose)
2426                 {
2427                         ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2428                                          te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2429                         if (te->nDeps > 0)
2430                         {
2431                                 int                     i;
2432
2433                                 ahprintf(AH, "-- Dependencies:");
2434                                 for (i = 0; i < te->nDeps; i++)
2435                                         ahprintf(AH, " %d", te->dependencies[i]);
2436                                 ahprintf(AH, "\n");
2437                         }
2438                 }
2439                 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2440                                  pfx, te->tag, te->desc,
2441                                  te->namespace ? te->namespace : "-",
2442                                  ropt->noOwner ? "-" : te->owner);
2443                 if (te->tablespace)
2444                         ahprintf(AH, "; Tablespace: %s", te->tablespace);
2445                 ahprintf(AH, "\n");
2446
2447                 if (AH->PrintExtraTocPtr !=NULL)
2448                         (*AH->PrintExtraTocPtr) (AH, te);
2449                 ahprintf(AH, "--\n\n");
2450         }
2451
2452         /*
2453          * Actually print the definition.
2454          *
2455          * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2456          * versions put into CREATE SCHEMA.  We have to do this when --no-owner
2457          * mode is selected.  This is ugly, but I see no other good way ...
2458          */
2459         if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2460         {
2461                 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2462         }
2463         else
2464         {
2465                 if (strlen(te->defn) > 0)
2466                         ahprintf(AH, "%s\n\n", te->defn);
2467         }
2468
2469         /*
2470          * If we aren't using SET SESSION AUTH to determine ownership, we must
2471          * instead issue an ALTER OWNER command.  We assume that anything without
2472          * a DROP command is not a separately ownable object.  All the categories
2473          * with DROP commands must appear in one list or the other.
2474          */
2475         if (!ropt->noOwner && !ropt->use_setsessauth &&
2476                 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2477         {
2478                 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2479                         strcmp(te->desc, "CONVERSION") == 0 ||
2480                         strcmp(te->desc, "DATABASE") == 0 ||
2481                         strcmp(te->desc, "DOMAIN") == 0 ||
2482                         strcmp(te->desc, "FUNCTION") == 0 ||
2483                         strcmp(te->desc, "OPERATOR") == 0 ||
2484                         strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2485                         strcmp(te->desc, "SCHEMA") == 0 ||
2486                         strcmp(te->desc, "TABLE") == 0 ||
2487                         strcmp(te->desc, "TYPE") == 0 ||
2488                         strcmp(te->desc, "VIEW") == 0 ||
2489                         strcmp(te->desc, "SEQUENCE") == 0)
2490                 {
2491                         PQExpBuffer temp = createPQExpBuffer();
2492
2493                         appendPQExpBuffer(temp, "ALTER ");
2494                         _getObjectDescription(temp, te, AH);
2495                         appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2496                         ahprintf(AH, "%s\n\n", temp->data);
2497                         destroyPQExpBuffer(temp);
2498                 }
2499                 else if (strcmp(te->desc, "CAST") == 0 ||
2500                                  strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2501                                  strcmp(te->desc, "CONSTRAINT") == 0 ||
2502                                  strcmp(te->desc, "DEFAULT") == 0 ||
2503                                  strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2504                                  strcmp(te->desc, "INDEX") == 0 ||
2505                                  strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2506                                  strcmp(te->desc, "RULE") == 0 ||
2507                                  strcmp(te->desc, "TRIGGER") == 0)
2508                 {
2509                         /* these object types don't have separate owners */
2510                 }
2511                 else
2512                 {
2513                         write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2514                                           te->desc);
2515                 }
2516         }
2517
2518         /*
2519          * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2520          * commands, so we can no longer assume we know the current auth setting.
2521          */
2522         if (strncmp(te->desc, "ACL", 3) == 0)
2523         {
2524                 if (AH->currUser)
2525                         free(AH->currUser);
2526                 AH->currUser = NULL;
2527         }
2528 }
2529
2530 void
2531 WriteHead(ArchiveHandle *AH)
2532 {
2533         struct tm       crtm;
2534
2535         (*AH->WriteBufPtr) (AH, "PGDMP", 5);            /* Magic code */
2536         (*AH->WriteBytePtr) (AH, AH->vmaj);
2537         (*AH->WriteBytePtr) (AH, AH->vmin);
2538         (*AH->WriteBytePtr) (AH, AH->vrev);
2539         (*AH->WriteBytePtr) (AH, AH->intSize);
2540         (*AH->WriteBytePtr) (AH, AH->offSize);
2541         (*AH->WriteBytePtr) (AH, AH->format);
2542
2543 #ifndef HAVE_LIBZ
2544         if (AH->compression != 0)
2545                 write_msg(modulename, "WARNING: requested compression not available in this "
2546                                   "installation -- archive will be uncompressed\n");
2547
2548         AH->compression = 0;
2549 #endif
2550
2551         WriteInt(AH, AH->compression);
2552
2553         crtm = *localtime(&AH->createDate);
2554         WriteInt(AH, crtm.tm_sec);
2555         WriteInt(AH, crtm.tm_min);
2556         WriteInt(AH, crtm.tm_hour);
2557         WriteInt(AH, crtm.tm_mday);
2558         WriteInt(AH, crtm.tm_mon);
2559         WriteInt(AH, crtm.tm_year);
2560         WriteInt(AH, crtm.tm_isdst);
2561         WriteStr(AH, PQdb(AH->connection));
2562         WriteStr(AH, AH->public.remoteVersionStr);
2563         WriteStr(AH, PG_VERSION);
2564 }
2565
2566 void
2567 ReadHead(ArchiveHandle *AH)
2568 {
2569         char            tmpMag[7];
2570         int                     fmt;
2571         struct tm       crtm;
2572
2573         /* If we haven't already read the header... */
2574         if (!AH->readHeader)
2575         {
2576
2577                 (*AH->ReadBufPtr) (AH, tmpMag, 5);
2578
2579                 if (strncmp(tmpMag, "PGDMP", 5) != 0)
2580                         die_horribly(AH, modulename, "did not find magic string in file header\n");
2581
2582                 AH->vmaj = (*AH->ReadBytePtr) (AH);
2583                 AH->vmin = (*AH->ReadBytePtr) (AH);
2584
2585                 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))                /* Version > 1.0 */
2586                         AH->vrev = (*AH->ReadBytePtr) (AH);
2587                 else
2588                         AH->vrev = 0;
2589
2590                 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
2591
2592
2593                 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2594                         die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
2595                                                  AH->vmaj, AH->vmin);
2596
2597                 AH->intSize = (*AH->ReadBytePtr) (AH);
2598                 if (AH->intSize > 32)
2599                         die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
2600                                                  (unsigned long) AH->intSize);
2601
2602                 if (AH->intSize > sizeof(int))
2603                         write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations may fail\n");
2604
2605                 if (AH->version >= K_VERS_1_7)
2606                         AH->offSize = (*AH->ReadBytePtr) (AH);
2607                 else
2608                         AH->offSize = AH->intSize;
2609
2610                 fmt = (*AH->ReadBytePtr) (AH);
2611
2612                 if (AH->format != fmt)
2613                         die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
2614                                                  AH->format, fmt);
2615         }
2616
2617         if (AH->version >= K_VERS_1_2)
2618         {
2619                 if (AH->version < K_VERS_1_4)
2620                         AH->compression = (*AH->ReadBytePtr) (AH);
2621                 else
2622                         AH->compression = ReadInt(AH);
2623         }
2624         else
2625                 AH->compression = Z_DEFAULT_COMPRESSION;
2626
2627 #ifndef HAVE_LIBZ
2628         if (AH->compression != 0)
2629                 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
2630 #endif
2631
2632         if (AH->version >= K_VERS_1_4)
2633         {
2634                 crtm.tm_sec = ReadInt(AH);
2635                 crtm.tm_min = ReadInt(AH);
2636                 crtm.tm_hour = ReadInt(AH);
2637                 crtm.tm_mday = ReadInt(AH);
2638                 crtm.tm_mon = ReadInt(AH);
2639                 crtm.tm_year = ReadInt(AH);
2640                 crtm.tm_isdst = ReadInt(AH);
2641
2642                 AH->archdbname = ReadStr(AH);
2643
2644                 AH->createDate = mktime(&crtm);
2645
2646                 if (AH->createDate == (time_t) -1)
2647                         write_msg(modulename, "WARNING: invalid creation date in header\n");
2648         }
2649
2650         if (AH->version >= K_VERS_1_10)
2651         {
2652                 AH->archiveRemoteVersion = ReadStr(AH);
2653                 AH->archiveDumpVersion = ReadStr(AH);
2654         }
2655
2656 }
2657
2658
2659 /*
2660  * checkSeek
2661  *        check to see if fseek can be performed.
2662  */
2663
2664 bool
2665 checkSeek(FILE *fp)
2666 {
2667
2668         if (fseeko(fp, 0, SEEK_CUR) != 0)
2669                 return false;
2670         else if (sizeof(off_t) > sizeof(long))
2671
2672                 /*
2673                  * At this point, off_t is too large for long, so we return based on
2674                  * whether an off_t version of fseek is available.
2675                  */
2676 #ifdef HAVE_FSEEKO
2677                 return true;
2678 #else
2679                 return false;
2680 #endif
2681         else
2682                 return true;
2683 }
2684
2685
2686 /*
2687  * dumpTimestamp
2688  */
2689 static void
2690 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
2691 {
2692         char            buf[256];
2693
2694         if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&tim)) != 0)
2695                 ahprintf(AH, "-- %s %s\n\n", msg, buf);
2696 }