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