]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_backup_archiver.c
Suppress possibly-uninitialized-variable warnings from gcc 4.5.
[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  *              src/bin/pg_dump/pg_backup_archiver.c
19  *
20  *-------------------------------------------------------------------------
21  */
22
23 #include "pg_backup_db.h"
24 #include "dumputils.h"
25
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30
31 #ifdef WIN32
32 #include <io.h>
33 #endif
34
35 #include "libpq/libpq-fs.h"
36
37 /*
38  * Special exit values from worker children.  We reserve 0 for normal
39  * success; 1 and other small values should be interpreted as crashes.
40  */
41 #define WORKER_CREATE_DONE              10
42 #define WORKER_INHIBIT_DATA             11
43 #define WORKER_IGNORED_ERRORS   12
44
45 /*
46  * Unix uses exit to return result from worker child, so function is void.
47  * Windows thread result comes via function return.
48  */
49 #ifndef WIN32
50 #define parallel_restore_result void
51 #else
52 #define parallel_restore_result DWORD
53 #endif
54
55 /* IDs for worker children are either PIDs or thread handles */
56 #ifndef WIN32
57 #define thandle pid_t
58 #else
59 #define thandle HANDLE
60 #endif
61
62 /* Arguments needed for a worker child */
63 typedef struct _restore_args
64 {
65         ArchiveHandle *AH;
66         TocEntry   *te;
67 } RestoreArgs;
68
69 /* State for each parallel activity slot */
70 typedef struct _parallel_slot
71 {
72         thandle         child_id;
73         RestoreArgs *args;
74 } ParallelSlot;
75
76 #define NO_SLOT (-1)
77
78 /* state needed to save/restore an archive's output target */
79 typedef struct _outputContext
80 {
81         void       *OF;
82         int                     gzOut;
83 } OutputContext;
84
85 const char *progname;
86
87 static const char *modulename = gettext_noop("archiver");
88
89 /* index array created by fix_dependencies -- only used in parallel restore */
90 static TocEntry   **tocsByDumpId;                       /* index by dumpId - 1 */
91 static DumpId           maxDumpId;                              /* length of above array */
92
93
94 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
95                  const int compression, ArchiveMode mode);
96 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
97                                           ArchiveHandle *AH);
98 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
99
100
101 static void _doSetFixedOutputState(ArchiveHandle *AH);
102 static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
103 static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
104 static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
105 static void _becomeUser(ArchiveHandle *AH, const char *user);
106 static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
107 static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
108 static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
109 static void processEncodingEntry(ArchiveHandle *AH, TocEntry *te);
110 static void processStdStringsEntry(ArchiveHandle *AH, TocEntry *te);
111 static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
112 static bool _tocEntryIsACL(TocEntry *te);
113 static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
114 static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
115 static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
116 static void _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
117 static int      _discoverArchiveFormat(ArchiveHandle *AH);
118
119 static void dump_lo_buf(ArchiveHandle *AH);
120 static void _write_msg(const char *modulename, const char *fmt, va_list ap);
121 static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
122
123 static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
124 static void SetOutput(ArchiveHandle *AH, char *filename, int compression);
125 static OutputContext SaveOutput(ArchiveHandle *AH);
126 static void RestoreOutput(ArchiveHandle *AH, OutputContext savedContext);
127
128 static int restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
129                                   RestoreOptions *ropt, bool is_parallel);
130 static void restore_toc_entries_parallel(ArchiveHandle *AH);
131 static thandle spawn_restore(RestoreArgs *args);
132 static thandle reap_child(ParallelSlot *slots, int n_slots, int *work_status);
133 static bool work_in_progress(ParallelSlot *slots, int n_slots);
134 static int      get_next_slot(ParallelSlot *slots, int n_slots);
135 static void par_list_header_init(TocEntry *l);
136 static void par_list_append(TocEntry *l, TocEntry *te);
137 static void par_list_remove(TocEntry *te);
138 static TocEntry *get_next_work_item(ArchiveHandle *AH,
139                                    TocEntry *ready_list,
140                                    ParallelSlot *slots, int n_slots);
141 static parallel_restore_result parallel_restore(RestoreArgs *args);
142 static void mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
143                            thandle worker, int status,
144                            ParallelSlot *slots, int n_slots);
145 static void fix_dependencies(ArchiveHandle *AH);
146 static bool has_lock_conflicts(TocEntry *te1, TocEntry *te2);
147 static void repoint_table_dependencies(ArchiveHandle *AH,
148                                                    DumpId tableId, DumpId tableDataId);
149 static void identify_locking_dependencies(TocEntry *te);
150 static void reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
151                                         TocEntry *ready_list);
152 static void mark_create_done(ArchiveHandle *AH, TocEntry *te);
153 static void inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te);
154 static ArchiveHandle *CloneArchive(ArchiveHandle *AH);
155 static void DeCloneArchive(ArchiveHandle *AH);
156
157
158 /*
159  *      Wrapper functions.
160  *
161  *      The objective it to make writing new formats and dumpers as simple
162  *      as possible, if necessary at the expense of extra function calls etc.
163  *
164  */
165
166
167 /* Create a new archive */
168 /* Public */
169 Archive *
170 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
171                           const int compression, ArchiveMode mode)
172
173 {
174         ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode);
175
176         return (Archive *) AH;
177 }
178
179 /* Open an existing archive */
180 /* Public */
181 Archive *
182 OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
183 {
184         ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);
185
186         return (Archive *) AH;
187 }
188
189 /* Public */
190 void
191 CloseArchive(Archive *AHX)
192 {
193         int                     res = 0;
194         ArchiveHandle *AH = (ArchiveHandle *) AHX;
195
196         (*AH->ClosePtr) (AH);
197
198         /* Close the output */
199         if (AH->gzOut)
200                 res = GZCLOSE(AH->OF);
201         else if (AH->OF != stdout)
202                 res = fclose(AH->OF);
203
204         if (res != 0)
205                 die_horribly(AH, modulename, "could not close output file: %s\n",
206                                          strerror(errno));
207 }
208
209 /* Public */
210 void
211 RestoreArchive(Archive *AHX, RestoreOptions *ropt)
212 {
213         ArchiveHandle *AH = (ArchiveHandle *) AHX;
214         TocEntry   *te;
215         teReqs          reqs;
216         OutputContext sav;
217
218         AH->ropt = ropt;
219         AH->stage = STAGE_INITIALIZING;
220
221         /*
222          * Check for nonsensical option combinations.
223          *
224          * NB: createDB+dropSchema is useless because if you're creating the DB,
225          * there's no need to drop individual items in it.  Moreover, if we tried
226          * to do that then we'd issue the drops in the database initially
227          * connected to, not the one we will create, which is very bad...
228          */
229         if (ropt->createDB && ropt->dropSchema)
230                 die_horribly(AH, modulename, "-C and -c are incompatible options\n");
231
232         /*
233          * -C is not compatible with -1, because we can't create a database inside
234          * a transaction block.
235          */
236         if (ropt->createDB && ropt->single_txn)
237                 die_horribly(AH, modulename, "-C and -1 are incompatible options\n");
238
239         /*
240          * Make sure we won't need (de)compression we haven't got
241          */
242 #ifndef HAVE_LIBZ
243         if (AH->compression != 0 && AH->PrintTocDataPtr !=NULL)
244         {
245                 for (te = AH->toc->next; te != AH->toc; te = te->next)
246                 {
247                         reqs = _tocEntryRequired(te, ropt, false);
248                         if (te->hadDumper && (reqs & REQ_DATA) != 0)
249                                 die_horribly(AH, modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
250                 }
251         }
252 #endif
253
254         /*
255          * If we're using a DB connection, then connect it.
256          */
257         if (ropt->useDB)
258         {
259                 ahlog(AH, 1, "connecting to database for restore\n");
260                 if (AH->version < K_VERS_1_3)
261                         die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
262
263                 /* XXX Should get this from the archive */
264                 AHX->minRemoteVersion = 070100;
265                 AHX->maxRemoteVersion = 999999;
266
267                 ConnectDatabase(AHX, ropt->dbname,
268                                                 ropt->pghost, ropt->pgport, ropt->username,
269                                                 ropt->promptPassword);
270
271                 /*
272                  * If we're talking to the DB directly, don't send comments since they
273                  * obscure SQL when displaying errors
274                  */
275                 AH->noTocComments = 1;
276         }
277
278         /*
279          * Work out if we have an implied data-only restore. This can happen if
280          * the dump was data only or if the user has used a toc list to exclude
281          * all of the schema data. All we do is look for schema entries - if none
282          * are found then we set the dataOnly flag.
283          *
284          * We could scan for wanted TABLE entries, but that is not the same as
285          * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
286          */
287         if (!ropt->dataOnly)
288         {
289                 int                     impliedDataOnly = 1;
290
291                 for (te = AH->toc->next; te != AH->toc; te = te->next)
292                 {
293                         reqs = _tocEntryRequired(te, ropt, true);
294                         if ((reqs & REQ_SCHEMA) != 0)
295                         {                                       /* It's schema, and it's wanted */
296                                 impliedDataOnly = 0;
297                                 break;
298                         }
299                 }
300                 if (impliedDataOnly)
301                 {
302                         ropt->dataOnly = impliedDataOnly;
303                         ahlog(AH, 1, "implied data-only restore\n");
304                 }
305         }
306
307         /*
308          * Setup the output file if necessary.
309          */
310         sav = SaveOutput(AH);
311         if (ropt->filename || ropt->compression)
312                 SetOutput(AH, ropt->filename, ropt->compression);
313
314         ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
315
316         if (AH->public.verbose)
317         {
318                 if (AH->archiveRemoteVersion)
319                         ahprintf(AH, "-- Dumped from database version %s\n",
320                                          AH->archiveRemoteVersion);
321                 if (AH->archiveDumpVersion)
322                         ahprintf(AH, "-- Dumped by pg_dump version %s\n",
323                                          AH->archiveDumpVersion);
324                 dumpTimestamp(AH, "Started on", AH->createDate);
325         }
326
327         if (ropt->single_txn)
328         {
329                 if (AH->connection)
330                         StartTransaction(AH);
331                 else
332                         ahprintf(AH, "BEGIN;\n\n");
333         }
334
335         /*
336          * Establish important parameter values right away.
337          */
338         _doSetFixedOutputState(AH);
339
340         AH->stage = STAGE_PROCESSING;
341
342         /*
343          * Drop the items at the start, in reverse order
344          */
345         if (ropt->dropSchema)
346         {
347                 for (te = AH->toc->prev; te != AH->toc; te = te->prev)
348                 {
349                         AH->currentTE = te;
350
351                         reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
352                         /* We want anything that's selected and has a dropStmt */
353                         if (((reqs & (REQ_SCHEMA | REQ_DATA)) != 0) && te->dropStmt)
354                         {
355                                 ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
356                                 /* Select owner and schema as necessary */
357                                 _becomeOwner(AH, te);
358                                 _selectOutputSchema(AH, te->namespace);
359                                 /* Drop it */
360                                 ahprintf(AH, "%s", te->dropStmt);
361                         }
362                 }
363
364                 /*
365                  * _selectOutputSchema may have set currSchema to reflect the effect
366                  * of a "SET search_path" command it emitted.  However, by now we may
367                  * have dropped that schema; or it might not have existed in the first
368                  * place.  In either case the effective value of search_path will not
369                  * be what we think.  Forcibly reset currSchema so that we will
370                  * re-establish the search_path setting when needed (after creating
371                  * the schema).
372                  *
373                  * If we treated users as pg_dump'able objects then we'd need to reset
374                  * currUser here too.
375                  */
376                 if (AH->currSchema)
377                         free(AH->currSchema);
378                 AH->currSchema = NULL;
379         }
380
381         /*
382          * In serial mode, we now process each non-ACL TOC entry.
383          *
384          * In parallel mode, turn control over to the parallel-restore logic.
385          */
386         if (ropt->number_of_jobs > 1 && ropt->useDB)
387                 restore_toc_entries_parallel(AH);
388         else
389         {
390                 for (te = AH->toc->next; te != AH->toc; te = te->next)
391                         (void) restore_toc_entry(AH, te, ropt, false);
392         }
393
394         /*
395          * Scan TOC again to output ownership commands and ACLs
396          */
397         for (te = AH->toc->next; te != AH->toc; te = te->next)
398         {
399                 AH->currentTE = te;
400
401                 /* Work out what, if anything, we want from this entry */
402                 reqs = _tocEntryRequired(te, ropt, true);
403
404                 /* Both schema and data objects might now have ownership/ACLs */
405                 if ((reqs & (REQ_SCHEMA | REQ_DATA)) != 0)
406                 {
407                         ahlog(AH, 1, "setting owner and privileges for %s %s\n",
408                                   te->desc, te->tag);
409                         _printTocEntry(AH, te, ropt, false, true);
410                 }
411         }
412
413         if (ropt->single_txn)
414         {
415                 if (AH->connection)
416                         CommitTransaction(AH);
417                 else
418                         ahprintf(AH, "COMMIT;\n\n");
419         }
420
421         if (AH->public.verbose)
422                 dumpTimestamp(AH, "Completed on", time(NULL));
423
424         ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
425
426         /*
427          * Clean up & we're done.
428          */
429         AH->stage = STAGE_FINALIZING;
430
431         if (ropt->filename || ropt->compression)
432                 RestoreOutput(AH, sav);
433
434         if (ropt->useDB)
435         {
436                 PQfinish(AH->connection);
437                 AH->connection = NULL;
438         }
439 }
440
441 /*
442  * Restore a single TOC item.  Used in both parallel and non-parallel restore;
443  * is_parallel is true if we are in a worker child process.
444  *
445  * Returns 0 normally, but WORKER_CREATE_DONE or WORKER_INHIBIT_DATA if
446  * the parallel parent has to make the corresponding status update.
447  */
448 static int
449 restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
450                                   RestoreOptions *ropt, bool is_parallel)
451 {
452         int                     retval = 0;
453         teReqs          reqs;
454         bool            defnDumped;
455
456         AH->currentTE = te;
457
458         /* Work out what, if anything, we want from this entry */
459         reqs = _tocEntryRequired(te, ropt, false);
460
461         /* Dump any relevant dump warnings to stderr */
462         if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
463         {
464                 if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
465                         write_msg(modulename, "warning from original dump file: %s\n", te->defn);
466                 else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
467                         write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
468         }
469
470         defnDumped = false;
471
472         if ((reqs & REQ_SCHEMA) != 0)           /* We want the schema */
473         {
474                 ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
475
476                 _printTocEntry(AH, te, ropt, false, false);
477                 defnDumped = true;
478
479                 if (strcmp(te->desc, "TABLE") == 0)
480                 {
481                         if (AH->lastErrorTE == te)
482                         {
483                                 /*
484                                  * We failed to create the table. If
485                                  * --no-data-for-failed-tables was given, mark the
486                                  * corresponding TABLE DATA to be ignored.
487                                  *
488                                  * In the parallel case this must be done in the parent, so we
489                                  * just set the return value.
490                                  */
491                                 if (ropt->noDataForFailedTables)
492                                 {
493                                         if (is_parallel)
494                                                 retval = WORKER_INHIBIT_DATA;
495                                         else
496                                                 inhibit_data_for_failed_table(AH, te);
497                                 }
498                         }
499                         else
500                         {
501                                 /*
502                                  * We created the table successfully.  Mark the corresponding
503                                  * TABLE DATA for possible truncation.
504                                  *
505                                  * In the parallel case this must be done in the parent, so we
506                                  * just set the return value.
507                                  */
508                                 if (is_parallel)
509                                         retval = WORKER_CREATE_DONE;
510                                 else
511                                         mark_create_done(AH, te);
512                         }
513                 }
514
515                 /* If we created a DB, connect to it... */
516                 if (strcmp(te->desc, "DATABASE") == 0)
517                 {
518                         ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
519                         _reconnectToDB(AH, te->tag);
520                         ropt->dbname = strdup(te->tag);
521                 }
522         }
523
524         /*
525          * If we have a data component, then process it
526          */
527         if ((reqs & REQ_DATA) != 0)
528         {
529                 /*
530                  * hadDumper will be set if there is genuine data component for this
531                  * node. Otherwise, we need to check the defn field for statements
532                  * that need to be executed in data-only restores.
533                  */
534                 if (te->hadDumper)
535                 {
536                         /*
537                          * If we can output the data, then restore it.
538                          */
539                         if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
540                         {
541                                 _printTocEntry(AH, te, ropt, true, false);
542
543                                 if (strcmp(te->desc, "BLOBS") == 0 ||
544                                         strcmp(te->desc, "BLOB COMMENTS") == 0)
545                                 {
546                                         ahlog(AH, 1, "restoring %s\n", te->desc);
547
548                                         _selectOutputSchema(AH, "pg_catalog");
549
550                                         (*AH->PrintTocDataPtr) (AH, te, ropt);
551                                 }
552                                 else
553                                 {
554                                         _disableTriggersIfNecessary(AH, te, ropt);
555
556                                         /* Select owner and schema as necessary */
557                                         _becomeOwner(AH, te);
558                                         _selectOutputSchema(AH, te->namespace);
559
560                                         ahlog(AH, 1, "restoring data for table \"%s\"\n",
561                                                   te->tag);
562
563                                         /*
564                                          * In parallel restore, if we created the table earlier in
565                                          * the run then we wrap the COPY in a transaction and
566                                          * precede it with a TRUNCATE.  If archiving is not on
567                                          * this prevents WAL-logging the COPY.  This obtains a
568                                          * speedup similar to that from using single_txn mode in
569                                          * non-parallel restores.
570                                          */
571                                         if (is_parallel && te->created)
572                                         {
573                                                 /*
574                                                  * Parallel restore is always talking directly to a
575                                                  * server, so no need to see if we should issue BEGIN.
576                                                  */
577                                                 StartTransaction(AH);
578
579                                                 /*
580                                                  * If the server version is >= 8.4, make sure we issue
581                                                  * TRUNCATE with ONLY so that child tables are not
582                                                  * wiped.
583                                                  */
584                                                 ahprintf(AH, "TRUNCATE TABLE %s%s;\n\n",
585                                                                  (PQserverVersion(AH->connection) >= 80400 ?
586                                                                   "ONLY " : ""),
587                                                                  fmtId(te->tag));
588                                         }
589
590                                         /*
591                                          * If we have a copy statement, use it. As of V1.3, these
592                                          * are separate to allow easy import from withing a
593                                          * database connection. Pre 1.3 archives can not use DB
594                                          * connections and are sent to output only.
595                                          *
596                                          * For V1.3+, the table data MUST have a copy statement so
597                                          * that we can go into appropriate mode with libpq.
598                                          */
599                                         if (te->copyStmt && strlen(te->copyStmt) > 0)
600                                         {
601                                                 ahprintf(AH, "%s", te->copyStmt);
602                                                 AH->writingCopyData = true;
603                                         }
604
605                                         (*AH->PrintTocDataPtr) (AH, te, ropt);
606
607                                         AH->writingCopyData = false;
608
609                                         /* close out the transaction started above */
610                                         if (is_parallel && te->created)
611                                                 CommitTransaction(AH);
612
613                                         _enableTriggersIfNecessary(AH, te, ropt);
614                                 }
615                         }
616                 }
617                 else if (!defnDumped)
618                 {
619                         /* If we haven't already dumped the defn part, do so now */
620                         ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
621                         _printTocEntry(AH, te, ropt, false, false);
622                 }
623         }
624
625         return retval;
626 }
627
628 /*
629  * Allocate a new RestoreOptions block.
630  * This is mainly so we can initialize it, but also for future expansion,
631  */
632 RestoreOptions *
633 NewRestoreOptions(void)
634 {
635         RestoreOptions *opts;
636
637         opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
638
639         /* set any fields that shouldn't default to zeroes */
640         opts->format = archUnknown;
641         opts->promptPassword = TRI_DEFAULT;
642
643         return opts;
644 }
645
646 static void
647 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
648 {
649         /* This hack is only needed in a data-only restore */
650         if (!ropt->dataOnly || !ropt->disable_triggers)
651                 return;
652
653         ahlog(AH, 1, "disabling triggers for %s\n", te->tag);
654
655         /*
656          * Become superuser if possible, since they are the only ones who can
657          * disable constraint triggers.  If -S was not given, assume the initial
658          * user identity is a superuser.  (XXX would it be better to become the
659          * table owner?)
660          */
661         _becomeUser(AH, ropt->superuser);
662
663         /*
664          * Disable them.
665          */
666         _selectOutputSchema(AH, te->namespace);
667
668         ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
669                          fmtId(te->tag));
670 }
671
672 static void
673 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
674 {
675         /* This hack is only needed in a data-only restore */
676         if (!ropt->dataOnly || !ropt->disable_triggers)
677                 return;
678
679         ahlog(AH, 1, "enabling triggers for %s\n", te->tag);
680
681         /*
682          * Become superuser if possible, since they are the only ones who can
683          * disable constraint triggers.  If -S was not given, assume the initial
684          * user identity is a superuser.  (XXX would it be better to become the
685          * table owner?)
686          */
687         _becomeUser(AH, ropt->superuser);
688
689         /*
690          * Enable them.
691          */
692         _selectOutputSchema(AH, te->namespace);
693
694         ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
695                          fmtId(te->tag));
696 }
697
698 /*
699  * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
700  */
701
702 /* Public */
703 size_t
704 WriteData(Archive *AHX, const void *data, size_t dLen)
705 {
706         ArchiveHandle *AH = (ArchiveHandle *) AHX;
707
708         if (!AH->currToc)
709                 die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
710
711         return (*AH->WriteDataPtr) (AH, data, dLen);
712 }
713
714 /*
715  * Create a new TOC entry. The TOC was designed as a TOC, but is now the
716  * repository for all metadata. But the name has stuck.
717  */
718
719 /* Public */
720 void
721 ArchiveEntry(Archive *AHX,
722                          CatalogId catalogId, DumpId dumpId,
723                          const char *tag,
724                          const char *namespace,
725                          const char *tablespace,
726                          const char *owner, bool withOids,
727                          const char *desc, teSection section,
728                          const char *defn,
729                          const char *dropStmt, const char *copyStmt,
730                          const DumpId *deps, int nDeps,
731                          DataDumperPtr dumpFn, void *dumpArg)
732 {
733         ArchiveHandle *AH = (ArchiveHandle *) AHX;
734         TocEntry   *newToc;
735
736         newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
737         if (!newToc)
738                 die_horribly(AH, modulename, "out of memory\n");
739
740         AH->tocCount++;
741         if (dumpId > AH->maxDumpId)
742                 AH->maxDumpId = dumpId;
743
744         newToc->prev = AH->toc->prev;
745         newToc->next = AH->toc;
746         AH->toc->prev->next = newToc;
747         AH->toc->prev = newToc;
748
749         newToc->catalogId = catalogId;
750         newToc->dumpId = dumpId;
751         newToc->section = section;
752
753         newToc->tag = strdup(tag);
754         newToc->namespace = namespace ? strdup(namespace) : NULL;
755         newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
756         newToc->owner = strdup(owner);
757         newToc->withOids = withOids;
758         newToc->desc = strdup(desc);
759         newToc->defn = strdup(defn);
760         newToc->dropStmt = strdup(dropStmt);
761         newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
762
763         if (nDeps > 0)
764         {
765                 newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
766                 memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
767                 newToc->nDeps = nDeps;
768         }
769         else
770         {
771                 newToc->dependencies = NULL;
772                 newToc->nDeps = 0;
773         }
774
775         newToc->dataDumper = dumpFn;
776         newToc->dataDumperArg = dumpArg;
777         newToc->hadDumper = dumpFn ? true : false;
778
779         newToc->formatData = NULL;
780
781         if (AH->ArchiveEntryPtr !=NULL)
782                 (*AH->ArchiveEntryPtr) (AH, newToc);
783 }
784
785 /* Public */
786 void
787 PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
788 {
789         ArchiveHandle *AH = (ArchiveHandle *) AHX;
790         TocEntry   *te;
791         OutputContext sav;
792         char       *fmtName;
793
794         sav = SaveOutput(AH);
795         if (ropt->filename)
796                 SetOutput(AH, ropt->filename, 0 /* no compression */ );
797
798         ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
799         ahprintf(AH, ";     dbname: %s\n;     TOC Entries: %d\n;     Compression: %d\n",
800                          AH->archdbname, AH->tocCount, AH->compression);
801
802         switch (AH->format)
803         {
804                 case archFiles:
805                         fmtName = "FILES";
806                         break;
807                 case archCustom:
808                         fmtName = "CUSTOM";
809                         break;
810                 case archTar:
811                         fmtName = "TAR";
812                         break;
813                 default:
814                         fmtName = "UNKNOWN";
815         }
816
817         ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
818         ahprintf(AH, ";     Format: %s\n", fmtName);
819         ahprintf(AH, ";     Integer: %d bytes\n", (int) AH->intSize);
820         ahprintf(AH, ";     Offset: %d bytes\n", (int) AH->offSize);
821         if (AH->archiveRemoteVersion)
822                 ahprintf(AH, ";     Dumped from database version: %s\n",
823                                  AH->archiveRemoteVersion);
824         if (AH->archiveDumpVersion)
825                 ahprintf(AH, ";     Dumped by pg_dump version: %s\n",
826                                  AH->archiveDumpVersion);
827
828         ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
829
830         /* We should print DATABASE entries whether or not -C was specified */
831         ropt->createDB = 1;
832
833         for (te = AH->toc->next; te != AH->toc; te = te->next)
834         {
835                 if (ropt->verbose || _tocEntryRequired(te, ropt, true) != 0)
836                         ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
837                                          te->catalogId.tableoid, te->catalogId.oid,
838                                          te->desc, te->namespace ? te->namespace : "-",
839                                          te->tag, te->owner);
840                 if (ropt->verbose && te->nDeps > 0)
841                 {
842                         int                     i;
843
844                         ahprintf(AH, ";\tdepends on:");
845                         for (i = 0; i < te->nDeps; i++)
846                                 ahprintf(AH, " %d", te->dependencies[i]);
847                         ahprintf(AH, "\n");
848                 }
849         }
850
851         if (ropt->filename)
852                 RestoreOutput(AH, sav);
853 }
854
855 /***********
856  * BLOB Archival
857  ***********/
858
859 /* Called by a dumper to signal start of a BLOB */
860 int
861 StartBlob(Archive *AHX, Oid oid)
862 {
863         ArchiveHandle *AH = (ArchiveHandle *) AHX;
864
865         if (!AH->StartBlobPtr)
866                 die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
867
868         (*AH->StartBlobPtr) (AH, AH->currToc, oid);
869
870         return 1;
871 }
872
873 /* Called by a dumper to signal end of a BLOB */
874 int
875 EndBlob(Archive *AHX, Oid oid)
876 {
877         ArchiveHandle *AH = (ArchiveHandle *) AHX;
878
879         if (AH->EndBlobPtr)
880                 (*AH->EndBlobPtr) (AH, AH->currToc, oid);
881
882         return 1;
883 }
884
885 /**********
886  * BLOB Restoration
887  **********/
888
889 /*
890  * Called by a format handler before any blobs are restored
891  */
892 void
893 StartRestoreBlobs(ArchiveHandle *AH)
894 {
895         if (!AH->ropt->single_txn)
896         {
897                 if (AH->connection)
898                         StartTransaction(AH);
899                 else
900                         ahprintf(AH, "BEGIN;\n\n");
901         }
902
903         AH->blobCount = 0;
904 }
905
906 /*
907  * Called by a format handler after all blobs are restored
908  */
909 void
910 EndRestoreBlobs(ArchiveHandle *AH)
911 {
912         if (!AH->ropt->single_txn)
913         {
914                 if (AH->connection)
915                         CommitTransaction(AH);
916                 else
917                         ahprintf(AH, "COMMIT;\n\n");
918         }
919
920         ahlog(AH, 1, ngettext("restored %d large object\n",
921                                                   "restored %d large objects\n",
922                                                   AH->blobCount),
923                   AH->blobCount);
924 }
925
926
927 /*
928  * Called by a format handler to initiate restoration of a blob
929  */
930 void
931 StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
932 {
933         bool            old_blob_style = (AH->version < K_VERS_1_12);
934         Oid                     loOid;
935
936         AH->blobCount++;
937
938         /* Initialize the LO Buffer */
939         AH->lo_buf_used = 0;
940
941         ahlog(AH, 2, "restoring large object with OID %u\n", oid);
942
943         /* With an old archive we must do drop and create logic here */
944         if (old_blob_style && drop)
945                 DropBlobIfExists(AH, oid);
946
947         if (AH->connection)
948         {
949                 if (old_blob_style)
950                 {
951                         loOid = lo_create(AH->connection, oid);
952                         if (loOid == 0 || loOid != oid)
953                                 die_horribly(AH, modulename, "could not create large object %u: %s",
954                                                          oid, PQerrorMessage(AH->connection));
955                 }
956                 AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
957                 if (AH->loFd == -1)
958                         die_horribly(AH, modulename, "could not open large object %u: %s",
959                                                  oid, PQerrorMessage(AH->connection));
960         }
961         else
962         {
963                 if (old_blob_style)
964                         ahprintf(AH, "SELECT pg_catalog.lo_open(pg_catalog.lo_create('%u'), %d);\n",
965                                          oid, INV_WRITE);
966                 else
967                         ahprintf(AH, "SELECT pg_catalog.lo_open('%u', %d);\n",
968                                          oid, INV_WRITE);
969         }
970
971         AH->writingBlob = 1;
972 }
973
974 void
975 EndRestoreBlob(ArchiveHandle *AH, Oid oid)
976 {
977         if (AH->lo_buf_used > 0)
978         {
979                 /* Write remaining bytes from the LO buffer */
980                 dump_lo_buf(AH);
981         }
982
983         AH->writingBlob = 0;
984
985         if (AH->connection)
986         {
987                 lo_close(AH->connection, AH->loFd);
988                 AH->loFd = -1;
989         }
990         else
991         {
992                 ahprintf(AH, "SELECT pg_catalog.lo_close(0);\n\n");
993         }
994 }
995
996 /***********
997  * Sorting and Reordering
998  ***********/
999
1000 void
1001 SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
1002 {
1003         ArchiveHandle *AH = (ArchiveHandle *) AHX;
1004         FILE       *fh;
1005         char            buf[1024];
1006         char       *cmnt;
1007         char       *endptr;
1008         DumpId          id;
1009         TocEntry   *te;
1010
1011         /* Allocate space for the 'wanted' array, and init it */
1012         ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
1013         memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
1014
1015         /* Setup the file */
1016         fh = fopen(ropt->tocFile, PG_BINARY_R);
1017         if (!fh)
1018                 die_horribly(AH, modulename, "could not open TOC file \"%s\": %s\n",
1019                                          ropt->tocFile, strerror(errno));
1020
1021         while (fgets(buf, sizeof(buf), fh) != NULL)
1022         {
1023                 /* Truncate line at comment, if any */
1024                 cmnt = strchr(buf, ';');
1025                 if (cmnt != NULL)
1026                         cmnt[0] = '\0';
1027
1028                 /* Ignore if all blank */
1029                 if (strspn(buf, " \t\r\n") == strlen(buf))
1030                         continue;
1031
1032                 /* Get an ID, check it's valid and not already seen */
1033                 id = strtol(buf, &endptr, 10);
1034                 if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
1035                         ropt->idWanted[id - 1])
1036                 {
1037                         write_msg(modulename, "WARNING: line ignored: %s\n", buf);
1038                         continue;
1039                 }
1040
1041                 /* Find TOC entry */
1042                 te = getTocEntryByDumpId(AH, id);
1043                 if (!te)
1044                         die_horribly(AH, modulename, "could not find entry for ID %d\n",
1045                                                  id);
1046
1047                 /* Mark it wanted */
1048                 ropt->idWanted[id - 1] = true;
1049
1050                 /*
1051                  * Move each item to the end of the list as it is selected, so that
1052                  * they are placed in the desired order.  Any unwanted items will end
1053                  * up at the front of the list, which may seem unintuitive but it's
1054                  * what we need.  In an ordinary serial restore that makes no
1055                  * difference, but in a parallel restore we need to mark unrestored
1056                  * items' dependencies as satisfied before we start examining
1057                  * restorable items.  Otherwise they could have surprising
1058                  * side-effects on the order in which restorable items actually get
1059                  * restored.
1060                  */
1061                 _moveBefore(AH, AH->toc, te);
1062         }
1063
1064         if (fclose(fh) != 0)
1065                 die_horribly(AH, modulename, "could not close TOC file: %s\n",
1066                                          strerror(errno));
1067 }
1068
1069 /*
1070  * Set up a dummy ID filter that selects all dump IDs
1071  */
1072 void
1073 InitDummyWantedList(Archive *AHX, RestoreOptions *ropt)
1074 {
1075         ArchiveHandle *AH = (ArchiveHandle *) AHX;
1076
1077         /* Allocate space for the 'wanted' array, and init it to 1's */
1078         ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
1079         memset(ropt->idWanted, 1, sizeof(bool) * AH->maxDumpId);
1080 }
1081
1082 /**********************
1083  * 'Convenience functions that look like standard IO functions
1084  * for writing data when in dump mode.
1085  **********************/
1086
1087 /* Public */
1088 int
1089 archputs(const char *s, Archive *AH)
1090 {
1091         return WriteData(AH, s, strlen(s));
1092 }
1093
1094 /* Public */
1095 int
1096 archprintf(Archive *AH, const char *fmt,...)
1097 {
1098         char       *p = NULL;
1099         va_list         ap;
1100         int                     bSize = strlen(fmt) + 256;
1101         int                     cnt = -1;
1102
1103         /*
1104          * This is paranoid: deal with the possibility that vsnprintf is willing
1105          * to ignore trailing null or returns > 0 even if string does not fit. It
1106          * may be the case that it returns cnt = bufsize
1107          */
1108         while (cnt < 0 || cnt >= (bSize - 1))
1109         {
1110                 if (p != NULL)
1111                         free(p);
1112                 bSize *= 2;
1113                 p = (char *) malloc(bSize);
1114                 if (p == NULL)
1115                         exit_horribly(AH, modulename, "out of memory\n");
1116                 va_start(ap, fmt);
1117                 cnt = vsnprintf(p, bSize, fmt, ap);
1118                 va_end(ap);
1119         }
1120         WriteData(AH, p, cnt);
1121         free(p);
1122         return cnt;
1123 }
1124
1125
1126 /*******************************
1127  * Stuff below here should be 'private' to the archiver routines
1128  *******************************/
1129
1130 static void
1131 SetOutput(ArchiveHandle *AH, char *filename, int compression)
1132 {
1133         int                     fn;
1134
1135         if (filename)
1136                 fn = -1;
1137         else if (AH->FH)
1138                 fn = fileno(AH->FH);
1139         else if (AH->fSpec)
1140         {
1141                 fn = -1;
1142                 filename = AH->fSpec;
1143         }
1144         else
1145                 fn = fileno(stdout);
1146
1147         /* If compression explicitly requested, use gzopen */
1148 #ifdef HAVE_LIBZ
1149         if (compression != 0)
1150         {
1151                 char            fmode[10];
1152
1153                 /* Don't use PG_BINARY_x since this is zlib */
1154                 sprintf(fmode, "wb%d", compression);
1155                 if (fn >= 0)
1156                         AH->OF = gzdopen(dup(fn), fmode);
1157                 else
1158                         AH->OF = gzopen(filename, fmode);
1159                 AH->gzOut = 1;
1160         }
1161         else
1162 #endif
1163         {                                                       /* Use fopen */
1164                 if (AH->mode == archModeAppend)
1165                 {
1166                         if (fn >= 0)
1167                                 AH->OF = fdopen(dup(fn), PG_BINARY_A);
1168                         else
1169                                 AH->OF = fopen(filename, PG_BINARY_A);
1170                 }
1171                 else
1172                 {
1173                         if (fn >= 0)
1174                                 AH->OF = fdopen(dup(fn), PG_BINARY_W);
1175                         else
1176                                 AH->OF = fopen(filename, PG_BINARY_W);
1177                 }
1178                 AH->gzOut = 0;
1179         }
1180
1181         if (!AH->OF)
1182         {
1183                 if (filename)
1184                         die_horribly(AH, modulename, "could not open output file \"%s\": %s\n",
1185                                                  filename, strerror(errno));
1186                 else
1187                         die_horribly(AH, modulename, "could not open output file: %s\n",
1188                                                  strerror(errno));
1189         }
1190 }
1191
1192 static OutputContext
1193 SaveOutput(ArchiveHandle *AH)
1194 {
1195         OutputContext sav;
1196
1197         sav.OF = AH->OF;
1198         sav.gzOut = AH->gzOut;
1199
1200         return sav;
1201 }
1202
1203 static void
1204 RestoreOutput(ArchiveHandle *AH, OutputContext savedContext)
1205 {
1206         int                     res;
1207
1208         if (AH->gzOut)
1209                 res = GZCLOSE(AH->OF);
1210         else
1211                 res = fclose(AH->OF);
1212
1213         if (res != 0)
1214                 die_horribly(AH, modulename, "could not close output file: %s\n",
1215                                          strerror(errno));
1216
1217         AH->gzOut = savedContext.gzOut;
1218         AH->OF = savedContext.OF;
1219 }
1220
1221
1222
1223 /*
1224  *      Print formatted text to the output file (usually stdout).
1225  */
1226 int
1227 ahprintf(ArchiveHandle *AH, const char *fmt,...)
1228 {
1229         char       *p = NULL;
1230         va_list         ap;
1231         int                     bSize = strlen(fmt) + 256;              /* Should be enough */
1232         int                     cnt = -1;
1233
1234         /*
1235          * This is paranoid: deal with the possibility that vsnprintf is willing
1236          * to ignore trailing null
1237          */
1238
1239         /*
1240          * or returns > 0 even if string does not fit. It may be the case that it
1241          * returns cnt = bufsize
1242          */
1243         while (cnt < 0 || cnt >= (bSize - 1))
1244         {
1245                 if (p != NULL)
1246                         free(p);
1247                 bSize *= 2;
1248                 p = (char *) malloc(bSize);
1249                 if (p == NULL)
1250                         die_horribly(AH, modulename, "out of memory\n");
1251                 va_start(ap, fmt);
1252                 cnt = vsnprintf(p, bSize, fmt, ap);
1253                 va_end(ap);
1254         }
1255         ahwrite(p, 1, cnt, AH);
1256         free(p);
1257         return cnt;
1258 }
1259
1260 void
1261 ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1262 {
1263         va_list         ap;
1264
1265         if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
1266                 return;
1267
1268         va_start(ap, fmt);
1269         _write_msg(NULL, fmt, ap);
1270         va_end(ap);
1271 }
1272
1273 /*
1274  * Single place for logic which says 'We are restoring to a direct DB connection'.
1275  */
1276 static int
1277 RestoringToDB(ArchiveHandle *AH)
1278 {
1279         return (AH->ropt && AH->ropt->useDB && AH->connection);
1280 }
1281
1282 /*
1283  * Dump the current contents of the LO data buffer while writing a BLOB
1284  */
1285 static void
1286 dump_lo_buf(ArchiveHandle *AH)
1287 {
1288         if (AH->connection)
1289         {
1290                 size_t          res;
1291
1292                 res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
1293                 ahlog(AH, 5, ngettext("wrote %lu byte of large object data (result = %lu)\n",
1294                                          "wrote %lu bytes of large object data (result = %lu)\n",
1295                                                           AH->lo_buf_used),
1296                           (unsigned long) AH->lo_buf_used, (unsigned long) res);
1297                 if (res != AH->lo_buf_used)
1298                         die_horribly(AH, modulename,
1299                         "could not write to large object (result: %lu, expected: %lu)\n",
1300                                            (unsigned long) res, (unsigned long) AH->lo_buf_used);
1301         }
1302         else
1303         {
1304                 PQExpBuffer buf = createPQExpBuffer();
1305
1306                 appendByteaLiteralAHX(buf,
1307                                                           (const unsigned char *) AH->lo_buf,
1308                                                           AH->lo_buf_used,
1309                                                           AH);
1310
1311                 /* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
1312                 AH->writingBlob = 0;
1313                 ahprintf(AH, "SELECT pg_catalog.lowrite(0, %s);\n", buf->data);
1314                 AH->writingBlob = 1;
1315
1316                 destroyPQExpBuffer(buf);
1317         }
1318         AH->lo_buf_used = 0;
1319 }
1320
1321
1322 /*
1323  *      Write buffer to the output file (usually stdout). This is user for
1324  *      outputting 'restore' scripts etc. It is even possible for an archive
1325  *      format to create a custom output routine to 'fake' a restore if it
1326  *      wants to generate a script (see TAR output).
1327  */
1328 int
1329 ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
1330 {
1331         size_t          res;
1332
1333         if (AH->writingBlob)
1334         {
1335                 size_t          remaining = size * nmemb;
1336
1337                 while (AH->lo_buf_used + remaining > AH->lo_buf_size)
1338                 {
1339                         size_t          avail = AH->lo_buf_size - AH->lo_buf_used;
1340
1341                         memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
1342                         ptr = (const void *) ((const char *) ptr + avail);
1343                         remaining -= avail;
1344                         AH->lo_buf_used += avail;
1345                         dump_lo_buf(AH);
1346                 }
1347
1348                 memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
1349                 AH->lo_buf_used += remaining;
1350
1351                 return size * nmemb;
1352         }
1353         else if (AH->gzOut)
1354         {
1355                 res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1356                 if (res != (nmemb * size))
1357                         die_horribly(AH, modulename, "could not write to output file: %s\n", strerror(errno));
1358                 return res;
1359         }
1360         else if (AH->CustomOutPtr)
1361         {
1362                 res = AH->CustomOutPtr (AH, ptr, size * nmemb);
1363
1364                 if (res != (nmemb * size))
1365                         die_horribly(AH, modulename, "could not write to custom output routine\n");
1366                 return res;
1367         }
1368         else
1369         {
1370                 /*
1371                  * If we're doing a restore, and it's direct to DB, and we're
1372                  * connected then send it to the DB.
1373                  */
1374                 if (RestoringToDB(AH))
1375                         return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb);            /* Always 1, currently */
1376                 else
1377                 {
1378                         res = fwrite((void *) ptr, size, nmemb, AH->OF);
1379                         if (res != nmemb)
1380                                 die_horribly(AH, modulename, "could not write to output file: %s\n",
1381                                                          strerror(errno));
1382                         return res;
1383                 }
1384         }
1385 }
1386
1387 /* Common exit code */
1388 static void
1389 _write_msg(const char *modulename, const char *fmt, va_list ap)
1390 {
1391         if (modulename)
1392                 fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1393         else
1394                 fprintf(stderr, "%s: ", progname);
1395         vfprintf(stderr, _(fmt), ap);
1396 }
1397
1398 void
1399 write_msg(const char *modulename, const char *fmt,...)
1400 {
1401         va_list         ap;
1402
1403         va_start(ap, fmt);
1404         _write_msg(modulename, fmt, ap);
1405         va_end(ap);
1406 }
1407
1408
1409 static void
1410 _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
1411 {
1412         _write_msg(modulename, fmt, ap);
1413
1414         if (AH)
1415         {
1416                 if (AH->public.verbose)
1417                         write_msg(NULL, "*** aborted because of error\n");
1418                 if (AH->connection)
1419                         PQfinish(AH->connection);
1420         }
1421
1422         exit(1);
1423 }
1424
1425 /* External use */
1426 void
1427 exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1428 {
1429         va_list         ap;
1430
1431         va_start(ap, fmt);
1432         _die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1433         va_end(ap);
1434 }
1435
1436 /* Archiver use (just different arg declaration) */
1437 void
1438 die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
1439 {
1440         va_list         ap;
1441
1442         va_start(ap, fmt);
1443         _die_horribly(AH, modulename, fmt, ap);
1444         va_end(ap);
1445 }
1446
1447 /* on some error, we may decide to go on... */
1448 void
1449 warn_or_die_horribly(ArchiveHandle *AH,
1450                                          const char *modulename, const char *fmt,...)
1451 {
1452         va_list         ap;
1453
1454         switch (AH->stage)
1455         {
1456
1457                 case STAGE_NONE:
1458                         /* Do nothing special */
1459                         break;
1460
1461                 case STAGE_INITIALIZING:
1462                         if (AH->stage != AH->lastErrorStage)
1463                                 write_msg(modulename, "Error while INITIALIZING:\n");
1464                         break;
1465
1466                 case STAGE_PROCESSING:
1467                         if (AH->stage != AH->lastErrorStage)
1468                                 write_msg(modulename, "Error while PROCESSING TOC:\n");
1469                         break;
1470
1471                 case STAGE_FINALIZING:
1472                         if (AH->stage != AH->lastErrorStage)
1473                                 write_msg(modulename, "Error while FINALIZING:\n");
1474                         break;
1475         }
1476         if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
1477         {
1478                 write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
1479                                   AH->currentTE->dumpId,
1480                          AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
1481                           AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1482         }
1483         AH->lastErrorStage = AH->stage;
1484         AH->lastErrorTE = AH->currentTE;
1485
1486         va_start(ap, fmt);
1487         if (AH->public.exit_on_error)
1488                 _die_horribly(AH, modulename, fmt, ap);
1489         else
1490         {
1491                 _write_msg(modulename, fmt, ap);
1492                 AH->public.n_errors++;
1493         }
1494         va_end(ap);
1495 }
1496
1497 #ifdef NOT_USED
1498
1499 static void
1500 _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1501 {
1502         /* Unlink te from list */
1503         te->prev->next = te->next;
1504         te->next->prev = te->prev;
1505
1506         /* and insert it after "pos" */
1507         te->prev = pos;
1508         te->next = pos->next;
1509         pos->next->prev = te;
1510         pos->next = te;
1511 }
1512
1513 #endif
1514
1515 static void
1516 _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
1517 {
1518         /* Unlink te from list */
1519         te->prev->next = te->next;
1520         te->next->prev = te->prev;
1521
1522         /* and insert it before "pos" */
1523         te->prev = pos->prev;
1524         te->next = pos;
1525         pos->prev->next = te;
1526         pos->prev = te;
1527 }
1528
1529 static TocEntry *
1530 getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
1531 {
1532         TocEntry   *te;
1533
1534         for (te = AH->toc->next; te != AH->toc; te = te->next)
1535         {
1536                 if (te->dumpId == id)
1537                         return te;
1538         }
1539         return NULL;
1540 }
1541
1542 teReqs
1543 TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
1544 {
1545         TocEntry   *te = getTocEntryByDumpId(AH, id);
1546
1547         if (!te)
1548                 return 0;
1549
1550         return _tocEntryRequired(te, ropt, true);
1551 }
1552
1553 size_t
1554 WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
1555 {
1556         int                     off;
1557
1558         /* Save the flag */
1559         (*AH->WriteBytePtr) (AH, wasSet);
1560
1561         /* Write out pgoff_t smallest byte first, prevents endian mismatch */
1562         for (off = 0; off < sizeof(pgoff_t); off++)
1563         {
1564                 (*AH->WriteBytePtr) (AH, o & 0xFF);
1565                 o >>= 8;
1566         }
1567         return sizeof(pgoff_t) + 1;
1568 }
1569
1570 int
1571 ReadOffset(ArchiveHandle *AH, pgoff_t * o)
1572 {
1573         int                     i;
1574         int                     off;
1575         int                     offsetFlg;
1576
1577         /* Initialize to zero */
1578         *o = 0;
1579
1580         /* Check for old version */
1581         if (AH->version < K_VERS_1_7)
1582         {
1583                 /* Prior versions wrote offsets using WriteInt */
1584                 i = ReadInt(AH);
1585                 /* -1 means not set */
1586                 if (i < 0)
1587                         return K_OFFSET_POS_NOT_SET;
1588                 else if (i == 0)
1589                         return K_OFFSET_NO_DATA;
1590
1591                 /* Cast to pgoff_t because it was written as an int. */
1592                 *o = (pgoff_t) i;
1593                 return K_OFFSET_POS_SET;
1594         }
1595
1596         /*
1597          * Read the flag indicating the state of the data pointer. Check if valid
1598          * and die if not.
1599          *
1600          * This used to be handled by a negative or zero pointer, now we use an
1601          * extra byte specifically for the state.
1602          */
1603         offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;
1604
1605         switch (offsetFlg)
1606         {
1607                 case K_OFFSET_POS_NOT_SET:
1608                 case K_OFFSET_NO_DATA:
1609                 case K_OFFSET_POS_SET:
1610
1611                         break;
1612
1613                 default:
1614                         die_horribly(AH, modulename, "unexpected data offset flag %d\n", offsetFlg);
1615         }
1616
1617         /*
1618          * Read the bytes
1619          */
1620         for (off = 0; off < AH->offSize; off++)
1621         {
1622                 if (off < sizeof(pgoff_t))
1623                         *o |= ((pgoff_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1624                 else
1625                 {
1626                         if ((*AH->ReadBytePtr) (AH) != 0)
1627                                 die_horribly(AH, modulename, "file offset in dump file is too large\n");
1628                 }
1629         }
1630
1631         return offsetFlg;
1632 }
1633
1634 size_t
1635 WriteInt(ArchiveHandle *AH, int i)
1636 {
1637         int                     b;
1638
1639         /*
1640          * This is a bit yucky, but I don't want to make the binary format very
1641          * dependent on representation, and not knowing much about it, I write out
1642          * a sign byte. If you change this, don't forget to change the file
1643          * version #, and modify readInt to read the new format AS WELL AS the old
1644          * formats.
1645          */
1646
1647         /* SIGN byte */
1648         if (i < 0)
1649         {
1650                 (*AH->WriteBytePtr) (AH, 1);
1651                 i = -i;
1652         }
1653         else
1654                 (*AH->WriteBytePtr) (AH, 0);
1655
1656         for (b = 0; b < AH->intSize; b++)
1657         {
1658                 (*AH->WriteBytePtr) (AH, i & 0xFF);
1659                 i >>= 8;
1660         }
1661
1662         return AH->intSize + 1;
1663 }
1664
1665 int
1666 ReadInt(ArchiveHandle *AH)
1667 {
1668         int                     res = 0;
1669         int                     bv,
1670                                 b;
1671         int                     sign = 0;               /* Default positive */
1672         int                     bitShift = 0;
1673
1674         if (AH->version > K_VERS_1_0)
1675                 /* Read a sign byte */
1676                 sign = (*AH->ReadBytePtr) (AH);
1677
1678         for (b = 0; b < AH->intSize; b++)
1679         {
1680                 bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1681                 if (bv != 0)
1682                         res = res + (bv << bitShift);
1683                 bitShift += 8;
1684         }
1685
1686         if (sign)
1687                 res = -res;
1688
1689         return res;
1690 }
1691
1692 size_t
1693 WriteStr(ArchiveHandle *AH, const char *c)
1694 {
1695         size_t          res;
1696
1697         if (c)
1698         {
1699                 res = WriteInt(AH, strlen(c));
1700                 res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1701         }
1702         else
1703                 res = WriteInt(AH, -1);
1704
1705         return res;
1706 }
1707
1708 char *
1709 ReadStr(ArchiveHandle *AH)
1710 {
1711         char       *buf;
1712         int                     l;
1713
1714         l = ReadInt(AH);
1715         if (l < 0)
1716                 buf = NULL;
1717         else
1718         {
1719                 buf = (char *) malloc(l + 1);
1720                 if (!buf)
1721                         die_horribly(AH, modulename, "out of memory\n");
1722
1723                 if ((*AH->ReadBufPtr) (AH, (void *) buf, l) != l)
1724                         die_horribly(AH, modulename, "unexpected end of file\n");
1725
1726                 buf[l] = '\0';
1727         }
1728
1729         return buf;
1730 }
1731
1732 static int
1733 _discoverArchiveFormat(ArchiveHandle *AH)
1734 {
1735         FILE       *fh;
1736         char            sig[6];                 /* More than enough */
1737         size_t          cnt;
1738         int                     wantClose = 0;
1739
1740 #if 0
1741         write_msg(modulename, "attempting to ascertain archive format\n");
1742 #endif
1743
1744         if (AH->lookahead)
1745                 free(AH->lookahead);
1746
1747         AH->lookaheadSize = 512;
1748         AH->lookahead = calloc(1, 512);
1749         AH->lookaheadLen = 0;
1750         AH->lookaheadPos = 0;
1751
1752         if (AH->fSpec)
1753         {
1754                 wantClose = 1;
1755                 fh = fopen(AH->fSpec, PG_BINARY_R);
1756                 if (!fh)
1757                         die_horribly(AH, modulename, "could not open input file \"%s\": %s\n",
1758                                                  AH->fSpec, strerror(errno));
1759         }
1760         else
1761         {
1762                 fh = stdin;
1763                 if (!fh)
1764                         die_horribly(AH, modulename, "could not open input file: %s\n",
1765                                                  strerror(errno));
1766         }
1767
1768         cnt = fread(sig, 1, 5, fh);
1769
1770         if (cnt != 5)
1771         {
1772                 if (ferror(fh))
1773                         die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
1774                 else
1775                         die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
1776                                                  (unsigned long) cnt);
1777         }
1778
1779         /* Save it, just in case we need it later */
1780         strncpy(&AH->lookahead[0], sig, 5);
1781         AH->lookaheadLen = 5;
1782
1783         if (strncmp(sig, "PGDMP", 5) == 0)
1784         {
1785                 /*
1786                  * Finish reading (most of) a custom-format header.
1787                  *
1788                  * NB: this code must agree with ReadHead().
1789                  */
1790                 AH->vmaj = fgetc(fh);
1791                 AH->vmin = fgetc(fh);
1792
1793                 /* Save these too... */
1794                 AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
1795                 AH->lookahead[AH->lookaheadLen++] = AH->vmin;
1796
1797                 /* Check header version; varies from V1.0 */
1798                 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))                /* Version > 1.0 */
1799                 {
1800                         AH->vrev = fgetc(fh);
1801                         AH->lookahead[AH->lookaheadLen++] = AH->vrev;
1802                 }
1803                 else
1804                         AH->vrev = 0;
1805
1806                 /* Make a convenient integer <maj><min><rev>00 */
1807                 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1808
1809                 AH->intSize = fgetc(fh);
1810                 AH->lookahead[AH->lookaheadLen++] = AH->intSize;
1811
1812                 if (AH->version >= K_VERS_1_7)
1813                 {
1814                         AH->offSize = fgetc(fh);
1815                         AH->lookahead[AH->lookaheadLen++] = AH->offSize;
1816                 }
1817                 else
1818                         AH->offSize = AH->intSize;
1819
1820                 AH->format = fgetc(fh);
1821                 AH->lookahead[AH->lookaheadLen++] = AH->format;
1822         }
1823         else
1824         {
1825                 /*
1826                  * *Maybe* we have a tar archive format file... So, read first 512
1827                  * byte header...
1828                  */
1829                 cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
1830                 AH->lookaheadLen += cnt;
1831
1832                 if (AH->lookaheadLen != 512)
1833                         die_horribly(AH, modulename, "input file does not appear to be a valid archive (too short?)\n");
1834
1835                 if (!isValidTarHeader(AH->lookahead))
1836                         die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
1837
1838                 AH->format = archTar;
1839         }
1840
1841         /* If we can't seek, then mark the header as read */
1842         if (fseeko(fh, 0, SEEK_SET) != 0)
1843         {
1844                 /*
1845                  * NOTE: Formats that use the lookahead buffer can unset this in their
1846                  * Init routine.
1847                  */
1848                 AH->readHeader = 1;
1849         }
1850         else
1851                 AH->lookaheadLen = 0;   /* Don't bother since we've reset the file */
1852
1853         /* Close the file */
1854         if (wantClose)
1855                 if (fclose(fh) != 0)
1856                         die_horribly(AH, modulename, "could not close input file: %s\n",
1857                                                  strerror(errno));
1858
1859         return AH->format;
1860 }
1861
1862
1863 /*
1864  * Allocate an archive handle
1865  */
1866 static ArchiveHandle *
1867 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
1868                  const int compression, ArchiveMode mode)
1869 {
1870         ArchiveHandle *AH;
1871
1872 #if 0
1873         write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1874 #endif
1875
1876         AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
1877         if (!AH)
1878                 die_horribly(AH, modulename, "out of memory\n");
1879
1880         /* AH->debugLevel = 100; */
1881
1882         AH->vmaj = K_VERS_MAJOR;
1883         AH->vmin = K_VERS_MINOR;
1884         AH->vrev = K_VERS_REV;
1885
1886         /* Make a convenient integer <maj><min><rev>00 */
1887         AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
1888
1889         /* initialize for backwards compatible string processing */
1890         AH->public.encoding = 0;        /* PG_SQL_ASCII */
1891         AH->public.std_strings = false;
1892
1893         /* sql error handling */
1894         AH->public.exit_on_error = true;
1895         AH->public.n_errors = 0;
1896
1897         AH->archiveDumpVersion = PG_VERSION;
1898
1899         AH->createDate = time(NULL);
1900
1901         AH->intSize = sizeof(int);
1902         AH->offSize = sizeof(pgoff_t);
1903         if (FileSpec)
1904         {
1905                 AH->fSpec = strdup(FileSpec);
1906
1907                 /*
1908                  * Not used; maybe later....
1909                  *
1910                  * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
1911                  * i--) if (AH->workDir[i-1] == '/')
1912                  */
1913         }
1914         else
1915                 AH->fSpec = NULL;
1916
1917         AH->currUser = NULL;            /* unknown */
1918         AH->currSchema = NULL;          /* ditto */
1919         AH->currTablespace = NULL;      /* ditto */
1920         AH->currWithOids = -1;          /* force SET */
1921
1922         AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
1923         if (!AH->toc)
1924                 die_horribly(AH, modulename, "out of memory\n");
1925
1926         AH->toc->next = AH->toc;
1927         AH->toc->prev = AH->toc;
1928
1929         AH->mode = mode;
1930         AH->compression = compression;
1931
1932         AH->pgCopyBuf = createPQExpBuffer();
1933         AH->sqlBuf = createPQExpBuffer();
1934
1935         /* Open stdout with no compression for AH output handle */
1936         AH->gzOut = 0;
1937         AH->OF = stdout;
1938
1939         /*
1940          * On Windows, we need to use binary mode to read/write non-text archive
1941          * formats.  Force stdin/stdout into binary mode if that is what we are
1942          * using.
1943          */
1944 #ifdef WIN32
1945         if (fmt != archNull &&
1946                 (AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1947         {
1948                 if (mode == archModeWrite)
1949                         setmode(fileno(stdout), O_BINARY);
1950                 else
1951                         setmode(fileno(stdin), O_BINARY);
1952         }
1953 #endif
1954
1955         if (fmt == archUnknown)
1956                 AH->format = _discoverArchiveFormat(AH);
1957         else
1958                 AH->format = fmt;
1959
1960         AH->promptPassword = TRI_DEFAULT;
1961
1962         switch (AH->format)
1963         {
1964                 case archCustom:
1965                         InitArchiveFmt_Custom(AH);
1966                         break;
1967
1968                 case archFiles:
1969                         InitArchiveFmt_Files(AH);
1970                         break;
1971
1972                 case archNull:
1973                         InitArchiveFmt_Null(AH);
1974                         break;
1975
1976                 case archTar:
1977                         InitArchiveFmt_Tar(AH);
1978                         break;
1979
1980                 default:
1981                         die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
1982         }
1983
1984         return AH;
1985 }
1986
1987
1988 void
1989 WriteDataChunks(ArchiveHandle *AH)
1990 {
1991         TocEntry   *te;
1992         StartDataPtr startPtr;
1993         EndDataPtr      endPtr;
1994
1995         for (te = AH->toc->next; te != AH->toc; te = te->next)
1996         {
1997                 if (te->dataDumper != NULL)
1998                 {
1999                         AH->currToc = te;
2000                         /* printf("Writing data for %d (%x)\n", te->id, te); */
2001
2002                         if (strcmp(te->desc, "BLOBS") == 0)
2003                         {
2004                                 startPtr = AH->StartBlobsPtr;
2005                                 endPtr = AH->EndBlobsPtr;
2006                         }
2007                         else
2008                         {
2009                                 startPtr = AH->StartDataPtr;
2010                                 endPtr = AH->EndDataPtr;
2011                         }
2012
2013                         if (startPtr != NULL)
2014                                 (*startPtr) (AH, te);
2015
2016                         /*
2017                          * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
2018                          */
2019
2020                         /*
2021                          * The user-provided DataDumper routine needs to call
2022                          * AH->WriteData
2023                          */
2024                         (*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
2025
2026                         if (endPtr != NULL)
2027                                 (*endPtr) (AH, te);
2028                         AH->currToc = NULL;
2029                 }
2030         }
2031 }
2032
2033 void
2034 WriteToc(ArchiveHandle *AH)
2035 {
2036         TocEntry   *te;
2037         char            workbuf[32];
2038         int                     i;
2039
2040         /* printf("%d TOC Entries to save\n", AH->tocCount); */
2041
2042         WriteInt(AH, AH->tocCount);
2043
2044         for (te = AH->toc->next; te != AH->toc; te = te->next)
2045         {
2046                 WriteInt(AH, te->dumpId);
2047                 WriteInt(AH, te->dataDumper ? 1 : 0);
2048
2049                 /* OID is recorded as a string for historical reasons */
2050                 sprintf(workbuf, "%u", te->catalogId.tableoid);
2051                 WriteStr(AH, workbuf);
2052                 sprintf(workbuf, "%u", te->catalogId.oid);
2053                 WriteStr(AH, workbuf);
2054
2055                 WriteStr(AH, te->tag);
2056                 WriteStr(AH, te->desc);
2057                 WriteInt(AH, te->section);
2058                 WriteStr(AH, te->defn);
2059                 WriteStr(AH, te->dropStmt);
2060                 WriteStr(AH, te->copyStmt);
2061                 WriteStr(AH, te->namespace);
2062                 WriteStr(AH, te->tablespace);
2063                 WriteStr(AH, te->owner);
2064                 WriteStr(AH, te->withOids ? "true" : "false");
2065
2066                 /* Dump list of dependencies */
2067                 for (i = 0; i < te->nDeps; i++)
2068                 {
2069                         sprintf(workbuf, "%d", te->dependencies[i]);
2070                         WriteStr(AH, workbuf);
2071                 }
2072                 WriteStr(AH, NULL);             /* Terminate List */
2073
2074                 if (AH->WriteExtraTocPtr)
2075                         (*AH->WriteExtraTocPtr) (AH, te);
2076         }
2077 }
2078
2079 void
2080 ReadToc(ArchiveHandle *AH)
2081 {
2082         int                     i;
2083         char       *tmp;
2084         DumpId     *deps;
2085         int                     depIdx;
2086         int                     depSize;
2087         TocEntry   *te;
2088
2089         AH->tocCount = ReadInt(AH);
2090         AH->maxDumpId = 0;
2091
2092         for (i = 0; i < AH->tocCount; i++)
2093         {
2094                 te = (TocEntry *) calloc(1, sizeof(TocEntry));
2095                 te->dumpId = ReadInt(AH);
2096
2097                 if (te->dumpId > AH->maxDumpId)
2098                         AH->maxDumpId = te->dumpId;
2099
2100                 /* Sanity check */
2101                 if (te->dumpId <= 0)
2102                         die_horribly(AH, modulename,
2103                                            "entry ID %d out of range -- perhaps a corrupt TOC\n",
2104                                                  te->dumpId);
2105
2106                 te->hadDumper = ReadInt(AH);
2107
2108                 if (AH->version >= K_VERS_1_8)
2109                 {
2110                         tmp = ReadStr(AH);
2111                         sscanf(tmp, "%u", &te->catalogId.tableoid);
2112                         free(tmp);
2113                 }
2114                 else
2115                         te->catalogId.tableoid = InvalidOid;
2116                 tmp = ReadStr(AH);
2117                 sscanf(tmp, "%u", &te->catalogId.oid);
2118                 free(tmp);
2119
2120                 te->tag = ReadStr(AH);
2121                 te->desc = ReadStr(AH);
2122
2123                 if (AH->version >= K_VERS_1_11)
2124                 {
2125                         te->section = ReadInt(AH);
2126                 }
2127                 else
2128                 {
2129                         /*
2130                          * Rules for pre-8.4 archives wherein pg_dump hasn't classified
2131                          * the entries into sections.  This list need not cover entry
2132                          * types added later than 8.4.
2133                          */
2134                         if (strcmp(te->desc, "COMMENT") == 0 ||
2135                                 strcmp(te->desc, "ACL") == 0 ||
2136                                 strcmp(te->desc, "ACL LANGUAGE") == 0)
2137                                 te->section = SECTION_NONE;
2138                         else if (strcmp(te->desc, "TABLE DATA") == 0 ||
2139                                          strcmp(te->desc, "BLOBS") == 0 ||
2140                                          strcmp(te->desc, "BLOB COMMENTS") == 0)
2141                                 te->section = SECTION_DATA;
2142                         else if (strcmp(te->desc, "CONSTRAINT") == 0 ||
2143                                          strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2144                                          strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2145                                          strcmp(te->desc, "INDEX") == 0 ||
2146                                          strcmp(te->desc, "RULE") == 0 ||
2147                                          strcmp(te->desc, "TRIGGER") == 0)
2148                                 te->section = SECTION_POST_DATA;
2149                         else
2150                                 te->section = SECTION_PRE_DATA;
2151                 }
2152
2153                 te->defn = ReadStr(AH);
2154                 te->dropStmt = ReadStr(AH);
2155
2156                 if (AH->version >= K_VERS_1_3)
2157                         te->copyStmt = ReadStr(AH);
2158
2159                 if (AH->version >= K_VERS_1_6)
2160                         te->namespace = ReadStr(AH);
2161
2162                 if (AH->version >= K_VERS_1_10)
2163                         te->tablespace = ReadStr(AH);
2164
2165                 te->owner = ReadStr(AH);
2166                 if (AH->version >= K_VERS_1_9)
2167                 {
2168                         if (strcmp(ReadStr(AH), "true") == 0)
2169                                 te->withOids = true;
2170                         else
2171                                 te->withOids = false;
2172                 }
2173                 else
2174                         te->withOids = true;
2175
2176                 /* Read TOC entry dependencies */
2177                 if (AH->version >= K_VERS_1_5)
2178                 {
2179                         depSize = 100;
2180                         deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
2181                         depIdx = 0;
2182                         for (;;)
2183                         {
2184                                 tmp = ReadStr(AH);
2185                                 if (!tmp)
2186                                         break;          /* end of list */
2187                                 if (depIdx >= depSize)
2188                                 {
2189                                         depSize *= 2;
2190                                         deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
2191                                 }
2192                                 sscanf(tmp, "%d", &deps[depIdx]);
2193                                 free(tmp);
2194                                 depIdx++;
2195                         }
2196
2197                         if (depIdx > 0)         /* We have a non-null entry */
2198                         {
2199                                 deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
2200                                 te->dependencies = deps;
2201                                 te->nDeps = depIdx;
2202                         }
2203                         else
2204                         {
2205                                 free(deps);
2206                                 te->dependencies = NULL;
2207                                 te->nDeps = 0;
2208                         }
2209                 }
2210                 else
2211                 {
2212                         te->dependencies = NULL;
2213                         te->nDeps = 0;
2214                 }
2215
2216                 if (AH->ReadExtraTocPtr)
2217                         (*AH->ReadExtraTocPtr) (AH, te);
2218
2219                 ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
2220                           i, te->dumpId, te->desc, te->tag);
2221
2222                 /* link completed entry into TOC circular list */
2223                 te->prev = AH->toc->prev;
2224                 AH->toc->prev->next = te;
2225                 AH->toc->prev = te;
2226                 te->next = AH->toc;
2227
2228                 /* special processing immediately upon read for some items */
2229                 if (strcmp(te->desc, "ENCODING") == 0)
2230                         processEncodingEntry(AH, te);
2231                 else if (strcmp(te->desc, "STDSTRINGS") == 0)
2232                         processStdStringsEntry(AH, te);
2233         }
2234 }
2235
2236 static void
2237 processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
2238 {
2239         /* te->defn should have the form SET client_encoding = 'foo'; */
2240         char       *defn = strdup(te->defn);
2241         char       *ptr1;
2242         char       *ptr2 = NULL;
2243         int                     encoding;
2244
2245         ptr1 = strchr(defn, '\'');
2246         if (ptr1)
2247                 ptr2 = strchr(++ptr1, '\'');
2248         if (ptr2)
2249         {
2250                 *ptr2 = '\0';
2251                 encoding = pg_char_to_encoding(ptr1);
2252                 if (encoding < 0)
2253                         die_horribly(AH, modulename, "unrecognized encoding \"%s\"\n",
2254                                                  ptr1);
2255                 AH->public.encoding = encoding;
2256         }
2257         else
2258                 die_horribly(AH, modulename, "invalid ENCODING item: %s\n",
2259                                          te->defn);
2260
2261         free(defn);
2262 }
2263
2264 static void
2265 processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
2266 {
2267         /* te->defn should have the form SET standard_conforming_strings = 'x'; */
2268         char       *ptr1;
2269
2270         ptr1 = strchr(te->defn, '\'');
2271         if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
2272                 AH->public.std_strings = true;
2273         else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
2274                 AH->public.std_strings = false;
2275         else
2276                 die_horribly(AH, modulename, "invalid STDSTRINGS item: %s\n",
2277                                          te->defn);
2278 }
2279
2280 static teReqs
2281 _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
2282 {
2283         teReqs          res = REQ_ALL;
2284
2285         /* ENCODING and STDSTRINGS items are dumped specially, so always reject */
2286         if (strcmp(te->desc, "ENCODING") == 0 ||
2287                 strcmp(te->desc, "STDSTRINGS") == 0)
2288                 return 0;
2289
2290         /* If it's an ACL, maybe ignore it */
2291         if ((!include_acls || ropt->aclsSkip) && _tocEntryIsACL(te))
2292                 return 0;
2293
2294         /* If it's security labels, maybe ignore it */
2295         if (ropt->skip_seclabel && strcmp(te->desc, "SECURITY LABEL") == 0)
2296                 return 0;
2297
2298         /* Ignore DATABASE entry unless we should create it */
2299         if (!ropt->createDB && strcmp(te->desc, "DATABASE") == 0)
2300                 return 0;
2301
2302         /* Check options for selective dump/restore */
2303         if (ropt->schemaNames)
2304         {
2305                 /* If no namespace is specified, it means all. */
2306                 if (!te->namespace)
2307                         return 0;
2308                 if (strcmp(ropt->schemaNames, te->namespace) != 0)
2309                         return 0;
2310         }
2311
2312         if (ropt->selTypes)
2313         {
2314                 if (strcmp(te->desc, "TABLE") == 0 ||
2315                         strcmp(te->desc, "TABLE DATA") == 0)
2316                 {
2317                         if (!ropt->selTable)
2318                                 return 0;
2319                         if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2320                                 return 0;
2321                 }
2322                 else if (strcmp(te->desc, "INDEX") == 0)
2323                 {
2324                         if (!ropt->selIndex)
2325                                 return 0;
2326                         if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2327                                 return 0;
2328                 }
2329                 else if (strcmp(te->desc, "FUNCTION") == 0)
2330                 {
2331                         if (!ropt->selFunction)
2332                                 return 0;
2333                         if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2334                                 return 0;
2335                 }
2336                 else if (strcmp(te->desc, "TRIGGER") == 0)
2337                 {
2338                         if (!ropt->selTrigger)
2339                                 return 0;
2340                         if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2341                                 return 0;
2342                 }
2343                 else
2344                         return 0;
2345         }
2346
2347         /*
2348          * Check if we had a dataDumper. Indicates if the entry is schema or data
2349          */
2350         if (!te->hadDumper)
2351         {
2352                 /*
2353                  * Special Case: If 'SEQUENCE SET' or anything to do with BLOBs, then
2354                  * it is considered a data entry.  We don't need to check for the
2355                  * BLOBS entry or old-style BLOB COMMENTS, because they will have
2356                  * hadDumper = true ... but we do need to check new-style BLOB
2357                  * comments.
2358                  */
2359                 if (strcmp(te->desc, "SEQUENCE SET") == 0 ||
2360                         strcmp(te->desc, "BLOB") == 0 ||
2361                         (strcmp(te->desc, "ACL") == 0 &&
2362                          strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
2363                         (strcmp(te->desc, "COMMENT") == 0 &&
2364                          strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
2365                         (strcmp(te->desc, "SECURITY LABEL") == 0 &&
2366                          strncmp(te->tag, "LARGE OBJECT ", 13) == 0))
2367                         res = res & REQ_DATA;
2368                 else
2369                         res = res & ~REQ_DATA;
2370         }
2371
2372         /*
2373          * Special case: <Init> type with <Max OID> tag; this is obsolete and we
2374          * always ignore it.
2375          */
2376         if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2377                 return 0;
2378
2379         /* Mask it if we only want schema */
2380         if (ropt->schemaOnly)
2381                 res = res & REQ_SCHEMA;
2382
2383         /* Mask it we only want data */
2384         if (ropt->dataOnly)
2385                 res = res & REQ_DATA;
2386
2387         /* Mask it if we don't have a schema contribution */
2388         if (!te->defn || strlen(te->defn) == 0)
2389                 res = res & ~REQ_SCHEMA;
2390
2391         /* Finally, if there's a per-ID filter, limit based on that as well */
2392         if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
2393                 return 0;
2394
2395         return res;
2396 }
2397
2398 /*
2399  * Identify TOC entries that are ACLs.
2400  */
2401 static bool
2402 _tocEntryIsACL(TocEntry *te)
2403 {
2404         /* "ACL LANGUAGE" was a crock emitted only in PG 7.4 */
2405         if (strcmp(te->desc, "ACL") == 0 ||
2406                 strcmp(te->desc, "ACL LANGUAGE") == 0 ||
2407                 strcmp(te->desc, "DEFAULT ACL") == 0)
2408                 return true;
2409         return false;
2410 }
2411
2412 /*
2413  * Issue SET commands for parameters that we want to have set the same way
2414  * at all times during execution of a restore script.
2415  */
2416 static void
2417 _doSetFixedOutputState(ArchiveHandle *AH)
2418 {
2419         /* Disable statement_timeout in archive for pg_restore/psql  */
2420         ahprintf(AH, "SET statement_timeout = 0;\n");
2421
2422         /* Select the correct character set encoding */
2423         ahprintf(AH, "SET client_encoding = '%s';\n",
2424                          pg_encoding_to_char(AH->public.encoding));
2425
2426         /* Select the correct string literal syntax */
2427         ahprintf(AH, "SET standard_conforming_strings = %s;\n",
2428                          AH->public.std_strings ? "on" : "off");
2429
2430         /* Select the role to be used during restore */
2431         if (AH->ropt && AH->ropt->use_role)
2432                 ahprintf(AH, "SET ROLE %s;\n", fmtId(AH->ropt->use_role));
2433
2434         /* Make sure function checking is disabled */
2435         ahprintf(AH, "SET check_function_bodies = false;\n");
2436
2437         /* Avoid annoying notices etc */
2438         ahprintf(AH, "SET client_min_messages = warning;\n");
2439         if (!AH->public.std_strings)
2440                 ahprintf(AH, "SET escape_string_warning = off;\n");
2441
2442         ahprintf(AH, "\n");
2443 }
2444
2445 /*
2446  * Issue a SET SESSION AUTHORIZATION command.  Caller is responsible
2447  * for updating state if appropriate.  If user is NULL or an empty string,
2448  * the specification DEFAULT will be used.
2449  */
2450 static void
2451 _doSetSessionAuth(ArchiveHandle *AH, const char *user)
2452 {
2453         PQExpBuffer cmd = createPQExpBuffer();
2454
2455         appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
2456
2457         /*
2458          * SQL requires a string literal here.  Might as well be correct.
2459          */
2460         if (user && *user)
2461                 appendStringLiteralAHX(cmd, user, AH);
2462         else
2463                 appendPQExpBuffer(cmd, "DEFAULT");
2464         appendPQExpBuffer(cmd, ";");
2465
2466         if (RestoringToDB(AH))
2467         {
2468                 PGresult   *res;
2469
2470                 res = PQexec(AH->connection, cmd->data);
2471
2472                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2473                         /* NOT warn_or_die_horribly... use -O instead to skip this. */
2474                         die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2475                                                  user, PQerrorMessage(AH->connection));
2476
2477                 PQclear(res);
2478         }
2479         else
2480                 ahprintf(AH, "%s\n\n", cmd->data);
2481
2482         destroyPQExpBuffer(cmd);
2483 }
2484
2485
2486 /*
2487  * Issue a SET default_with_oids command.  Caller is responsible
2488  * for updating state if appropriate.
2489  */
2490 static void
2491 _doSetWithOids(ArchiveHandle *AH, const bool withOids)
2492 {
2493         PQExpBuffer cmd = createPQExpBuffer();
2494
2495         appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
2496                                           "true" : "false");
2497
2498         if (RestoringToDB(AH))
2499         {
2500                 PGresult   *res;
2501
2502                 res = PQexec(AH->connection, cmd->data);
2503
2504                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2505                         warn_or_die_horribly(AH, modulename,
2506                                                                  "could not set default_with_oids: %s",
2507                                                                  PQerrorMessage(AH->connection));
2508
2509                 PQclear(res);
2510         }
2511         else
2512                 ahprintf(AH, "%s\n\n", cmd->data);
2513
2514         destroyPQExpBuffer(cmd);
2515 }
2516
2517
2518 /*
2519  * Issue the commands to connect to the specified database.
2520  *
2521  * If we're currently restoring right into a database, this will
2522  * actually establish a connection. Otherwise it puts a \connect into
2523  * the script output.
2524  *
2525  * NULL dbname implies reconnecting to the current DB (pretty useless).
2526  */
2527 static void
2528 _reconnectToDB(ArchiveHandle *AH, const char *dbname)
2529 {
2530         if (RestoringToDB(AH))
2531                 ReconnectToServer(AH, dbname, NULL);
2532         else
2533         {
2534                 PQExpBuffer qry = createPQExpBuffer();
2535
2536                 appendPQExpBuffer(qry, "\\connect %s\n\n",
2537                                                   dbname ? fmtId(dbname) : "-");
2538                 ahprintf(AH, "%s", qry->data);
2539                 destroyPQExpBuffer(qry);
2540         }
2541
2542         /*
2543          * NOTE: currUser keeps track of what the imaginary session user in our
2544          * script is.  It's now effectively reset to the original userID.
2545          */
2546         if (AH->currUser)
2547                 free(AH->currUser);
2548         AH->currUser = NULL;
2549
2550         /* don't assume we still know the output schema, tablespace, etc either */
2551         if (AH->currSchema)
2552                 free(AH->currSchema);
2553         AH->currSchema = NULL;
2554         if (AH->currTablespace)
2555                 free(AH->currTablespace);
2556         AH->currTablespace = NULL;
2557         AH->currWithOids = -1;
2558
2559         /* re-establish fixed state */
2560         _doSetFixedOutputState(AH);
2561 }
2562
2563 /*
2564  * Become the specified user, and update state to avoid redundant commands
2565  *
2566  * NULL or empty argument is taken to mean restoring the session default
2567  */
2568 static void
2569 _becomeUser(ArchiveHandle *AH, const char *user)
2570 {
2571         if (!user)
2572                 user = "";                              /* avoid null pointers */
2573
2574         if (AH->currUser && strcmp(AH->currUser, user) == 0)
2575                 return;                                 /* no need to do anything */
2576
2577         _doSetSessionAuth(AH, user);
2578
2579         /*
2580          * NOTE: currUser keeps track of what the imaginary session user in our
2581          * script is
2582          */
2583         if (AH->currUser)
2584                 free(AH->currUser);
2585         AH->currUser = strdup(user);
2586 }
2587
2588 /*
2589  * Become the owner of the given TOC entry object.      If
2590  * changes in ownership are not allowed, this doesn't do anything.
2591  */
2592 static void
2593 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
2594 {
2595         if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2596                 return;
2597
2598         _becomeUser(AH, te->owner);
2599 }
2600
2601
2602 /*
2603  * Set the proper default_with_oids value for the table.
2604  */
2605 static void
2606 _setWithOids(ArchiveHandle *AH, TocEntry *te)
2607 {
2608         if (AH->currWithOids != te->withOids)
2609         {
2610                 _doSetWithOids(AH, te->withOids);
2611                 AH->currWithOids = te->withOids;
2612         }
2613 }
2614
2615
2616 /*
2617  * Issue the commands to select the specified schema as the current schema
2618  * in the target database.
2619  */
2620 static void
2621 _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
2622 {
2623         PQExpBuffer qry;
2624
2625         if (!schemaName || *schemaName == '\0' ||
2626                 (AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2627                 return;                                 /* no need to do anything */
2628
2629         qry = createPQExpBuffer();
2630
2631         appendPQExpBuffer(qry, "SET search_path = %s",
2632                                           fmtId(schemaName));
2633         if (strcmp(schemaName, "pg_catalog") != 0)
2634                 appendPQExpBuffer(qry, ", pg_catalog");
2635
2636         if (RestoringToDB(AH))
2637         {
2638                 PGresult   *res;
2639
2640                 res = PQexec(AH->connection, qry->data);
2641
2642                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2643                         warn_or_die_horribly(AH, modulename,
2644                                                                  "could not set search_path to \"%s\": %s",
2645                                                                  schemaName, PQerrorMessage(AH->connection));
2646
2647                 PQclear(res);
2648         }
2649         else
2650                 ahprintf(AH, "%s;\n\n", qry->data);
2651
2652         if (AH->currSchema)
2653                 free(AH->currSchema);
2654         AH->currSchema = strdup(schemaName);
2655
2656         destroyPQExpBuffer(qry);
2657 }
2658
2659 /*
2660  * Issue the commands to select the specified tablespace as the current one
2661  * in the target database.
2662  */
2663 static void
2664 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
2665 {
2666         PQExpBuffer qry;
2667         const char *want,
2668                            *have;
2669
2670         /* do nothing in --no-tablespaces mode */
2671         if (AH->ropt->noTablespace)
2672                 return;
2673
2674         have = AH->currTablespace;
2675         want = tablespace;
2676
2677         /* no need to do anything for non-tablespace object */
2678         if (!want)
2679                 return;
2680
2681         if (have && strcmp(want, have) == 0)
2682                 return;                                 /* no need to do anything */
2683
2684         qry = createPQExpBuffer();
2685
2686         if (strcmp(want, "") == 0)
2687         {
2688                 /* We want the tablespace to be the database's default */
2689                 appendPQExpBuffer(qry, "SET default_tablespace = ''");
2690         }
2691         else
2692         {
2693                 /* We want an explicit tablespace */
2694                 appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
2695         }
2696
2697         if (RestoringToDB(AH))
2698         {
2699                 PGresult   *res;
2700
2701                 res = PQexec(AH->connection, qry->data);
2702
2703                 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2704                         warn_or_die_horribly(AH, modulename,
2705                                                                  "could not set default_tablespace to %s: %s",
2706                                                                  fmtId(want), PQerrorMessage(AH->connection));
2707
2708                 PQclear(res);
2709         }
2710         else
2711                 ahprintf(AH, "%s;\n\n", qry->data);
2712
2713         if (AH->currTablespace)
2714                 free(AH->currTablespace);
2715         AH->currTablespace = strdup(want);
2716
2717         destroyPQExpBuffer(qry);
2718 }
2719
2720 /*
2721  * Extract an object description for a TOC entry, and append it to buf.
2722  *
2723  * This is not quite as general as it may seem, since it really only
2724  * handles constructing the right thing to put into ALTER ... OWNER TO.
2725  *
2726  * The whole thing is pretty grotty, but we are kind of stuck since the
2727  * information used is all that's available in older dump files.
2728  */
2729 static void
2730 _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2731 {
2732         const char *type = te->desc;
2733
2734         /* Use ALTER TABLE for views and sequences */
2735         if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2736                 type = "TABLE";
2737
2738         /* objects named by a schema and name */
2739         if (strcmp(type, "CONVERSION") == 0 ||
2740                 strcmp(type, "DOMAIN") == 0 ||
2741                 strcmp(type, "TABLE") == 0 ||
2742                 strcmp(type, "TYPE") == 0 ||
2743                 strcmp(type, "FOREIGN TABLE") == 0 ||
2744                 strcmp(type, "TEXT SEARCH DICTIONARY") == 0 ||
2745                 strcmp(type, "TEXT SEARCH CONFIGURATION") == 0)
2746         {
2747                 appendPQExpBuffer(buf, "%s ", type);
2748                 if (te->namespace && te->namespace[0])  /* is null pre-7.3 */
2749                         appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
2750
2751                 /*
2752                  * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
2753                  * into te->tag for an index. This check is heuristic, so make its
2754                  * scope as narrow as possible.
2755                  */
2756                 if (AH->version < K_VERS_1_7 &&
2757                         te->tag[0] == '"' &&
2758                         te->tag[strlen(te->tag) - 1] == '"' &&
2759                         strcmp(type, "INDEX") == 0)
2760                         appendPQExpBuffer(buf, "%s", te->tag);
2761                 else
2762                         appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2763                 return;
2764         }
2765
2766         /* objects named by just a name */
2767         if (strcmp(type, "DATABASE") == 0 ||
2768                 strcmp(type, "PROCEDURAL LANGUAGE") == 0 ||
2769                 strcmp(type, "SCHEMA") == 0 ||
2770                 strcmp(type, "FOREIGN DATA WRAPPER") == 0 ||
2771                 strcmp(type, "SERVER") == 0 ||
2772                 strcmp(type, "USER MAPPING") == 0)
2773         {
2774                 appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
2775                 return;
2776         }
2777
2778         /* BLOBs just have a name, but it's numeric so must not use fmtId */
2779         if (strcmp(type, "BLOB") == 0)
2780         {
2781                 appendPQExpBuffer(buf, "LARGE OBJECT %s", te->tag);
2782                 return;
2783         }
2784
2785         /*
2786          * These object types require additional decoration.  Fortunately, the
2787          * information needed is exactly what's in the DROP command.
2788          */
2789         if (strcmp(type, "AGGREGATE") == 0 ||
2790                 strcmp(type, "FUNCTION") == 0 ||
2791                 strcmp(type, "OPERATOR") == 0 ||
2792                 strcmp(type, "OPERATOR CLASS") == 0 ||
2793                 strcmp(type, "OPERATOR FAMILY") == 0)
2794         {
2795                 /* Chop "DROP " off the front and make a modifiable copy */
2796                 char       *first = strdup(te->dropStmt + 5);
2797                 char       *last;
2798
2799                 /* point to last character in string */
2800                 last = first + strlen(first) - 1;
2801
2802                 /* Strip off any ';' or '\n' at the end */
2803                 while (last >= first && (*last == '\n' || *last == ';'))
2804                         last--;
2805                 *(last + 1) = '\0';
2806
2807                 appendPQExpBufferStr(buf, first);
2808
2809                 free(first);
2810                 return;
2811         }
2812
2813         write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2814                           type);
2815 }
2816
2817 static void
2818 _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
2819 {
2820         /* ACLs are dumped only during acl pass */
2821         if (acl_pass)
2822         {
2823                 if (!_tocEntryIsACL(te))
2824                         return;
2825         }
2826         else
2827         {
2828                 if (_tocEntryIsACL(te))
2829                         return;
2830         }
2831
2832         /*
2833          * Avoid dumping the public schema, as it will already be created ...
2834          * unless we are using --clean mode, in which case it's been deleted and
2835          * we'd better recreate it.  Likewise for its comment, if any.
2836          */
2837         if (!ropt->dropSchema)
2838         {
2839                 if (strcmp(te->desc, "SCHEMA") == 0 &&
2840                         strcmp(te->tag, "public") == 0)
2841                         return;
2842                 /* The comment restore would require super-user privs, so avoid it. */
2843                 if (strcmp(te->desc, "COMMENT") == 0 &&
2844                         strcmp(te->tag, "SCHEMA public") == 0)
2845                         return;
2846         }
2847
2848         /* Select owner, schema, and tablespace as necessary */
2849         _becomeOwner(AH, te);
2850         _selectOutputSchema(AH, te->namespace);
2851         _selectTablespace(AH, te->tablespace);
2852
2853         /* Set up OID mode too */
2854         if (strcmp(te->desc, "TABLE") == 0)
2855                 _setWithOids(AH, te);
2856
2857         /* Emit header comment for item */
2858         if (!AH->noTocComments)
2859         {
2860                 const char *pfx;
2861
2862                 if (isData)
2863                         pfx = "Data for ";
2864                 else
2865                         pfx = "";
2866
2867                 ahprintf(AH, "--\n");
2868                 if (AH->public.verbose)
2869                 {
2870                         ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
2871                                          te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
2872                         if (te->nDeps > 0)
2873                         {
2874                                 int                     i;
2875
2876                                 ahprintf(AH, "-- Dependencies:");
2877                                 for (i = 0; i < te->nDeps; i++)
2878                                         ahprintf(AH, " %d", te->dependencies[i]);
2879                                 ahprintf(AH, "\n");
2880                         }
2881                 }
2882                 ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2883                                  pfx, te->tag, te->desc,
2884                                  te->namespace ? te->namespace : "-",
2885                                  ropt->noOwner ? "-" : te->owner);
2886                 if (te->tablespace && !ropt->noTablespace)
2887                         ahprintf(AH, "; Tablespace: %s", te->tablespace);
2888                 ahprintf(AH, "\n");
2889
2890                 if (AH->PrintExtraTocPtr !=NULL)
2891                         (*AH->PrintExtraTocPtr) (AH, te);
2892                 ahprintf(AH, "--\n\n");
2893         }
2894
2895         /*
2896          * Actually print the definition.
2897          *
2898          * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
2899          * versions put into CREATE SCHEMA.  We have to do this when --no-owner
2900          * mode is selected.  This is ugly, but I see no other good way ...
2901          */
2902         if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2903         {
2904                 ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2905         }
2906         else
2907         {
2908                 if (strlen(te->defn) > 0)
2909                         ahprintf(AH, "%s\n\n", te->defn);
2910         }
2911
2912         /*
2913          * If we aren't using SET SESSION AUTH to determine ownership, we must
2914          * instead issue an ALTER OWNER command.  We assume that anything without
2915          * a DROP command is not a separately ownable object.  All the categories
2916          * with DROP commands must appear in one list or the other.
2917          */
2918         if (!ropt->noOwner && !ropt->use_setsessauth &&
2919                 strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
2920         {
2921                 if (strcmp(te->desc, "AGGREGATE") == 0 ||
2922                         strcmp(te->desc, "BLOB") == 0 ||
2923                         strcmp(te->desc, "CONVERSION") == 0 ||
2924                         strcmp(te->desc, "DATABASE") == 0 ||
2925                         strcmp(te->desc, "DOMAIN") == 0 ||
2926                         strcmp(te->desc, "FUNCTION") == 0 ||
2927                         strcmp(te->desc, "OPERATOR") == 0 ||
2928                         strcmp(te->desc, "OPERATOR CLASS") == 0 ||
2929                         strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
2930                         strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
2931                         strcmp(te->desc, "SCHEMA") == 0 ||
2932                         strcmp(te->desc, "TABLE") == 0 ||
2933                         strcmp(te->desc, "TYPE") == 0 ||
2934                         strcmp(te->desc, "VIEW") == 0 ||
2935                         strcmp(te->desc, "SEQUENCE") == 0 ||
2936                         strcmp(te->desc, "FOREIGN TABLE") == 0 ||
2937                         strcmp(te->desc, "TEXT SEARCH DICTIONARY") == 0 ||
2938                         strcmp(te->desc, "TEXT SEARCH CONFIGURATION") == 0 ||
2939                         strcmp(te->desc, "FOREIGN DATA WRAPPER") == 0 ||
2940                         strcmp(te->desc, "SERVER") == 0)
2941                 {
2942                         PQExpBuffer temp = createPQExpBuffer();
2943
2944                         appendPQExpBuffer(temp, "ALTER ");
2945                         _getObjectDescription(temp, te, AH);
2946                         appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
2947                         ahprintf(AH, "%s\n\n", temp->data);
2948                         destroyPQExpBuffer(temp);
2949                 }
2950                 else if (strcmp(te->desc, "CAST") == 0 ||
2951                                  strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
2952                                  strcmp(te->desc, "CONSTRAINT") == 0 ||
2953                                  strcmp(te->desc, "DEFAULT") == 0 ||
2954                                  strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2955                                  strcmp(te->desc, "INDEX") == 0 ||
2956                                  strcmp(te->desc, "RULE") == 0 ||
2957                                  strcmp(te->desc, "TRIGGER") == 0 ||
2958                                  strcmp(te->desc, "USER MAPPING") == 0)
2959                 {
2960                         /* these object types don't have separate owners */
2961                 }
2962                 else
2963                 {
2964                         write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
2965                                           te->desc);
2966                 }
2967         }
2968
2969         /*
2970          * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
2971          * commands, so we can no longer assume we know the current auth setting.
2972          */
2973         if (acl_pass)
2974         {
2975                 if (AH->currUser)
2976                         free(AH->currUser);
2977                 AH->currUser = NULL;
2978         }
2979 }
2980
2981 void
2982 WriteHead(ArchiveHandle *AH)
2983 {
2984         struct tm       crtm;
2985
2986         (*AH->WriteBufPtr) (AH, "PGDMP", 5);            /* Magic code */
2987         (*AH->WriteBytePtr) (AH, AH->vmaj);
2988         (*AH->WriteBytePtr) (AH, AH->vmin);
2989         (*AH->WriteBytePtr) (AH, AH->vrev);
2990         (*AH->WriteBytePtr) (AH, AH->intSize);
2991         (*AH->WriteBytePtr) (AH, AH->offSize);
2992         (*AH->WriteBytePtr) (AH, AH->format);
2993
2994 #ifndef HAVE_LIBZ
2995         if (AH->compression != 0)
2996                 write_msg(modulename, "WARNING: requested compression not available in this "
2997                                   "installation -- archive will be uncompressed\n");
2998
2999         AH->compression = 0;
3000 #endif
3001
3002         WriteInt(AH, AH->compression);
3003
3004         crtm = *localtime(&AH->createDate);
3005         WriteInt(AH, crtm.tm_sec);
3006         WriteInt(AH, crtm.tm_min);
3007         WriteInt(AH, crtm.tm_hour);
3008         WriteInt(AH, crtm.tm_mday);
3009         WriteInt(AH, crtm.tm_mon);
3010         WriteInt(AH, crtm.tm_year);
3011         WriteInt(AH, crtm.tm_isdst);
3012         WriteStr(AH, PQdb(AH->connection));
3013         WriteStr(AH, AH->public.remoteVersionStr);
3014         WriteStr(AH, PG_VERSION);
3015 }
3016
3017 void
3018 ReadHead(ArchiveHandle *AH)
3019 {
3020         char            tmpMag[7];
3021         int                     fmt;
3022         struct tm       crtm;
3023
3024         /*
3025          * If we haven't already read the header, do so.
3026          *
3027          * NB: this code must agree with _discoverArchiveFormat().      Maybe find a
3028          * way to unify the cases?
3029          */
3030         if (!AH->readHeader)
3031         {
3032                 if ((*AH->ReadBufPtr) (AH, tmpMag, 5) != 5)
3033                         die_horribly(AH, modulename, "unexpected end of file\n");
3034
3035                 if (strncmp(tmpMag, "PGDMP", 5) != 0)
3036                         die_horribly(AH, modulename, "did not find magic string in file header\n");
3037
3038                 AH->vmaj = (*AH->ReadBytePtr) (AH);
3039                 AH->vmin = (*AH->ReadBytePtr) (AH);
3040
3041                 if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))                /* Version > 1.0 */
3042                         AH->vrev = (*AH->ReadBytePtr) (AH);
3043                 else
3044                         AH->vrev = 0;
3045
3046                 AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
3047
3048                 if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
3049                         die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
3050                                                  AH->vmaj, AH->vmin);
3051
3052                 AH->intSize = (*AH->ReadBytePtr) (AH);
3053                 if (AH->intSize > 32)
3054                         die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
3055                                                  (unsigned long) AH->intSize);
3056
3057                 if (AH->intSize > sizeof(int))
3058                         write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations might fail\n");
3059
3060                 if (AH->version >= K_VERS_1_7)
3061                         AH->offSize = (*AH->ReadBytePtr) (AH);
3062                 else
3063                         AH->offSize = AH->intSize;
3064
3065                 fmt = (*AH->ReadBytePtr) (AH);
3066
3067                 if (AH->format != fmt)
3068                         die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
3069                                                  AH->format, fmt);
3070         }
3071
3072         if (AH->version >= K_VERS_1_2)
3073         {
3074                 if (AH->version < K_VERS_1_4)
3075                         AH->compression = (*AH->ReadBytePtr) (AH);
3076                 else
3077                         AH->compression = ReadInt(AH);
3078         }
3079         else
3080                 AH->compression = Z_DEFAULT_COMPRESSION;
3081
3082 #ifndef HAVE_LIBZ
3083         if (AH->compression != 0)
3084                 write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
3085 #endif
3086
3087         if (AH->version >= K_VERS_1_4)
3088         {
3089                 crtm.tm_sec = ReadInt(AH);
3090                 crtm.tm_min = ReadInt(AH);
3091                 crtm.tm_hour = ReadInt(AH);
3092                 crtm.tm_mday = ReadInt(AH);
3093                 crtm.tm_mon = ReadInt(AH);
3094                 crtm.tm_year = ReadInt(AH);
3095                 crtm.tm_isdst = ReadInt(AH);
3096
3097                 AH->archdbname = ReadStr(AH);
3098
3099                 AH->createDate = mktime(&crtm);
3100
3101                 if (AH->createDate == (time_t) -1)
3102                         write_msg(modulename, "WARNING: invalid creation date in header\n");
3103         }
3104
3105         if (AH->version >= K_VERS_1_10)
3106         {
3107                 AH->archiveRemoteVersion = ReadStr(AH);
3108                 AH->archiveDumpVersion = ReadStr(AH);
3109         }
3110 }
3111
3112
3113 /*
3114  * checkSeek
3115  *        check to see if ftell/fseek can be performed.
3116  */
3117 bool
3118 checkSeek(FILE *fp)
3119 {
3120         pgoff_t         tpos;
3121
3122         /*
3123          * If pgoff_t is wider than long, we must have "real" fseeko and not an
3124          * emulation using fseek.  Otherwise report no seek capability.
3125          */
3126 #ifndef HAVE_FSEEKO
3127         if (sizeof(pgoff_t) > sizeof(long))
3128                 return false;
3129 #endif
3130
3131         /* Check that ftello works on this file */
3132         errno = 0;
3133         tpos = ftello(fp);
3134         if (errno)
3135                 return false;
3136
3137         /*
3138          * Check that fseeko(SEEK_SET) works, too.      NB: we used to try to test
3139          * this with fseeko(fp, 0, SEEK_CUR).  But some platforms treat that as a
3140          * successful no-op even on files that are otherwise unseekable.
3141          */
3142         if (fseeko(fp, tpos, SEEK_SET) != 0)
3143                 return false;
3144
3145         return true;
3146 }
3147
3148
3149 /*
3150  * dumpTimestamp
3151  */
3152 static void
3153 dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
3154 {
3155         char            buf[256];
3156
3157         /*
3158          * We don't print the timezone on Win32, because the names are long and
3159          * localized, which means they may contain characters in various random
3160          * encodings; this has been seen to cause encoding errors when reading the
3161          * dump script.
3162          */
3163         if (strftime(buf, sizeof(buf),
3164 #ifndef WIN32
3165                                  "%Y-%m-%d %H:%M:%S %Z",
3166 #else
3167                                  "%Y-%m-%d %H:%M:%S",
3168 #endif
3169                                  localtime(&tim)) != 0)
3170                 ahprintf(AH, "-- %s %s\n\n", msg, buf);
3171 }
3172
3173
3174 /*
3175  * Main engine for parallel restore.
3176  *
3177  * Work is done in three phases.
3178  * First we process tocEntries until we come to one that is marked
3179  * SECTION_DATA or SECTION_POST_DATA, in a single connection, just as for a
3180  * standard restore.  Second we process the remaining non-ACL steps in
3181  * parallel worker children (threads on Windows, processes on Unix), each of
3182  * which connects separately to the database.  Finally we process all the ACL
3183  * entries in a single connection (that happens back in RestoreArchive).
3184  */
3185 static void
3186 restore_toc_entries_parallel(ArchiveHandle *AH)
3187 {
3188         RestoreOptions *ropt = AH->ropt;
3189         int                     n_slots = ropt->number_of_jobs;
3190         ParallelSlot *slots;
3191         int                     work_status;
3192         int                     next_slot;
3193         TocEntry        pending_list;
3194         TocEntry        ready_list;
3195         TocEntry   *next_work_item;
3196         thandle         ret_child;
3197         TocEntry   *te;
3198
3199         ahlog(AH, 2, "entering restore_toc_entries_parallel\n");
3200
3201         /* we haven't got round to making this work for all archive formats */
3202         if (AH->ClonePtr == NULL || AH->ReopenPtr == NULL)
3203                 die_horribly(AH, modulename, "parallel restore is not supported with this archive file format\n");
3204
3205         /* doesn't work if the archive represents dependencies as OIDs, either */
3206         if (AH->version < K_VERS_1_8)
3207                 die_horribly(AH, modulename, "parallel restore is not supported with archives made by pre-8.0 pg_dump\n");
3208
3209         slots = (ParallelSlot *) calloc(sizeof(ParallelSlot), n_slots);
3210
3211         /* Adjust dependency information */
3212         fix_dependencies(AH);
3213
3214         /*
3215          * Do all the early stuff in a single connection in the parent. There's no
3216          * great point in running it in parallel, in fact it will actually run
3217          * faster in a single connection because we avoid all the connection and
3218          * setup overhead.  Also, pg_dump is not currently very good about
3219          * showing all the dependencies of SECTION_PRE_DATA items, so we do not
3220          * risk trying to process them out-of-order.
3221          */
3222         for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3223         {
3224                 /* Non-PRE_DATA items are just ignored for now */
3225                 if (next_work_item->section == SECTION_DATA ||
3226                         next_work_item->section == SECTION_POST_DATA)
3227                         continue;
3228
3229                 ahlog(AH, 1, "processing item %d %s %s\n",
3230                           next_work_item->dumpId,
3231                           next_work_item->desc, next_work_item->tag);
3232
3233                 (void) restore_toc_entry(AH, next_work_item, ropt, false);
3234
3235                 /* there should be no touch of ready_list here, so pass NULL */
3236                 reduce_dependencies(AH, next_work_item, NULL);
3237         }
3238
3239         /*
3240          * Now close parent connection in prep for parallel steps.      We do this
3241          * mainly to ensure that we don't exceed the specified number of parallel
3242          * connections.
3243          */
3244         PQfinish(AH->connection);
3245         AH->connection = NULL;
3246
3247         /* blow away any transient state from the old connection */
3248         if (AH->currUser)
3249                 free(AH->currUser);
3250         AH->currUser = NULL;
3251         if (AH->currSchema)
3252                 free(AH->currSchema);
3253         AH->currSchema = NULL;
3254         if (AH->currTablespace)
3255                 free(AH->currTablespace);
3256         AH->currTablespace = NULL;
3257         AH->currWithOids = -1;
3258
3259         /*
3260          * Initialize the lists of pending and ready items.  After this setup, the
3261          * pending list is everything that needs to be done but is blocked by one
3262          * or more dependencies, while the ready list contains items that have no
3263          * remaining dependencies.      Note: we don't yet filter out entries that
3264          * aren't going to be restored.  They might participate in dependency
3265          * chains connecting entries that should be restored, so we treat them as
3266          * live until we actually process them.
3267          */
3268         par_list_header_init(&pending_list);
3269         par_list_header_init(&ready_list);
3270         for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3271         {
3272                 /* All PRE_DATA items were dealt with above */
3273                 if (next_work_item->section == SECTION_DATA ||
3274                         next_work_item->section == SECTION_POST_DATA)
3275                 {
3276                         if (next_work_item->depCount > 0)
3277                                 par_list_append(&pending_list, next_work_item);
3278                         else
3279                                 par_list_append(&ready_list, next_work_item);
3280                 }
3281         }
3282
3283         /*
3284          * main parent loop
3285          *
3286          * Keep going until there is no worker still running AND there is no work
3287          * left to be done.
3288          */
3289
3290         ahlog(AH, 1, "entering main parallel loop\n");
3291
3292         while ((next_work_item = get_next_work_item(AH, &ready_list,
3293                                                                                                 slots, n_slots)) != NULL ||
3294                    work_in_progress(slots, n_slots))
3295         {
3296                 if (next_work_item != NULL)
3297                 {
3298                         teReqs          reqs;
3299
3300                         /* If not to be dumped, don't waste time launching a worker */
3301                         reqs = _tocEntryRequired(next_work_item, AH->ropt, false);
3302                         if ((reqs & (REQ_SCHEMA | REQ_DATA)) == 0)
3303                         {
3304                                 ahlog(AH, 1, "skipping item %d %s %s\n",
3305                                           next_work_item->dumpId,
3306                                           next_work_item->desc, next_work_item->tag);
3307
3308                                 par_list_remove(next_work_item);
3309                                 reduce_dependencies(AH, next_work_item, &ready_list);
3310
3311                                 continue;
3312                         }
3313
3314                         if ((next_slot = get_next_slot(slots, n_slots)) != NO_SLOT)
3315                         {
3316                                 /* There is work still to do and a worker slot available */
3317                                 thandle         child;
3318                                 RestoreArgs *args;
3319
3320                                 ahlog(AH, 1, "launching item %d %s %s\n",
3321                                           next_work_item->dumpId,
3322                                           next_work_item->desc, next_work_item->tag);
3323
3324                                 par_list_remove(next_work_item);
3325
3326                                 /* this memory is dealloced in mark_work_done() */
3327                                 args = malloc(sizeof(RestoreArgs));
3328                                 args->AH = CloneArchive(AH);
3329                                 args->te = next_work_item;
3330
3331                                 /* run the step in a worker child */
3332                                 child = spawn_restore(args);
3333
3334                                 slots[next_slot].child_id = child;
3335                                 slots[next_slot].args = args;
3336
3337                                 continue;
3338                         }
3339                 }
3340
3341                 /*
3342                  * If we get here there must be work being done.  Either there is no
3343                  * work available to schedule (and work_in_progress returned true) or
3344                  * there are no slots available.  So we wait for a worker to finish,
3345                  * and process the result.
3346                  */
3347                 ret_child = reap_child(slots, n_slots, &work_status);
3348
3349                 if (WIFEXITED(work_status))
3350                 {
3351                         mark_work_done(AH, &ready_list,
3352                                                    ret_child, WEXITSTATUS(work_status),
3353                                                    slots, n_slots);
3354                 }
3355                 else
3356                 {
3357                         die_horribly(AH, modulename, "worker process crashed: status %d\n",
3358                                                  work_status);
3359                 }
3360         }
3361
3362         ahlog(AH, 1, "finished main parallel loop\n");
3363
3364         /*
3365          * Now reconnect the single parent connection.
3366          */
3367         ConnectDatabase((Archive *) AH, ropt->dbname,
3368                                         ropt->pghost, ropt->pgport, ropt->username,
3369                                         ropt->promptPassword);
3370
3371         _doSetFixedOutputState(AH);
3372
3373         /*
3374          * Make sure there is no non-ACL work left due to, say, circular
3375          * dependencies, or some other pathological condition. If so, do it in the
3376          * single parent connection.
3377          */
3378         for (te = pending_list.par_next; te != &pending_list; te = te->par_next)
3379         {
3380                 ahlog(AH, 1, "processing missed item %d %s %s\n",
3381                           te->dumpId, te->desc, te->tag);
3382                 (void) restore_toc_entry(AH, te, ropt, false);
3383         }
3384
3385         /* The ACLs will be handled back in RestoreArchive. */
3386 }
3387
3388 /*
3389  * create a worker child to perform a restore step in parallel
3390  */
3391 static thandle
3392 spawn_restore(RestoreArgs *args)
3393 {
3394         thandle         child;
3395
3396         /* Ensure stdio state is quiesced before forking */
3397         fflush(NULL);
3398
3399 #ifndef WIN32
3400         child = fork();
3401         if (child == 0)
3402         {
3403                 /* in child process */
3404                 parallel_restore(args);
3405                 die_horribly(args->AH, modulename,
3406                                          "parallel_restore should not return\n");
3407         }
3408         else if (child < 0)
3409         {
3410                 /* fork failed */
3411                 die_horribly(args->AH, modulename,
3412                                          "could not create worker process: %s\n",
3413                                          strerror(errno));
3414         }
3415 #else
3416         child = (HANDLE) _beginthreadex(NULL, 0, (void *) parallel_restore,
3417                                                                         args, 0, NULL);
3418         if (child == 0)
3419                 die_horribly(args->AH, modulename,
3420                                          "could not create worker thread: %s\n",
3421                                          strerror(errno));
3422 #endif
3423
3424         return child;
3425 }
3426
3427 /*
3428  *      collect status from a completed worker child
3429  */
3430 static thandle
3431 reap_child(ParallelSlot *slots, int n_slots, int *work_status)
3432 {
3433 #ifndef WIN32
3434         /* Unix is so much easier ... */
3435         return wait(work_status);
3436 #else
3437         static HANDLE *handles = NULL;
3438         int                     hindex,
3439                                 snum,
3440                                 tnum;
3441         thandle         ret_child;
3442         DWORD           res;
3443
3444         /* first time around only, make space for handles to listen on */
3445         if (handles == NULL)
3446                 handles = (HANDLE *) calloc(sizeof(HANDLE), n_slots);
3447
3448         /* set up list of handles to listen to */
3449         for (snum = 0, tnum = 0; snum < n_slots; snum++)
3450                 if (slots[snum].child_id != 0)
3451                         handles[tnum++] = slots[snum].child_id;
3452
3453         /* wait for one to finish */
3454         hindex = WaitForMultipleObjects(tnum, handles, false, INFINITE);
3455
3456         /* get handle of finished thread */
3457         ret_child = handles[hindex - WAIT_OBJECT_0];
3458
3459         /* get the result */
3460         GetExitCodeThread(ret_child, &res);
3461         *work_status = res;
3462
3463         /* dispose of handle to stop leaks */
3464         CloseHandle(ret_child);
3465
3466         return ret_child;
3467 #endif
3468 }
3469
3470 /*
3471  * are we doing anything now?
3472  */
3473 static bool
3474 work_in_progress(ParallelSlot *slots, int n_slots)
3475 {
3476         int                     i;
3477
3478         for (i = 0; i < n_slots; i++)
3479         {
3480                 if (slots[i].child_id != 0)
3481                         return true;
3482         }
3483         return false;
3484 }
3485
3486 /*
3487  * find the first free parallel slot (if any).
3488  */
3489 static int
3490 get_next_slot(ParallelSlot *slots, int n_slots)
3491 {
3492         int                     i;
3493
3494         for (i = 0; i < n_slots; i++)
3495         {
3496                 if (slots[i].child_id == 0)
3497                         return i;
3498         }
3499         return NO_SLOT;
3500 }
3501
3502
3503 /*
3504  * Check if te1 has an exclusive lock requirement for an item that te2 also
3505  * requires, whether or not te2's requirement is for an exclusive lock.
3506  */
3507 static bool
3508 has_lock_conflicts(TocEntry *te1, TocEntry *te2)
3509 {
3510         int                     j,
3511                                 k;
3512
3513         for (j = 0; j < te1->nLockDeps; j++)
3514         {
3515                 for (k = 0; k < te2->nDeps; k++)
3516                 {
3517                         if (te1->lockDeps[j] == te2->dependencies[k])
3518                                 return true;
3519                 }
3520         }
3521         return false;
3522 }
3523
3524
3525 /*
3526  * Initialize the header of a parallel-processing list.
3527  *
3528  * These are circular lists with a dummy TocEntry as header, just like the
3529  * main TOC list; but we use separate list links so that an entry can be in
3530  * the main TOC list as well as in a parallel-processing list.
3531  */
3532 static void
3533 par_list_header_init(TocEntry *l)
3534 {
3535         l->par_prev = l->par_next = l;
3536 }
3537
3538 /* Append te to the end of the parallel-processing list headed by l */
3539 static void
3540 par_list_append(TocEntry *l, TocEntry *te)
3541 {
3542         te->par_prev = l->par_prev;
3543         l->par_prev->par_next = te;
3544         l->par_prev = te;
3545         te->par_next = l;
3546 }
3547
3548 /* Remove te from whatever parallel-processing list it's in */
3549 static void
3550 par_list_remove(TocEntry *te)
3551 {
3552         te->par_prev->par_next = te->par_next;
3553         te->par_next->par_prev = te->par_prev;
3554         te->par_prev = NULL;
3555         te->par_next = NULL;
3556 }
3557
3558
3559 /*
3560  * Find the next work item (if any) that is capable of being run now.
3561  *
3562  * To qualify, the item must have no remaining dependencies
3563  * and no requirements for locks that are incompatible with
3564  * items currently running.  Items in the ready_list are known to have
3565  * no remaining dependencies, but we have to check for lock conflicts.
3566  *
3567  * Note that the returned item has *not* been removed from ready_list.
3568  * The caller must do that after successfully dispatching the item.
3569  *
3570  * pref_non_data is for an alternative selection algorithm that gives
3571  * preference to non-data items if there is already a data load running.
3572  * It is currently disabled.
3573  */
3574 static TocEntry *
3575 get_next_work_item(ArchiveHandle *AH, TocEntry *ready_list,
3576                                    ParallelSlot *slots, int n_slots)
3577 {
3578         bool            pref_non_data = false;  /* or get from AH->ropt */
3579         TocEntry   *data_te = NULL;
3580         TocEntry   *te;
3581         int                     i,
3582                                 k;
3583
3584         /*
3585          * Bogus heuristics for pref_non_data
3586          */
3587         if (pref_non_data)
3588         {
3589                 int                     count = 0;
3590
3591                 for (k = 0; k < n_slots; k++)
3592                         if (slots[k].args->te != NULL &&
3593                                 slots[k].args->te->section == SECTION_DATA)
3594                                 count++;
3595                 if (n_slots == 0 || count * 4 < n_slots)
3596                         pref_non_data = false;
3597         }
3598
3599         /*
3600          * Search the ready_list until we find a suitable item.
3601          */
3602         for (te = ready_list->par_next; te != ready_list; te = te->par_next)
3603         {
3604                 bool            conflicts = false;
3605
3606                 /*
3607                  * Check to see if the item would need exclusive lock on something
3608                  * that a currently running item also needs lock on, or vice versa. If
3609                  * so, we don't want to schedule them together.
3610                  */
3611                 for (i = 0; i < n_slots && !conflicts; i++)
3612                 {
3613                         TocEntry   *running_te;
3614
3615                         if (slots[i].args == NULL)
3616                                 continue;
3617                         running_te = slots[i].args->te;
3618
3619                         if (has_lock_conflicts(te, running_te) ||
3620                                 has_lock_conflicts(running_te, te))
3621                         {
3622                                 conflicts = true;
3623                                 break;
3624                         }
3625                 }
3626
3627                 if (conflicts)
3628                         continue;
3629
3630                 if (pref_non_data && te->section == SECTION_DATA)
3631                 {
3632                         if (data_te == NULL)
3633                                 data_te = te;
3634                         continue;
3635                 }
3636
3637                 /* passed all tests, so this item can run */
3638                 return te;
3639         }
3640
3641         if (data_te != NULL)
3642                 return data_te;
3643
3644         ahlog(AH, 2, "no item ready\n");
3645         return NULL;
3646 }
3647
3648
3649 /*
3650  * Restore a single TOC item in parallel with others
3651  *
3652  * this is the procedure run as a thread (Windows) or a
3653  * separate process (everything else).
3654  */
3655 static parallel_restore_result
3656 parallel_restore(RestoreArgs *args)
3657 {
3658         ArchiveHandle *AH = args->AH;
3659         TocEntry   *te = args->te;
3660         RestoreOptions *ropt = AH->ropt;
3661         int                     retval;
3662
3663         /*
3664          * Close and reopen the input file so we have a private file pointer that
3665          * doesn't stomp on anyone else's file pointer, if we're actually going to
3666          * need to read from the file. Otherwise, just close it except on Windows,
3667          * where it will possibly be needed by other threads.
3668          *
3669          * Note: on Windows, since we are using threads not processes, the reopen
3670          * call *doesn't* close the original file pointer but just open a new one.
3671          */
3672         if (te->section == SECTION_DATA)
3673                 (AH->ReopenPtr) (AH);
3674 #ifndef WIN32
3675         else
3676                 (AH->ClosePtr) (AH);
3677 #endif
3678
3679         /*
3680          * We need our own database connection, too
3681          */
3682         ConnectDatabase((Archive *) AH, ropt->dbname,
3683                                         ropt->pghost, ropt->pgport, ropt->username,
3684                                         ropt->promptPassword);
3685
3686         _doSetFixedOutputState(AH);
3687
3688         /* Restore the TOC item */
3689         retval = restore_toc_entry(AH, te, ropt, true);
3690
3691         /* And clean up */
3692         PQfinish(AH->connection);
3693         AH->connection = NULL;
3694
3695         /* If we reopened the file, we are done with it, so close it now */
3696         if (te->section == SECTION_DATA)
3697                 (AH->ClosePtr) (AH);
3698
3699         if (retval == 0 && AH->public.n_errors)
3700                 retval = WORKER_IGNORED_ERRORS;
3701
3702 #ifndef WIN32
3703         exit(retval);
3704 #else
3705         return retval;
3706 #endif
3707 }
3708
3709
3710 /*
3711  * Housekeeping to be done after a step has been parallel restored.
3712  *
3713  * Clear the appropriate slot, free all the extra memory we allocated,
3714  * update status, and reduce the dependency count of any dependent items.
3715  */
3716 static void
3717 mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
3718                            thandle worker, int status,
3719                            ParallelSlot *slots, int n_slots)
3720 {
3721         TocEntry   *te = NULL;
3722         int                     i;
3723
3724         for (i = 0; i < n_slots; i++)
3725         {
3726                 if (slots[i].child_id == worker)
3727                 {
3728                         slots[i].child_id = 0;
3729                         te = slots[i].args->te;
3730                         DeCloneArchive(slots[i].args->AH);
3731                         free(slots[i].args);
3732                         slots[i].args = NULL;
3733
3734                         break;
3735                 }
3736         }
3737
3738         if (te == NULL)
3739                 die_horribly(AH, modulename, "could not find slot of finished worker\n");
3740
3741         ahlog(AH, 1, "finished item %d %s %s\n",
3742                   te->dumpId, te->desc, te->tag);
3743
3744         if (status == WORKER_CREATE_DONE)
3745                 mark_create_done(AH, te);
3746         else if (status == WORKER_INHIBIT_DATA)
3747         {
3748                 inhibit_data_for_failed_table(AH, te);
3749                 AH->public.n_errors++;
3750         }
3751         else if (status == WORKER_IGNORED_ERRORS)
3752                 AH->public.n_errors++;
3753         else if (status != 0)
3754                 die_horribly(AH, modulename, "worker process failed: exit code %d\n",
3755                                          status);
3756
3757         reduce_dependencies(AH, te, ready_list);
3758 }
3759
3760
3761 /*
3762  * Process the dependency information into a form useful for parallel restore.
3763  *
3764  * This function takes care of fixing up some missing or badly designed
3765  * dependencies, and then prepares subsidiary data structures that will be
3766  * used in the main parallel-restore logic, including:
3767  * 1. We build the tocsByDumpId[] index array.
3768  * 2. We build the revDeps[] arrays of incoming dependency dumpIds.
3769  * 3. We set up depCount fields that are the number of as-yet-unprocessed
3770  * dependencies for each TOC entry.
3771  *
3772  * We also identify locking dependencies so that we can avoid trying to
3773  * schedule conflicting items at the same time.
3774  */
3775 static void
3776 fix_dependencies(ArchiveHandle *AH)
3777 {
3778         TocEntry   *te;
3779         int                     i;
3780
3781         /*
3782          * It is convenient to have an array that indexes the TOC entries by dump
3783          * ID, rather than searching the TOC list repeatedly.  Entries for dump
3784          * IDs not present in the TOC will be NULL.
3785          *
3786          * NOTE: because maxDumpId is just the highest dump ID defined in the
3787          * archive, there might be dependencies for IDs > maxDumpId.  All uses of
3788          * this array must guard against out-of-range dependency numbers.
3789          *
3790          * Also, initialize the depCount/revDeps/nRevDeps fields, and make sure
3791          * the TOC items are marked as not being in any parallel-processing list.
3792          */
3793         maxDumpId = AH->maxDumpId;
3794         tocsByDumpId = (TocEntry **) calloc(maxDumpId, sizeof(TocEntry *));
3795         for (te = AH->toc->next; te != AH->toc; te = te->next)
3796         {
3797                 tocsByDumpId[te->dumpId - 1] = te;
3798                 te->depCount = te->nDeps;
3799                 te->revDeps = NULL;
3800                 te->nRevDeps = 0;
3801                 te->par_prev = NULL;
3802                 te->par_next = NULL;
3803         }
3804
3805         /*
3806          * POST_DATA items that are shown as depending on a table need to be
3807          * re-pointed to depend on that table's data, instead.  This ensures they
3808          * won't get scheduled until the data has been loaded.  We handle this by
3809          * first finding TABLE/TABLE DATA pairs and then scanning all the
3810          * dependencies.
3811          *
3812          * Note: currently, a TABLE DATA should always have exactly one
3813          * dependency, on its TABLE item.  So we don't bother to search, but look
3814          * just at the first dependency.  We do trouble to make sure that it's a
3815          * TABLE, if possible.  However, if the dependency isn't in the archive
3816          * then just assume it was a TABLE; this is to cover cases where the table
3817          * was suppressed but we have the data and some dependent post-data items.
3818          *
3819          * XXX this is O(N^2) if there are a lot of tables.  We ought to fix
3820          * pg_dump to produce correctly-linked dependencies in the first place.
3821          */
3822         for (te = AH->toc->next; te != AH->toc; te = te->next)
3823         {
3824                 if (strcmp(te->desc, "TABLE DATA") == 0 && te->nDeps > 0)
3825                 {
3826                         DumpId          tableId = te->dependencies[0];
3827
3828                         if (tableId > maxDumpId ||
3829                                 tocsByDumpId[tableId - 1] == NULL ||
3830                                 strcmp(tocsByDumpId[tableId - 1]->desc, "TABLE") == 0)
3831                         {
3832                                 repoint_table_dependencies(AH, tableId, te->dumpId);
3833                         }
3834                 }
3835         }
3836
3837         /*
3838          * Pre-8.4 versions of pg_dump neglected to set up a dependency from BLOB
3839          * COMMENTS to BLOBS.  Cope.  (We assume there's only one BLOBS and only
3840          * one BLOB COMMENTS in such files.)
3841          */
3842         if (AH->version < K_VERS_1_11)
3843         {
3844                 for (te = AH->toc->next; te != AH->toc; te = te->next)
3845                 {
3846                         if (strcmp(te->desc, "BLOB COMMENTS") == 0 && te->nDeps == 0)
3847                         {
3848                                 TocEntry   *te2;
3849
3850                                 for (te2 = AH->toc->next; te2 != AH->toc; te2 = te2->next)
3851                                 {
3852                                         if (strcmp(te2->desc, "BLOBS") == 0)
3853                                         {
3854                                                 te->dependencies = (DumpId *) malloc(sizeof(DumpId));
3855                                                 te->dependencies[0] = te2->dumpId;
3856                                                 te->nDeps++;
3857                                                 te->depCount++;
3858                                                 break;
3859                                         }
3860                                 }
3861                                 break;
3862                         }
3863                 }
3864         }
3865
3866         /*
3867          * At this point we start to build the revDeps reverse-dependency arrays,
3868          * so all changes of dependencies must be complete.
3869          */
3870
3871         /*
3872          * Count the incoming dependencies for each item.  Also, it is possible
3873          * that the dependencies list items that are not in the archive at
3874          * all.  Subtract such items from the depCounts.
3875          */
3876         for (te = AH->toc->next; te != AH->toc; te = te->next)
3877         {
3878                 for (i = 0; i < te->nDeps; i++)
3879                 {
3880                         DumpId          depid = te->dependencies[i];
3881
3882                         if (depid <= maxDumpId && tocsByDumpId[depid - 1] != NULL)
3883                                 tocsByDumpId[depid - 1]->nRevDeps++;
3884                         else
3885                                 te->depCount--;
3886                 }
3887         }
3888
3889         /*
3890          * Allocate space for revDeps[] arrays, and reset nRevDeps so we can
3891          * use it as a counter below.
3892          */
3893         for (te = AH->toc->next; te != AH->toc; te = te->next)
3894         {
3895                 if (te->nRevDeps > 0)
3896                         te->revDeps = (DumpId *) malloc(te->nRevDeps * sizeof(DumpId));
3897                 te->nRevDeps = 0;
3898         }
3899
3900         /*
3901          * Build the revDeps[] arrays of incoming-dependency dumpIds.  This
3902          * had better agree with the loops above.
3903          */
3904         for (te = AH->toc->next; te != AH->toc; te = te->next)
3905         {
3906                 for (i = 0; i < te->nDeps; i++)
3907                 {
3908                         DumpId          depid = te->dependencies[i];
3909
3910                         if (depid <= maxDumpId && tocsByDumpId[depid - 1] != NULL)
3911                         {
3912                                 TocEntry   *otherte = tocsByDumpId[depid - 1];
3913
3914                                 otherte->revDeps[otherte->nRevDeps++] = te->dumpId;
3915                         }
3916                 }
3917         }
3918
3919         /*
3920          * Lastly, work out the locking dependencies.
3921          */
3922         for (te = AH->toc->next; te != AH->toc; te = te->next)
3923         {
3924                 te->lockDeps = NULL;
3925                 te->nLockDeps = 0;
3926                 identify_locking_dependencies(te);
3927         }
3928 }
3929
3930 /*
3931  * Change dependencies on tableId to depend on tableDataId instead,
3932  * but only in POST_DATA items.
3933  */
3934 static void
3935 repoint_table_dependencies(ArchiveHandle *AH,
3936                                                    DumpId tableId, DumpId tableDataId)
3937 {
3938         TocEntry   *te;
3939         int                     i;
3940
3941         for (te = AH->toc->next; te != AH->toc; te = te->next)
3942         {
3943                 if (te->section != SECTION_POST_DATA)
3944                         continue;
3945                 for (i = 0; i < te->nDeps; i++)
3946                 {
3947                         if (te->dependencies[i] == tableId)
3948                         {
3949                                 te->dependencies[i] = tableDataId;
3950                                 ahlog(AH, 2, "transferring dependency %d -> %d to %d\n",
3951                                           te->dumpId, tableId, tableDataId);
3952                         }
3953                 }
3954         }
3955 }
3956
3957 /*
3958  * Identify which objects we'll need exclusive lock on in order to restore
3959  * the given TOC entry (*other* than the one identified by the TOC entry
3960  * itself).  Record their dump IDs in the entry's lockDeps[] array.
3961  */
3962 static void
3963 identify_locking_dependencies(TocEntry *te)
3964 {
3965         DumpId     *lockids;
3966         int                     nlockids;
3967         int                     i;
3968
3969         /* Quick exit if no dependencies at all */
3970         if (te->nDeps == 0)
3971                 return;
3972
3973         /* Exit if this entry doesn't need exclusive lock on other objects */
3974         if (!(strcmp(te->desc, "CONSTRAINT") == 0 ||
3975                   strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
3976                   strcmp(te->desc, "FK CONSTRAINT") == 0 ||
3977                   strcmp(te->desc, "RULE") == 0 ||
3978                   strcmp(te->desc, "TRIGGER") == 0))
3979                 return;
3980
3981         /*
3982          * We assume the item requires exclusive lock on each TABLE DATA item
3983          * listed among its dependencies.  (This was originally a dependency on
3984          * the TABLE, but fix_dependencies repointed it to the data item. Note
3985          * that all the entry types we are interested in here are POST_DATA, so
3986          * they will all have been changed this way.)
3987          */
3988         lockids = (DumpId *) malloc(te->nDeps * sizeof(DumpId));
3989         nlockids = 0;
3990         for (i = 0; i < te->nDeps; i++)
3991         {
3992                 DumpId          depid = te->dependencies[i];
3993
3994                 if (depid <= maxDumpId && tocsByDumpId[depid - 1] &&
3995                         strcmp(tocsByDumpId[depid - 1]->desc, "TABLE DATA") == 0)
3996                         lockids[nlockids++] = depid;
3997         }
3998
3999         if (nlockids == 0)
4000         {
4001                 free(lockids);
4002                 return;
4003         }
4004
4005         te->lockDeps = realloc(lockids, nlockids * sizeof(DumpId));
4006         te->nLockDeps = nlockids;
4007 }
4008
4009 /*
4010  * Remove the specified TOC entry from the depCounts of items that depend on
4011  * it, thereby possibly making them ready-to-run.  Any pending item that
4012  * becomes ready should be moved to the ready list.
4013  */
4014 static void
4015 reduce_dependencies(ArchiveHandle *AH, TocEntry *te, TocEntry *ready_list)
4016 {
4017         int                     i;
4018
4019         ahlog(AH, 2, "reducing dependencies for %d\n", te->dumpId);
4020
4021         for (i = 0; i < te->nRevDeps; i++)
4022         {
4023                 TocEntry   *otherte = tocsByDumpId[te->revDeps[i] - 1];
4024
4025                 otherte->depCount--;
4026                 if (otherte->depCount == 0 && otherte->par_prev != NULL)
4027                 {
4028                         /* It must be in the pending list, so remove it ... */
4029                         par_list_remove(otherte);
4030                         /* ... and add to ready_list */
4031                         par_list_append(ready_list, otherte);
4032                 }
4033         }
4034 }
4035
4036 /*
4037  * Set the created flag on the DATA member corresponding to the given
4038  * TABLE member
4039  */
4040 static void
4041 mark_create_done(ArchiveHandle *AH, TocEntry *te)
4042 {
4043         TocEntry   *tes;
4044
4045         for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
4046         {
4047                 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
4048                         strcmp(tes->tag, te->tag) == 0 &&
4049                         strcmp(tes->namespace ? tes->namespace : "",
4050                                    te->namespace ? te->namespace : "") == 0)
4051                 {
4052                         tes->created = true;
4053                         break;
4054                 }
4055         }
4056 }
4057
4058 /*
4059  * Mark the DATA member corresponding to the given TABLE member
4060  * as not wanted
4061  */
4062 static void
4063 inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
4064 {
4065         RestoreOptions *ropt = AH->ropt;
4066         TocEntry   *tes;
4067
4068         ahlog(AH, 1, "table \"%s\" could not be created, will not restore its data\n",
4069                   te->tag);
4070
4071         for (tes = AH->toc->next; tes != AH->toc; tes = tes->next)
4072         {
4073                 if (strcmp(tes->desc, "TABLE DATA") == 0 &&
4074                         strcmp(tes->tag, te->tag) == 0 &&
4075                         strcmp(tes->namespace ? tes->namespace : "",
4076                                    te->namespace ? te->namespace : "") == 0)
4077                 {
4078                         /* mark it unwanted; we assume idWanted array already exists */
4079                         ropt->idWanted[tes->dumpId - 1] = false;
4080                         break;
4081                 }
4082         }
4083 }
4084
4085
4086 /*
4087  * Clone and de-clone routines used in parallel restoration.
4088  *
4089  * Enough of the structure is cloned to ensure that there is no
4090  * conflict between different threads each with their own clone.
4091  *
4092  * These could be public, but no need at present.
4093  */
4094 static ArchiveHandle *
4095 CloneArchive(ArchiveHandle *AH)
4096 {
4097         ArchiveHandle *clone;
4098
4099         /* Make a "flat" copy */
4100         clone = (ArchiveHandle *) malloc(sizeof(ArchiveHandle));
4101         if (clone == NULL)
4102                 die_horribly(AH, modulename, "out of memory\n");
4103         memcpy(clone, AH, sizeof(ArchiveHandle));
4104
4105         /* Handle format-independent fields */
4106         clone->pgCopyBuf = createPQExpBuffer();
4107         clone->sqlBuf = createPQExpBuffer();
4108         clone->sqlparse.tagBuf = NULL;
4109
4110         /* The clone will have its own connection, so disregard connection state */
4111         clone->connection = NULL;
4112         clone->currUser = NULL;
4113         clone->currSchema = NULL;
4114         clone->currTablespace = NULL;
4115         clone->currWithOids = -1;
4116
4117         /* savedPassword must be local in case we change it while connecting */
4118         if (clone->savedPassword)
4119                 clone->savedPassword = strdup(clone->savedPassword);
4120
4121         /* clone has its own error count, too */
4122         clone->public.n_errors = 0;
4123
4124         /* Let the format-specific code have a chance too */
4125         (clone->ClonePtr) (clone);
4126
4127         return clone;
4128 }
4129
4130 /*
4131  * Release clone-local storage.
4132  *
4133  * Note: we assume any clone-local connection was already closed.
4134  */
4135 static void
4136 DeCloneArchive(ArchiveHandle *AH)
4137 {
4138         /* Clear format-specific state */
4139         (AH->DeClonePtr) (AH);
4140
4141         /* Clear state allocated by CloneArchive */
4142         destroyPQExpBuffer(AH->pgCopyBuf);
4143         destroyPQExpBuffer(AH->sqlBuf);
4144         if (AH->sqlparse.tagBuf)
4145                 destroyPQExpBuffer(AH->sqlparse.tagBuf);
4146
4147         /* Clear any connection-local state */
4148         if (AH->currUser)
4149                 free(AH->currUser);
4150         if (AH->currSchema)
4151                 free(AH->currSchema);
4152         if (AH->currTablespace)
4153                 free(AH->currTablespace);
4154         if (AH->savedPassword)
4155                 free(AH->savedPassword);
4156
4157         free(AH);
4158 }