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