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