pg_backup_archiver.c 43.7 KB
Newer Older
B
Bruce Momjian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*-------------------------------------------------------------------------
 *
 * pg_backup_archiver.c
 *
 *	Private implementation of the archiver routines.
 *
 *	See the headers to pg_restore for more details.
 *
 * Copyright (c) 2000, Philip Warner
 *	Rights are granted to use this software in any way so long
 * 	as this notice is not removed.
 *
 *	The author is not responsible for loss or damages that may
 *	result from it's use.
 *
 *
 * IDENTIFICATION
 *
 * Modifications - 28-Jun-2000 - pjw@rhyme.com.au
 *
21 22 23 24
 *		Initial version. 
 *
 * Modifications - 31-Jul-2000 - pjw@rhyme.com.au (1.46, 1.47)
 *		Fixed version number initialization in _allocAH (pg_backup_archiver.c)
B
Bruce Momjian 已提交
25
 *
26 27 28 29
 *
 * Modifications - 30-Oct-2000 - pjw@rhyme.com.au
 *		Added {Start,End}RestoreBlobs to allow extended TX during BLOB restore.
 *
30 31 32 33 34 35 36
 * Modifications - 04-Jan-2001 - pjw@rhyme.com.au
 *	  -	strdup() the current user just in case it's deallocated from it's TOC
 *      entry. Should *never* happen, but that's what they said about the 
 *      Titanic...
 *
 *	  - Check results of IO routines more carefully.
 *
37 38 39
 * Modifications - 27-Jan-2001 - pjw@rhyme.com.au
 *	  - When dropping the schema, reconnect as owner of each object.
 *
B
Bruce Momjian 已提交
40 41 42 43 44
 *-------------------------------------------------------------------------
 */

#include "pg_backup.h"
#include "pg_backup_archiver.h"
45 46
#include "pg_backup_db.h"

B
Bruce Momjian 已提交
47 48 49 50 51 52 53
#include <string.h>
#include <unistd.h> /* for dup */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

54 55 56
#include "pqexpbuffer.h"
#include "libpq/libpq-fs.h"

B
Bruce Momjian 已提交
57 58 59
static void		_SortToc(ArchiveHandle* AH, TocSortCompareFn fn);
static int		_tocSortCompareByOIDNum(const void *p1, const void *p2);
static int		_tocSortCompareByIDNum(const void *p1, const void *p2);
60
static ArchiveHandle* 	_allocAH(const char* FileSpec, const ArchiveFormat fmt, 
61
				const int compression, ArchiveMode mode);
B
Bruce Momjian 已提交
62
static int 		_printTocEntry(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt);
63 64 65

static void		_reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* te);
static void		_reconnectAsUser(ArchiveHandle* AH, const char *dbname, char *user);
66

B
Bruce Momjian 已提交
67 68 69 70 71 72 73
static int		_tocEntryRequired(TocEntry* te, RestoreOptions *ropt);
static void		_disableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static void		_enableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static TocEntry*	_getTocEntry(ArchiveHandle* AH, int id);
static void		_moveAfter(ArchiveHandle* AH, TocEntry* pos, TocEntry* te);
static void		_moveBefore(ArchiveHandle* AH, TocEntry* pos, TocEntry* te);
static int		_discoverArchiveFormat(ArchiveHandle* AH);
74

B
Bruce Momjian 已提交
75 76
static char	*progname = "Archiver";

77 78 79
static void		_die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap);

static int 		_canRestoreBlobs(ArchiveHandle *AH);
80
static int 		_restoringToDB(ArchiveHandle *AH);
81

B
Bruce Momjian 已提交
82 83 84 85 86 87 88 89 90 91 92
/*
 *  Wrapper functions.
 * 
 *  The objective it to make writing new formats and dumpers as simple
 *  as possible, if necessary at the expense of extra function calls etc.
 *
 */


/* Create a new archive */
/* Public */
93 94 95
Archive* CreateArchive(const char* FileSpec, const ArchiveFormat fmt,
                                const int compression)

B
Bruce Momjian 已提交
96 97 98 99 100 101 102
{
    ArchiveHandle*	AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
    return (Archive*)AH;
}

/* Open an existing archive */
/* Public */
103
Archive* OpenArchive(const char* FileSpec, const ArchiveFormat fmt) 
B
Bruce Momjian 已提交
104 105 106 107 108 109 110 111
{
    ArchiveHandle*      AH = _allocAH(FileSpec, fmt, 0, archModeRead);
    return (Archive*)AH;
}

/* Public */
void	CloseArchive(Archive* AHX)
{
112
	int					res = 0;
B
Bruce Momjian 已提交
113 114 115 116 117
    ArchiveHandle*      AH = (ArchiveHandle*)AHX;
    (*AH->ClosePtr)(AH);

    /* Close the output */
    if (AH->gzOut)
118
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
119
    else if (AH->OF != stdout)
120 121 122 123
		res = fclose(AH->OF);

	if (res != 0)
		die_horribly(AH, "%s: could not close the output file in CloseArchive\n", progname);
B
Bruce Momjian 已提交
124 125 126 127 128 129 130 131 132 133
}

/* Public */
void RestoreArchive(Archive* AHX, RestoreOptions *ropt)
{
    ArchiveHandle*	AH = (ArchiveHandle*) AHX;
    TocEntry		*te = AH->toc->next;
    int			reqs;
    OutputContext	sav;

134 135
	AH->ropt = ropt;

136 137 138
	if (ropt->create && ropt->noReconnect)
		die_horribly(AH, "%s: --create and --no-reconnect are incompatible options\n",progname);

139 140 141 142 143 144 145 146 147
	/*
	 * If we're using a DB connection, then connect it.
	 */
	if (ropt->useDB)
	{
		ahlog(AH, 1, "Connecting to database for restore\n");
		if (AH->version < K_VERS_1_3)
			die_horribly(AH, "Direct database connections are not supported in pre-1.3 archives");

148 149
		ConnectDatabase(AHX, ropt->dbname, ropt->pghost, ropt->pgport, 
							ropt->requirePassword, ropt->ignoreVersion);
150 151 152 153 154 155 156 157 158 159

		/*
		 * If no superuser was specified then see if the current user will do...
		 */
		if (!ropt->superuser)
		{
			if (UserIsSuperuser(AH, ConnectedUser(AH)))
				ropt->superuser = strdup(ConnectedUser(AH));
		}

160 161
	}

162 163 164 165 166 167 168
	if (!ropt->superuser)
		fprintf(stderr, "\n%s: ******** WARNING ******** \n"
							"        Data restoration may fail since any defined triggers\n"
							"        can not be disabled (no superuser username specified).\n"
							"        This is only a problem for restoration into a database\n"
							"        with triggers already defined.\n\n", progname);

169 170 171
	/*
	 *	Setup the output file if necessary.
	 */
B
Bruce Momjian 已提交
172
    if (ropt->filename || ropt->compression)
173
		sav = SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
174 175 176

    ahprintf(AH, "--\n-- Selected TOC Entries:\n--\n");

177 178 179
    /*
     * Drop the items at the start, in reverse order 
	 */
B
Bruce Momjian 已提交
180
    if (ropt->dropSchema) {
181 182 183 184 185
		te = AH->toc->prev;
		while (te != AH->toc) {
			reqs = _tocEntryRequired(te, ropt);
			if ( ( (reqs & 1) != 0) && te->dropStmt) {  /* We want the schema */
				ahlog(AH, 1, "Dropping %s %s\n", te->desc, te->name);
186 187 188
				/* Reconnect if necessary */
				_reconnectAsOwner(AH, "-", te);
				/* Drop it */
189 190 191 192
				ahprintf(AH, "%s", te->dropStmt);
			}
			te = te->prev;
		}
B
Bruce Momjian 已提交
193 194
    }

195 196 197
	/*
	 * Now process each TOC entry
	 */
B
Bruce Momjian 已提交
198 199 200
    te = AH->toc->next;
    while (te != AH->toc) {

201 202 203 204 205
		/* Work out what, if anything, we want from this entry */
		reqs = _tocEntryRequired(te, ropt);

		if ( (reqs & 1) != 0) /* We want the schema */
		{
206 207 208
			/* Reconnect if necessary */
			_reconnectAsOwner(AH, "-", te);

209 210
			ahlog(AH, 1, "Creating %s %s\n", te->desc, te->name);
			_printTocEntry(AH, te, ropt);
211 212 213 214 215 216 217

			/* If we created a DB, connect to it... */
			if (strcmp(te->desc,"DATABASE") == 0)
			{
				ahlog(AH, 1, "Connecting to new DB '%s' as %s\n",te->name, te->owner);
				_reconnectAsUser(AH, te->name, te->owner);
			}
218
		}
B
Bruce Momjian 已提交
219

220 221 222 223
		/* 
		 * If we want data, and it has data, then restore that too 
		 */
		if (AH->PrintTocDataPtr != NULL && (reqs & 2) != 0) {
224
#ifndef HAVE_LIBZ
225 226
			if (AH->compression != 0)
				die_horribly(AH, "%s: Unable to restore data from a compressed archive\n", progname);
B
Bruce Momjian 已提交
227
#endif
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

			ahprintf(AH, "--\n-- Data for TOC Entry ID %d (OID %s) %s %s\n--\n\n",
						te->id, te->oid, te->desc, te->name);

			/*
			 * Maybe we can't do BLOBS, so check if this node is for BLOBS 
			 */
			if ((strcmp(te->desc,"BLOBS") == 0) && !_canRestoreBlobs(AH))
			{
				ahprintf(AH, "--\n-- SKIPPED \n--\n\n");
				/*
				 * This is a bit nasty - we assume, for the moment, that if a custom
				 * output is used, then we don't want warnings.
				 */
				if (!AH->CustomOutPtr)
					fprintf(stderr, "%s: WARNING - skipping BLOB restoration\n", progname);
244

245 246 247 248
			} else {

				_disableTriggers(AH, te, ropt);

249 250 251 252
				/* Reconnect if necessary (_disableTriggers may have reconnected) */
				_reconnectAsOwner(AH, "-", te);

				ahlog(AH, 1, "Restoring data for %s \n", te->name);
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

				/* If we have a copy statement, use it. As of V1.3, these are separate 
				 * to allow easy import from withing a database connection. Pre 1.3 
				 * archives can not use DB connections and are sent to output only.
				 *
				 * For V1.3+, the table data MUST have a copy statement so that 
				 * we can go into appropriate mode with libpq.
				 */
				if (te->copyStmt && strlen(te->copyStmt) > 0)
					ahprintf(AH, te->copyStmt);

				(*AH->PrintTocDataPtr)(AH, te, ropt);

				_enableTriggers(AH, te, ropt);
			}
		}
		te = te->next;
B
Bruce Momjian 已提交
270 271
    }

272 273 274 275 276
	/*
	 * Now use blobs_xref (if used) to fixup any refs for tables that we loaded
	 */
	if (_canRestoreBlobs(AH) && AH->createdBlobXref)
	{
277 278 279
		/* NULL parameter means disable ALL user triggers */
		_disableTriggers(AH, NULL, ropt);

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		te = AH->toc->next;
		while (te != AH->toc) {

			/* Is it table data? */
			if (strcmp(te->desc, "TABLE DATA") == 0) {

				ahlog(AH, 2, "Checking if we loaded %s\n", te->name);

				reqs = _tocEntryRequired(te, ropt);

				if ( (reqs & 2) != 0) /* We loaded the data */
				{
					ahlog(AH, 1, "Fixing up BLOB ref for %s\n", te->name);
					FixupBlobRefs(AH, te->name);
				}
			}
			else
			{
				ahlog(AH, 2, "Ignoring BLOB xrefs for %s %s\n", te->desc, te->name);
			}

			te = te->next;
		}
303 304 305

		/* NULL parameter means enable ALL user triggers */
		_enableTriggers(AH, NULL, ropt);
306 307 308 309 310
	}

	/*
	 * Clean up & we're done.
	 */
B
Bruce Momjian 已提交
311
    if (ropt->filename)
312
		ResetOutput(AH, sav);
B
Bruce Momjian 已提交
313

314 315 316 317
	if (ropt->useDB)
	{
		PQfinish(AH->connection);
		AH->connection = NULL;
318 319 320 321 322 323

		if (AH->blobConnection)
		{
			PQfinish(AH->blobConnection);
			AH->blobConnection = NULL;
		}
324
	}
B
Bruce Momjian 已提交
325 326
}

327 328 329 330
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
331 332 333 334 335 336 337 338 339 340 341
RestoreOptions*		NewRestoreOptions(void)
{
	RestoreOptions* opts;

	opts = (RestoreOptions*)calloc(1, sizeof(RestoreOptions));

	opts->format = archUnknown;

	return opts;
}

342
static int _restoringToDB(ArchiveHandle *AH)
343 344 345 346
{
	return (AH->ropt->useDB && AH->connection);
}

347 348 349 350 351
static int _canRestoreBlobs(ArchiveHandle *AH)
{
	return _restoringToDB(AH);
}

B
Bruce Momjian 已提交
352 353
static void _disableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
{
354 355 356 357 358 359 360 361 362 363 364 365
	char	*oldUser = NULL;

	/* Can't do much if we're connected & don't have a superuser */
	if (_restoringToDB(AH) && !ropt->superuser)
		return;

	/*
     * Reconnect as superuser if possible, since they are the only ones
	 * who can update pg_class...
	 */
	if (ropt->superuser)
	{
366 367 368 369 370 371 372 373 374 375
		if (!_restoringToDB(AH) || !ConnectedUserIsSuperuser(AH))
		{
			/* If we're not allowing changes for ownership, then remember the user
			 * so we can change it back here. Otherwise, let _reconnectAsOwner
			 * do what it has to do.
			 */
			if (ropt->noOwner)
				oldUser = strdup(ConnectedUser(AH));
			_reconnectAsUser(AH, "-", ropt->superuser);
		}
376 377 378 379 380 381 382 383
	}

	ahlog(AH, 1, "Disabling triggers\n");

	/*
     * Disable them. This is a hack. Needs to be done via an appropriate 'SET'
	 * command when one is available.
	 */
B
Bruce Momjian 已提交
384
    ahprintf(AH, "-- Disable triggers\n");
385 386 387 388 389 390 391 392 393 394

	/*
	 * Just update the AFFECTED table, if known.
	 */

	if (te && te->name && strlen(te->name) > 0)
		ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" ~* '%s';\n", 
						te->name);
	else
		ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" !~ '^pg_';\n\n");
395 396 397 398 399 400 401 402 403 404

	/*
	 * Restore the user connection from the start of this procedure
	 * if _reconnectAsOwner is disabled.
	 */
	if (ropt->noOwner && oldUser)
	{
		_reconnectAsUser(AH, "-", oldUser);
		free(oldUser);
	}
B
Bruce Momjian 已提交
405 406 407 408
}

static void _enableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
{
409 410 411 412 413 414 415 416 417 418 419 420
	char		*oldUser = NULL;

	/* Can't do much if we're connected & don't have a superuser */
	if (_restoringToDB(AH) && !ropt->superuser)
		return;

	/*
	 * Reconnect as superuser if possible, since they are the only ones
	 * who can update pg_class...
	 */
	if (ropt->superuser)
	{
421 422 423 424 425 426 427 428
		if (!_restoringToDB(AH) || !ConnectedUserIsSuperuser(AH))
		{
			/* If we're not allowing changes for ownership, then remember the user
			 * so we can change it back here. Otherwise, let _reconnectAsOwner
			 * do what it has to do
			 */
			if (ropt->noOwner)
				oldUser = strdup(ConnectedUser(AH));
429

430 431
			_reconnectAsUser(AH, "-", ropt->superuser);
		}
432 433 434 435 436 437 438 439
	}

	ahlog(AH, 1, "Enabling triggers\n");

	/*
	 * Enable them. This is a hack. Needs to be done via an appropriate 'SET'
	 * command when one is available.
	 */
B
Bruce Momjian 已提交
440 441 442
    ahprintf(AH, "-- Enable triggers\n");
    ahprintf(AH, "BEGIN TRANSACTION;\n");
    ahprintf(AH, "CREATE TEMP TABLE \"tr\" (\"tmp_relname\" name, \"tmp_reltriggers\" smallint);\n");
443 444 445 446 447 448 449 450 451 452 453 454 455

	/*
	 * Just update the affected table, if known.
	 */
	if (te && te->name && strlen(te->name) > 0)
		ahprintf(AH, "INSERT INTO \"tr\" SELECT C.\"relname\", count(T.\"oid\") FROM \"pg_class\" C,"
					" \"pg_trigger\" T WHERE C.\"oid\" = T.\"tgrelid\" AND C.\"relname\" ~* '%s' "
					" GROUP BY 1;\n", te->name);
	else
		ahprintf(AH, "INSERT INTO \"tr\" SELECT C.\"relname\", count(T.\"oid\") FROM \"pg_class\" C,"
					" \"pg_trigger\" T WHERE C.\"oid\" = T.\"tgrelid\" AND C.\"relname\" !~ '^pg_' "
					" GROUP BY 1;\n");

B
Bruce Momjian 已提交
456 457 458 459 460 461
    ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = TMP.\"tmp_reltriggers\" "
	    "FROM \"tr\" TMP WHERE "
	    "\"pg_class\".\"relname\" = TMP.\"tmp_relname\";\n");
    ahprintf(AH, "DROP TABLE \"tr\";\n");
    ahprintf(AH, "COMMIT TRANSACTION;\n\n");

462 463 464 465 466 467 468 469 470 471
	/*
	 * Restore the user connection from the start of this procedure
	 * if _reconnectAsOwner is disabled.
	 */
	if (ropt->noOwner && oldUser)
	{
		_reconnectAsUser(AH, "-", oldUser);
		free(oldUser);
	}
}
B
Bruce Momjian 已提交
472 473

/*
474
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
475 476 477 478 479 480 481
 */

/* Public */
int	WriteData(Archive* AHX, const void* data, int dLen)
{
    ArchiveHandle*      AH = (ArchiveHandle*)AHX;

482 483 484 485
	if (!AH->currToc)
		die_horribly(AH, "%s: WriteData can not be called outside the context of "
						"a DataDumper routine\n", progname);

B
Bruce Momjian 已提交
486 487 488 489 490 491 492 493 494 495 496
    return (*AH->WriteDataPtr)(AH, data, dLen);
}

/*
 * Create a new TOC entry. The TOC was designed as a TOC, but is now the 
 * repository for all metadata. But the name has stuck.
 */

/* Public */
void	ArchiveEntry(Archive* AHX, const char* oid, const char* name,
			const char* desc, const char* (deps[]), const char* defn,
497
			const char* dropStmt, const char* copyStmt, const char* owner,
B
Bruce Momjian 已提交
498 499 500 501 502 503 504 505
			DataDumperPtr dumpFn, void* dumpArg)
{
    ArchiveHandle*	AH = (ArchiveHandle*)AHX;
    TocEntry*		newToc;

    AH->lastID++;
    AH->tocCount++;

506
    newToc = (TocEntry*)calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
507
    if (!newToc)
508
	die_horribly(AH, "Archiver: unable to allocate memory for TOC entry\n");
B
Bruce Momjian 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521

    newToc->prev = AH->toc->prev;
    newToc->next = AH->toc;
    AH->toc->prev->next = newToc;
    AH->toc->prev = newToc;

    newToc->id = AH->lastID;
    newToc->oid = strdup(oid);
    newToc->oidVal = atoi(oid);
    newToc->name = strdup(name);
    newToc->desc = strdup(desc);
    newToc->defn = strdup(defn);
    newToc->dropStmt = strdup(dropStmt);
522
	newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
B
Bruce Momjian 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    newToc->owner = strdup(owner);
    newToc->printed = 0;
    newToc->formatData = NULL;
    newToc->dataDumper = dumpFn,
    newToc->dataDumperArg = dumpArg;

    newToc->hadDumper = dumpFn ? 1 : 0;

    if (AH->ArchiveEntryPtr != NULL) {
		(*AH->ArchiveEntryPtr)(AH, newToc);
    }

    /* printf("New toc owned by '%s', oid %d\n", newToc->owner, newToc->oidVal); */
}

/* Public */
void PrintTOCSummary(Archive* AHX, RestoreOptions *ropt)
{
    ArchiveHandle*	AH = (ArchiveHandle*) AHX;
    TocEntry		*te = AH->toc->next;
    OutputContext	sav;
544
	char			*fmtName;
B
Bruce Momjian 已提交
545 546 547 548

    if (ropt->filename)
	sav = SetOutput(AH, ropt->filename, ropt->compression);

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
	ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
	ahprintf(AH, ";     dbname: %s\n;     TOC Entries: %d\n;     Compression: %d\n",
				AH->archdbname, AH->tocCount, AH->compression);

	switch (AH->format) {
		case archFiles:
			fmtName = "FILES";
			break;
		case archCustom:
			fmtName = "CUSTOM";
			break;
		case archTar:
			fmtName = "TAR";
			break;
		default:
			fmtName = "UNKNOWN";
	}
566 567

	ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
568 569
	ahprintf(AH, ";     Format: %s\n;\n", fmtName);

B
Bruce Momjian 已提交
570 571 572 573 574 575 576 577 578 579 580 581
    ahprintf(AH, ";\n; Selected TOC Entries:\n;\n");

    while (te != AH->toc) {
	if (_tocEntryRequired(te, ropt) != 0)
		ahprintf(AH, "%d; %d %s %s %s\n", te->id, te->oidVal, te->desc, te->name, te->owner);
		te = te->next;
    }

    if (ropt->filename)
	ResetOutput(AH, sav);
}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
/***********
 * BLOB Archival
 ***********/

/* Called by a dumper to signal start of a BLOB */
int StartBlob(Archive* AHX, int oid)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;

    if (!AH->StartBlobPtr)
		die_horribly(AH, "%s: BLOB output not supported in chosen format\n", progname);

    (*AH->StartBlobPtr)(AH, AH->currToc, oid);

    return 1;
}

/* Called by a dumper to signal end of a BLOB */
int EndBlob(Archive* AHX, int oid)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;

    if (AH->EndBlobPtr)
		(*AH->EndBlobPtr)(AH, AH->currToc, oid);

    return 1;
}

/**********
 * BLOB Restoration
 **********/

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
/*
 * Called by a format handler before any blobs are restored 
 */
void StartRestoreBlobs(ArchiveHandle* AH)
{
	AH->blobCount = 0;
}

/*
 * Called by a format handler after all blobs are restored 
 */
void EndRestoreBlobs(ArchiveHandle* AH)
{
	if (AH->txActive)
	{
		ahlog(AH, 2, "Committing BLOB transactions\n");
		CommitTransaction(AH);
	}

	if (AH->blobTxActive)
	{
		CommitTransactionXref(AH);
	}

	ahlog(AH, 1, "Restored %d BLOBs\n", AH->blobCount);
}


642 643 644 645 646 647 648
/*
 * Called by a format handler to initiate restoration of a blob
 */
void StartRestoreBlob(ArchiveHandle* AH, int oid)
{
	int			loOid;

649 650
	AH->blobCount++;

651 652 653 654 655 656 657 658 659
	if (!AH->createdBlobXref)
	{
		if (!AH->connection)
			die_horribly(AH, "%s: can not restore BLOBs without a database connection", progname);

		CreateBlobXrefTable(AH);
		AH->createdBlobXref = 1;
	}

660 661 662 663 664 665 666 667 668 669 670 671
	/*
	 * Start long-running TXs if necessary
	 */
	if (!AH->txActive)
	{
		ahlog(AH, 2, "Starting BLOB transactions\n");
		StartTransaction(AH);
	}
	if (!AH->blobTxActive)
	{
		StartTransactionXref(AH);
	}
672

673 674 675 676
	loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
	if (loOid == 0)
		die_horribly(AH, "%s: unable to create BLOB\n", progname);

677
	ahlog(AH, 2, "Restoring BLOB oid %d as %d\n", oid, loOid);
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

	InsertBlobXref(AH, oid, loOid);

	AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
	if (AH->loFd == -1)
		die_horribly(AH, "%s: unable to open BLOB\n", progname);

    AH->writingBlob = 1;
}

void EndRestoreBlob(ArchiveHandle* AH, int oid)
{
    lo_close(AH->connection, AH->loFd);
    AH->writingBlob = 0;

693 694 695 696 697 698 699 700 701
	/*
	 * Commit every BLOB_BATCH_SIZE blobs...
	 */
	if ( ((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount) 
	{
		ahlog(AH, 2, "Committing BLOB transactions\n");
		CommitTransaction(AH);
		CommitTransactionXref(AH);
	}
702 703
}

B
Bruce Momjian 已提交
704 705 706 707 708 709 710
/***********
 * Sorting and Reordering
 ***********/

/*
 * Move TOC entries of the specified type to the START of the TOC.
 */
711

B
Bruce Momjian 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
/* Public */
void MoveToStart(Archive* AHX, char *oType) 
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    TocEntry	*te = AH->toc->next;
    TocEntry	*newTe;

    while (te != AH->toc) {
		te->_moved = 0;
		te = te->next;
    }

    te = AH->toc->prev;
    while (te != AH->toc && !te->_moved) {
	newTe = te->prev;
	if (strcmp(te->desc, oType) == 0) {
	    _moveAfter(AH, AH->toc, te);
	}
		te = newTe;
    }
}


/*
 * Move TOC entries of the specified type to the end of the TOC.
 */
/* Public */
void MoveToEnd(Archive* AHX, char *oType) 
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    TocEntry	*te = AH->toc->next;
    TocEntry	*newTe;

    while (te != AH->toc) {
	te->_moved = 0;
	te = te->next;
    }

    te = AH->toc->next;
    while (te != AH->toc && !te->_moved) {
	newTe = te->next;
	if (strcmp(te->desc, oType) == 0) {
	    _moveBefore(AH, AH->toc, te);
	}
		te = newTe;
    }
}

/* 
 * Sort TOC by OID
 */
/* Public */
void SortTocByOID(Archive* AHX)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    _SortToc(AH, _tocSortCompareByOIDNum);
}

/*
 * Sort TOC by ID
 */
/* Public */
void SortTocByID(Archive* AHX)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    _SortToc(AH, _tocSortCompareByIDNum);
}

void SortTocFromFile(Archive* AHX, RestoreOptions *ropt)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    FILE	*fh;
    char	buf[1024];
    char	*cmnt;
    char	*endptr;
    int		id;
    TocEntry	*te;
    TocEntry	*tePrev;
    int		i;

    /* Allocate space for the 'wanted' array, and init it */
    ropt->idWanted = (int*)malloc(sizeof(int)*AH->tocCount);
    for ( i = 0 ; i < AH->tocCount ; i++ )
	ropt->idWanted[i] = 0;

    ropt->limitToList = 1;

    /* Mark all entries as 'not moved' */
    te = AH->toc->next;
    while (te != AH->toc) {
	te->_moved = 0;
	te = te->next;
    }

    /* Set prev entry as head of list */
    tePrev = AH->toc;

    /* Setup the file */
    fh = fopen(ropt->tocFile, PG_BINARY_R);
811 812
	if (!fh)
		die_horribly(AH, "%s: could not open TOC file\n", progname);
B
Bruce Momjian 已提交
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

    while (fgets(buf, 1024, fh) != NULL)
    {
	/* Find a comment */
	cmnt = strchr(buf, ';');
	if (cmnt == buf)
	    continue;

	/* End string at comment */
	if (cmnt != NULL)
	    cmnt[0] = '\0';

	/* Skip if all spaces */
	if (strspn(buf, " \t") == strlen(buf))
	    continue;

	/* Get an ID */
	id = strtol(buf, &endptr, 10);
	if (endptr == buf)
	{
833
	    fprintf(stderr, "%s: WARNING - line ignored: %s\n", progname, buf);
B
Bruce Momjian 已提交
834 835 836 837 838 839
	    continue;
	}

	/* Find TOC entry */
	te = _getTocEntry(AH, id);
	if (!te) 
840
	    die_horribly(AH, "%s: could not find entry for id %d\n",progname, id);
B
Bruce Momjian 已提交
841 842 843 844 845 846 847

	ropt->idWanted[id-1] = 1;

	_moveAfter(AH, tePrev, te);
	tePrev = te;
    }

848 849
    if (fclose(fh) != 0)
		die_horribly(AH, "%s: could not close TOC file\n", progname);
B
Bruce Momjian 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
}

/**********************
 * 'Convenience functions that look like standard IO functions
 * for writing data when in dump mode.
 **********************/

/* Public */
int archputs(const char *s, Archive* AH) {
    return WriteData(AH, s, strlen(s));
}

/* Public */
int archputc(const char c, Archive* AH) {
    return WriteData(AH, &c, 1);
}

/* Public */
int archprintf(Archive* AH, const char *fmt, ...)
{
    char 	*p = NULL;
    va_list 	ap;
872
    int		bSize = strlen(fmt) + 256;
B
Bruce Momjian 已提交
873 874
    int		cnt = -1;

875 876
    /* This is paranoid: deal with the possibility that vsnprintf is willing to ignore trailing null */
    /* or returns > 0 even if string does not fit. It may be the case that it returns cnt = bufsize */ 
877
    while (cnt < 0 || cnt >= (bSize-1) )
B
Bruce Momjian 已提交
878
	{
879 880 881 882 883 884 885 886 887 888
		if (p != NULL) free(p);
		bSize *= 2;
		p = (char*)malloc(bSize);
		if (p == NULL)
		{
			exit_horribly(AH, "%s: could not allocate buffer for archprintf\n", progname);
		}
		va_start(ap, fmt);
		cnt = vsnprintf(p, bSize, fmt, ap);
		va_end(ap);
B
Bruce Momjian 已提交
889 890 891 892 893 894 895 896 897 898 899 900 901 902
    }
    WriteData(AH, p, cnt);
    free(p);
    return cnt;
}


/*******************************
 * Stuff below here should be 'private' to the archiver routines
 *******************************/

OutputContext SetOutput(ArchiveHandle* AH, char *filename, int compression)
{
    OutputContext	sav;
903
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    char		fmode[10];
#endif
    int			fn = 0;

    /* Replace the AH output file handle */
    sav.OF = AH->OF;
    sav.gzOut = AH->gzOut;

    if (filename) {
	fn = 0;
    } else if (AH->FH) {
	fn = fileno(AH->FH);
    } else if (AH->fSpec) {
	fn = 0;
	filename = AH->fSpec;
    } else {
	fn = fileno(stdout);
    }

    /* If compression explicitly requested, use gzopen */
924
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
925 926
    if (compression != 0)
    {
927 928 929 930 931 932 933
		sprintf(fmode, "wb%d", compression);
		if (fn) {
			AH->OF = gzdopen(dup(fn), fmode); /* Don't use PG_BINARY_x since this is zlib */
		} else {
			AH->OF = gzopen(filename, fmode);
		}
		AH->gzOut = 1;
B
Bruce Momjian 已提交
934 935
    } else { /* Use fopen */
#endif
936 937 938 939 940 941
		if (fn) {
			AH->OF = fdopen(dup(fn), PG_BINARY_W);
		} else {
			AH->OF = fopen(filename, PG_BINARY_W);
		}
		AH->gzOut = 0;
942
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
943 944 945
    }
#endif

946 947 948
	if (!AH->OF)
		die_horribly(AH, "%s: could not set output\n", progname);

B
Bruce Momjian 已提交
949 950 951 952 953
    return sav;
}

void ResetOutput(ArchiveHandle* AH, OutputContext sav)
{
954 955
	int				res;

B
Bruce Momjian 已提交
956
    if (AH->gzOut)
957
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
958
    else
959 960 961 962
		res = fclose(AH->OF);

	if (res != 0)
		die_horribly(AH, "%s: could not reset the output file\n", progname);
B
Bruce Momjian 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976

    AH->gzOut = sav.gzOut;
    AH->OF = sav.OF;
}



/*
 *  Print formatted text to the output file (usually stdout).
 */
int ahprintf(ArchiveHandle* AH, const char *fmt, ...)
{
    char 	*p = NULL;
    va_list 	ap;
977
    int		bSize = strlen(fmt) + 256; /* Should be enough */
B
Bruce Momjian 已提交
978 979
    int		cnt = -1;

980 981
    /* This is paranoid: deal with the possibility that vsnprintf is willing to ignore trailing null */
    /* or returns > 0 even if string does not fit. It may be the case that it returns cnt = bufsize */ 
982 983
    while (cnt < 0 || cnt >= (bSize - 1) )
	{
984 985 986 987 988 989 990
		if (p != NULL) free(p);
		bSize *= 2;
		p = (char*)malloc(bSize);
		if (p == NULL)
		{
			die_horribly(AH, "%s: could not allocate buffer for ahprintf\n", progname);
		}
991
		va_start(ap, fmt);
992
		cnt = vsnprintf(p, bSize, fmt, ap);
993
		va_end(ap);
B
Bruce Momjian 已提交
994 995 996 997 998 999
    }
    ahwrite(p, 1, cnt, AH);
    free(p);
    return cnt;
}

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
void ahlog(ArchiveHandle* AH, int level, const char *fmt, ...)
{
	va_list		ap;

	if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
		return;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
}

1012 1013 1014 1015 1016 1017 1018 1019
/*
 * Single place for logic which says 'We are restoring to a direct DB connection'.
 */
int RestoringToDB(ArchiveHandle* AH)
{
	return (AH->ropt && AH->ropt->useDB && AH->connection);
}

B
Bruce Momjian 已提交
1020
/*
1021 1022 1023 1024
 *  Write buffer to the output file (usually stdout). This is user for
 *  outputting 'restore' scripts etc. It is even possible for an archive
 * 	format to create a custom output routine to 'fake' a restore if it
 *	wants to generate a script (see TAR output).
B
Bruce Momjian 已提交
1025 1026 1027
 */
int ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle* AH)
{
1028 1029 1030 1031 1032 1033
	int		res;

    if (AH->writingBlob)
	{
		res = lo_write(AH->connection, AH->loFd, (void*)ptr, size * nmemb);
		ahlog(AH, 5, "Wrote %d bytes of BLOB data (result = %d)\n", size * nmemb, res);
1034 1035 1036 1037
		if (res < size * nmemb)
			die_horribly(AH, "%s: could not write to large object (result = %d, expected %d)\n", 
							progname, res, size * nmemb);

1038 1039 1040
		return res;
	}
    else if (AH->gzOut)
1041 1042 1043 1044 1045 1046
	{
		res = GZWRITE((void*)ptr, size, nmemb, AH->OF);
		if (res != (nmemb * size))
			die_horribly(AH, "%s: could not write to archive\n", progname);
		return res;
	}
1047
    else if (AH->CustomOutPtr)
1048 1049 1050 1051 1052 1053
	{
		res = AH->CustomOutPtr(AH, ptr, size * nmemb);
		if (res != (nmemb * size))
			die_horribly(AH, "%s: could not write to custom output routine\n", progname);
		return res;
	}
1054 1055 1056 1057 1058 1059
	else
	{
		/*
		 * If we're doing a restore, and it's direct to DB, and we're connected
	     * then send it to the DB.
		 */	
1060
		if (RestoringToDB(AH))
1061
			return ExecuteSqlCommandBuf(AH, (void*)ptr, size*nmemb); /* Always 1, currently */
1062
		else
1063 1064 1065 1066 1067 1068
		{
			res = fwrite((void*)ptr, size, nmemb, AH->OF);
			if (res != nmemb)
				die_horribly(AH, "%s: could not write to output file (%d != %d)\n", progname, res, nmemb);
			return res;
		}
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
	}
}		

/* Common exit code */
static void _die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap)
{
    vfprintf(stderr, fmt, ap);

    if (AH)
	if (AH->connection)
	    PQfinish(AH->connection);
1080 1081
	if (AH->blobConnection)
		PQfinish(AH->blobConnection);
1082 1083

    exit(1);
B
Bruce Momjian 已提交
1084 1085
}

1086 1087 1088 1089 1090 1091 1092 1093
/* External use */
void exit_horribly(Archive *AH, const char *fmt, ...)
{
    va_list     ap;

    va_start(ap, fmt);
    _die_horribly((ArchiveHandle*)AH, fmt, ap);
}
B
Bruce Momjian 已提交
1094

1095 1096
/* Archiver use (just different arg declaration) */
void die_horribly(ArchiveHandle *AH, const char *fmt, ...)
B
Bruce Momjian 已提交
1097 1098 1099 1100
{
    va_list 	ap;

    va_start(ap, fmt);
1101
    _die_horribly(AH, fmt, ap);
B
Bruce Momjian 已提交
1102 1103
}

1104

B
Bruce Momjian 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
static void _moveAfter(ArchiveHandle* AH, TocEntry* pos, TocEntry* te)
{
    te->prev->next = te->next;
    te->next->prev = te->prev;

    te->prev = pos;
    te->next = pos->next;

    pos->next->prev = te;
    pos->next = te;

    te->_moved = 1;
}

static void _moveBefore(ArchiveHandle* AH, TocEntry* pos, TocEntry* te)
{
    te->prev->next = te->next;
    te->next->prev = te->prev;

    te->prev = pos->prev;
    te->next = pos;
    pos->prev->next = te;
    pos->prev = te;

    te->_moved = 1;
}

static TocEntry* _getTocEntry(ArchiveHandle* AH, int id)
{
    TocEntry    *te;

    te = AH->toc->next;
    while (te != AH->toc) {
	if (te->id == id)
	    return te;
	te = te->next;
    }
    return NULL;
}

int	TocIDRequired(ArchiveHandle* AH, int id, RestoreOptions *ropt)
{
    TocEntry	*te = _getTocEntry(AH, id);

    if (!te)
	return 0;

    return _tocEntryRequired(te, ropt);
}

int	WriteInt(ArchiveHandle* AH, int i)
{
    int b;

    /* This is a bit yucky, but I don't want to make the 
     * binary format very dependant on representation,	    
     * and not knowing much about it, I write out a 
     * sign byte. If you change this, don't forget to change the
     * file version #, and modify readInt to read the new format
     * AS WELL AS the old formats.
     */ 

    /* SIGN byte */
    if (i < 0) {
	(*AH->WriteBytePtr)(AH, 1);
1170
		i = -i;
B
Bruce Momjian 已提交
1171
    } else {
1172
		(*AH->WriteBytePtr)(AH, 0);
B
Bruce Momjian 已提交
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    }
    
    for(b = 0 ; b < AH->intSize ; b++) {
        (*AH->WriteBytePtr)(AH, i & 0xFF);
        i = i / 256;
    }

    return AH->intSize + 1;
}

int    	ReadInt(ArchiveHandle* AH)
{
    int res = 0;
    int bv, b;
    int	sign = 0; /* Default positive */
1188
	int bitShift = 0;
B
Bruce Momjian 已提交
1189 1190

    if (AH->version > K_VERS_1_0)
1191 1192
		/* Read a sign byte */
		sign = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
1193 1194

    for( b = 0 ; b < AH->intSize ; b++) {
1195 1196 1197 1198
        bv = (*AH->ReadBytePtr)(AH) & 0xFF;
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
1199 1200 1201
    }

    if (sign)
1202
		res = - res;
B
Bruce Momjian 已提交
1203 1204 1205 1206 1207 1208

    return res;
}

int	WriteStr(ArchiveHandle* AH, char* c)
{
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
    int res;

	if (c)
	{
		res = WriteInt(AH, strlen(c));
		res += (*AH->WriteBufPtr)(AH, c, strlen(c));
	}
	else
		res = WriteInt(AH, -1);

    return res;
B
Bruce Momjian 已提交
1220 1221 1222 1223 1224 1225 1226 1227
}

char*	ReadStr(ArchiveHandle* AH)
{
    char*	buf;
    int		l;

    l = ReadInt(AH);
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
	if (l == -1)
		buf = NULL;
	else
	{
		buf = (char*)malloc(l+1);
		if (!buf)
			die_horribly(AH, "%s: Unable to allocate sufficient memory in ReadStr - "													"requested %d (0x%x) bytes\n", progname, l, l);

		(*AH->ReadBufPtr)(AH, (void*)buf, l);
		buf[l] = '\0';
	}
B
Bruce Momjian 已提交
1239 1240 1241 1242

    return buf;
}

T
Tom Lane 已提交
1243 1244
static int
_discoverArchiveFormat(ArchiveHandle* AH)
B
Bruce Momjian 已提交
1245 1246 1247 1248 1249 1250
{
    FILE	*fh;
    char	sig[6]; /* More than enough */
    int		cnt;
    int		wantClose = 0;

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	/*
	 * fprintf(stderr, "%s: Attempting to ascertain archive format\n", progname);
	 */

	if (AH->lookahead)
		free(AH->lookahead);

	AH->lookaheadSize = 512;
	AH->lookahead = calloc(1, 512);
	AH->lookaheadLen = 0;
	AH->lookaheadPos = 0;
1262

B
Bruce Momjian 已提交
1263
    if (AH->fSpec) {
1264 1265
		wantClose = 1;
		fh = fopen(AH->fSpec, PG_BINARY_R);
B
Bruce Momjian 已提交
1266
    } else {
1267
		fh = stdin;
B
Bruce Momjian 已提交
1268 1269 1270
    }

    if (!fh)
1271
		die_horribly(AH, "Archiver: could not open input file\n");
B
Bruce Momjian 已提交
1272 1273 1274

    cnt = fread(sig, 1, 5, fh);

1275
    if (cnt != 5)
1276
        die_horribly(AH, "%s: input file is too short, or is unreadable\n", progname);
B
Bruce Momjian 已提交
1277

1278 1279 1280
	/* Save it, just in case we need it later*/
	strncpy(&AH->lookahead[0], sig, 5);
	AH->lookaheadLen = 5;
B
Bruce Momjian 已提交
1281

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    if (strncmp(sig, "PGDMP", 5) == 0)
	{
		AH->vmaj = fgetc(fh);
		AH->vmin = fgetc(fh);

		/* Save these too... */
		AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
		AH->lookahead[AH->lookaheadLen++] = AH->vmin;

		/* Check header version; varies from V1.0 */
		if (AH->vmaj > 1 || ( (AH->vmaj == 1) && (AH->vmin > 0) ) ) /* Version > 1.0 */
		{	
			AH->vrev = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->vrev;
		}
		else
			AH->vrev = 0;

		AH->intSize = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->intSize;

		AH->format = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->format;

		/* Make a convenient integer <maj><min><rev>00 */
		AH->version = ( (AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev ) * 256 + 0;
	} else {
		/*
		 * *Maybe* we have a tar archive format file...
		 * So, read first 512 byte header...
		 */
		cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
		AH->lookaheadLen += cnt;
B
Bruce Momjian 已提交
1315

1316 1317 1318
		if (AH->lookaheadLen != 512)
			die_horribly(AH, "%s: input file does not appear to be a valid archive (too short?)\n",
							progname);
B
Bruce Momjian 已提交
1319

1320 1321
		if (!isValidTarHeader(AH->lookahead))
			die_horribly(AH, "%s: input file does not appear to be a valid archive\n", progname);
B
Bruce Momjian 已提交
1322

1323 1324
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1325 1326 1327

    /* If we can't seek, then mark the header as read */
    if (fseek(fh, 0, SEEK_SET) != 0) 
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	{
		/*
		 * NOTE: Formats that use the looahead buffer can unset this in their Init routine.
		 */
		AH->readHeader = 1;
	}
	else
		AH->lookaheadLen = 0; /* Don't bother since we've reset the file */

	/*
	 *fprintf(stderr, "%s: read %d bytes into lookahead buffer\n", progname, AH->lookaheadLen);
	 */
B
Bruce Momjian 已提交
1340 1341 1342

    /* Close the file */
    if (wantClose)
1343 1344
		if (fclose(fh) != 0)
			die_horribly(AH, "%s: could not close the input file after reading header\n", progname);
B
Bruce Momjian 已提交
1345 1346 1347 1348 1349 1350 1351 1352

    return AH->format;
}


/*
 * Allocate an archive handle
 */
1353 1354 1355
static ArchiveHandle* _allocAH(const char* FileSpec, const ArchiveFormat fmt, 
				const int compression, ArchiveMode mode) 
{
B
Bruce Momjian 已提交
1356 1357
    ArchiveHandle*	AH;

1358 1359 1360 1361
	/*
	 *fprintf(stderr, "%s: allocating AH for %s, format %d\n", progname, FileSpec, fmt); 
	 */

1362
    AH = (ArchiveHandle*)calloc(1, sizeof(ArchiveHandle));
B
Bruce Momjian 已提交
1363
    if (!AH) 
1364
		die_horribly(AH, "Archiver: Could not allocate archive handle\n");
B
Bruce Momjian 已提交
1365 1366 1367

    AH->vmaj = K_VERS_MAJOR;
    AH->vmin = K_VERS_MINOR;
1368
	AH->vrev = K_VERS_REV;
B
Bruce Momjian 已提交
1369

1370 1371
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
1372 1373 1374
    AH->intSize = sizeof(int);
    AH->lastID = 0;
    if (FileSpec) {
1375 1376 1377 1378 1379 1380 1381 1382
		AH->fSpec = strdup(FileSpec);
		/*
		 * Not used; maybe later....
		 *
		 * AH->workDir = strdup(FileSpec);
		 * for(i=strlen(FileSpec) ; i > 0 ; i--)
		 *   if (AH->workDir[i-1] == '/')
		 */
B
Bruce Momjian 已提交
1383
    } else {
1384 1385
		AH->fSpec = NULL;
    } 
B
Bruce Momjian 已提交
1386

1387
    AH->currUser = strdup(""); /* So it's valid, but we can free() it later if necessary */ 
B
Bruce Momjian 已提交
1388

1389
    AH->toc = (TocEntry*)calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
1390
    if (!AH->toc)
1391
		die_horribly(AH, "Archiver: Could not allocate TOC header\n");
B
Bruce Momjian 已提交
1392 1393 1394 1395 1396 1397 1398

    AH->toc->next = AH->toc;
    AH->toc->prev = AH->toc;
    
    AH->mode = mode;
    AH->compression = compression;

1399 1400
	AH->pgCopyBuf = createPQExpBuffer();
	AH->sqlBuf = createPQExpBuffer();
B
Bruce Momjian 已提交
1401 1402 1403 1404 1405

    /* Open stdout with no compression for AH output handle */
    AH->gzOut = 0;
    AH->OF = stdout;

1406 1407 1408 1409
	/*
	 *fprintf(stderr, "%s: archive format is %d\n", progname, fmt);
	 */

B
Bruce Momjian 已提交
1410
    if (fmt == archUnknown)
1411 1412 1413
		AH->format = _discoverArchiveFormat(AH);
	else
		AH->format = fmt;
B
Bruce Momjian 已提交
1414

1415
    switch (AH->format) {
B
Bruce Momjian 已提交
1416

1417 1418 1419
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
1420

1421 1422 1423
		case archFiles:
			InitArchiveFmt_Files(AH);
			break;
B
Bruce Momjian 已提交
1424

1425 1426 1427
		case archNull:
			InitArchiveFmt_Null(AH);
			break;
B
Bruce Momjian 已提交
1428

1429 1430 1431 1432 1433 1434
		case archTar:
			InitArchiveFmt_Tar(AH);
			break;

		default:
			die_horribly(AH, "Archiver: Unrecognized file format '%d'\n", fmt);
B
Bruce Momjian 已提交
1435 1436 1437 1438 1439 1440 1441 1442 1443
    }

    return AH;
}


void WriteDataChunks(ArchiveHandle* AH)
{
    TocEntry		*te = AH->toc->next;
1444 1445
	StartDataPtr	startPtr;
	EndDataPtr		endPtr;
B
Bruce Momjian 已提交
1446 1447 1448 1449 1450

    while (te != AH->toc) {
	if (te->dataDumper != NULL) {
	    AH->currToc = te;
	    /* printf("Writing data for %d (%x)\n", te->id, te); */
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462

		if (strcmp(te->desc, "BLOBS") == 0)
		{
			startPtr = AH->StartBlobsPtr;
			endPtr = AH->EndBlobsPtr;
		} else {
			startPtr = AH->StartDataPtr;
			endPtr = AH->EndDataPtr;
		}

	    if (startPtr != NULL) {
			(*startPtr)(AH, te);
B
Bruce Momjian 已提交
1463 1464 1465 1466 1467 1468 1469 1470
	    }

	    /* printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg); */
	    /*
	     * The user-provided DataDumper routine needs to call AH->WriteData
	     */
	    (*te->dataDumper)((Archive*)AH, te->oid, te->dataDumperArg);

1471 1472
	    if (endPtr != NULL) {
			(*endPtr)(AH, te);
B
Bruce Momjian 已提交
1473 1474 1475
	    }
	    AH->currToc = NULL;
	}
1476
		te = te->next;
B
Bruce Momjian 已提交
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
    }
}

void WriteToc(ArchiveHandle* AH)
{
    TocEntry	*te = AH->toc->next;

    /* printf("%d TOC Entries to save\n", AH->tocCount); */

    WriteInt(AH, AH->tocCount);
    while (te != AH->toc) {
	WriteInt(AH, te->id);
	WriteInt(AH, te->dataDumper ? 1 : 0);
	WriteStr(AH, te->oid);
	WriteStr(AH, te->name);
	WriteStr(AH, te->desc);
	WriteStr(AH, te->defn);
	WriteStr(AH, te->dropStmt);
1495
	WriteStr(AH, te->copyStmt);
B
Bruce Momjian 已提交
1496 1497 1498 1499
	WriteStr(AH, te->owner);
	if (AH->WriteExtraTocPtr) {
	    (*AH->WriteExtraTocPtr)(AH, te);
	}
1500
		te = te->next;
B
Bruce Momjian 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    }
}

void ReadToc(ArchiveHandle* AH)
{
    int 		i;

    TocEntry	*te = AH->toc->next;

    AH->tocCount = ReadInt(AH);

    for( i = 0 ; i < AH->tocCount ; i++) {

1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
		te = (TocEntry*)calloc(1, sizeof(TocEntry));
		te->id = ReadInt(AH);

		/* Sanity check */
		if (te->id <= 0 || te->id > AH->tocCount)
			die_horribly(AH, "Archiver: failed sanity check (bad entry id) - perhaps a corrupt TOC\n");

		te->hadDumper = ReadInt(AH);
		te->oid = ReadStr(AH);
		te->oidVal = atoi(te->oid);
		te->name = ReadStr(AH);
		te->desc = ReadStr(AH);
		te->defn = ReadStr(AH);
		te->dropStmt = ReadStr(AH);

		if (AH->version >= K_VERS_1_3)
			te->copyStmt = ReadStr(AH);

		te->owner = ReadStr(AH);

		if (AH->ReadExtraTocPtr) {
			(*AH->ReadExtraTocPtr)(AH, te);
		}

		ahlog(AH, 3, "Read TOC entry %d (id %d) for %s %s\n", i, te->id, te->desc, te->name);

		te->prev = AH->toc->prev;
		AH->toc->prev->next = te;
		AH->toc->prev = te;
		te->next = AH->toc;
B
Bruce Momjian 已提交
1544 1545 1546 1547 1548
    }
}

static int _tocEntryRequired(TocEntry* te, RestoreOptions *ropt)
{
1549 1550
    int res = 3; /* Schema = 1, Data = 2, Both = 3 */
 
B
Bruce Momjian 已提交
1551 1552
    /* If it's an ACL, maybe ignore it */
    if (ropt->aclsSkip && strcmp(te->desc,"ACL") == 0)
1553
		return 0;
B
Bruce Momjian 已提交
1554

1555 1556 1557
	if (!ropt->create && strcmp(te->desc,"DATABASE") == 0)
		return 0;

B
Bruce Momjian 已提交
1558 1559 1560
    /* Check if tablename only is wanted */
    if (ropt->selTypes)
    {
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
		if ( (strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0) )
		{
			if (!ropt->selTable)
				return 0;
			if (ropt->tableNames && strcmp(ropt->tableNames, te->name) != 0)
				return 0;
		} else if (strcmp(te->desc, "INDEX") == 0) {
			if (!ropt->selIndex)
				return 0;
			if (ropt->indexNames && strcmp(ropt->indexNames, te->name) != 0)
				return 0;
		} else if (strcmp(te->desc, "FUNCTION") == 0) {
			if (!ropt->selFunction)
				return 0;
			if (ropt->functionNames && strcmp(ropt->functionNames, te->name) != 0)
				return 0;
		} else if (strcmp(te->desc, "TRIGGER") == 0) {
			if (!ropt->selTrigger)
				return 0;
			if (ropt->triggerNames && strcmp(ropt->triggerNames, te->name) != 0)
				return 0;
		} else {
			return 0;
		}
B
Bruce Momjian 已提交
1585 1586
	}

1587 1588 1589 1590
	/* Special Case: If 'SEQUENCE SET' and schemaOnly, then not needed */
	if (ropt->schemaOnly && (strcmp(te->desc, "SEQUENCE SET") == 0) )
		return 0;

B
Bruce Momjian 已提交
1591 1592
    /* Mask it if we only want schema */
    if (ropt->schemaOnly)
1593
		res = res & 1;
B
Bruce Momjian 已提交
1594 1595

    /* Mask it we only want data */
1596
    if (ropt->dataOnly && (strcmp(te->desc, "SEQUENCE SET") != 0) ) 
B
Bruce Momjian 已提交
1597 1598 1599 1600
       res = res & 2;

    /* Mask it if we don't have a schema contribition */
    if (!te->defn || strlen(te->defn) == 0) 
1601
		res = res & 2;
B
Bruce Momjian 已提交
1602 1603 1604

    /* Mask it if we don't have a possible data contribition */
    if (!te->hadDumper)
1605
		res = res & 1;
B
Bruce Momjian 已提交
1606 1607 1608

    /* Finally, if we used a list, limit based on that as well */
    if (ropt->limitToList && !ropt->idWanted[te->id - 1]) 
1609
		return 0;
B
Bruce Momjian 已提交
1610 1611 1612 1613

    return res;
}

1614
static void _reconnectAsUser(ArchiveHandle* AH, const char *dbname, char *user)
1615
{
1616 1617 1618 1619 1620 1621
	if (AH->ropt && AH->ropt->noReconnect)
		return;

	if (user && strlen(user) != 0
			&& ( (strcmp(AH->currUser, user) != 0) || (strcmp(dbname,"-") != 0)))
	{
1622 1623
		if (RestoringToDB(AH))
		{
1624
			ReconnectDatabase(AH, dbname, user);
1625 1626 1627
		}
		else
		{
1628
			ahprintf(AH, "\\connect %s %s\n", dbname, user);
1629
		}
1630 1631 1632 1633 1634 1635
		if (AH->currUser) 
		{
			free(AH->currUser);
		}

		AH->currUser = strdup(user);
1636 1637 1638 1639 1640 1641 1642 1643 1644
    } 
}

static void _reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* te) 
{
	if (AH->ropt && AH->ropt->noOwner)
		return;

	_reconnectAsUser(AH, dbname, te->owner);
1645 1646
}

B
Bruce Momjian 已提交
1647 1648 1649 1650 1651
static int _printTocEntry(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) 
{
    ahprintf(AH, "--\n-- TOC Entry ID %d (OID %s)\n--\n-- Name: %s Type: %s Owner: %s\n",
	    te->id, te->oid, te->name, te->desc, te->owner);
    if (AH->PrintExtraTocPtr != NULL) {
1652
		(*AH->PrintExtraTocPtr)(AH, te);
B
Bruce Momjian 已提交
1653 1654 1655
    }
    ahprintf(AH, "--\n\n");

1656
	ahprintf(AH, "%s\n", te->defn);
B
Bruce Momjian 已提交
1657 1658 1659 1660 1661 1662

    return 1;
}

void WriteHead(ArchiveHandle* AH) 
{
1663 1664
	struct tm		crtm;

B
Bruce Momjian 已提交
1665 1666 1667 1668 1669 1670 1671
    (*AH->WriteBufPtr)(AH, "PGDMP", 5); 	/* Magic code */
    (*AH->WriteBytePtr)(AH, AH->vmaj);
    (*AH->WriteBytePtr)(AH, AH->vmin);
    (*AH->WriteBytePtr)(AH, AH->vrev);
    (*AH->WriteBytePtr)(AH, AH->intSize);
    (*AH->WriteBytePtr)(AH, AH->format);

1672
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
1673 1674 1675 1676 1677 1678
    if (AH->compression != 0)
	fprintf(stderr, "%s: WARNING - requested compression not available in this installation - "
		    "archive will be uncompressed \n", progname);

    AH->compression = 0;

1679
#endif
B
Bruce Momjian 已提交
1680

1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
	WriteInt(AH, AH->compression);

	crtm = *localtime(&AH->createDate);
	WriteInt(AH, crtm.tm_sec);
	WriteInt(AH, crtm.tm_min);
	WriteInt(AH, crtm.tm_hour);
	WriteInt(AH, crtm.tm_mday);
	WriteInt(AH, crtm.tm_mon);
	WriteInt(AH, crtm.tm_year);
	WriteInt(AH, crtm.tm_isdst);
	WriteStr(AH, AH->dbname);	
B
Bruce Momjian 已提交
1692 1693 1694 1695
}

void ReadHead(ArchiveHandle* AH)
{
1696 1697 1698
    char		tmpMag[7];
    int			fmt;
	struct tm	crtm;
B
Bruce Momjian 已提交
1699

1700
	/* If we haven't already read the header... */
1701
    if (!AH->readHeader) {
B
Bruce Momjian 已提交
1702

1703
		(*AH->ReadBufPtr)(AH, tmpMag, 5);
B
Bruce Momjian 已提交
1704

1705 1706
		if (strncmp(tmpMag,"PGDMP", 5) != 0)
			die_horribly(AH, "Archiver: Did not fing magic PGDMP in file header\n");
B
Bruce Momjian 已提交
1707

1708 1709
		AH->vmaj = (*AH->ReadBytePtr)(AH);
		AH->vmin = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
1710

1711 1712 1713 1714 1715 1716
		if (AH->vmaj > 1 || ( (AH->vmaj == 1) && (AH->vmin > 0) ) ) /* Version > 1.0 */
		{
			AH->vrev = (*AH->ReadBytePtr)(AH);
		} else {
			AH->vrev = 0;
		}
B
Bruce Momjian 已提交
1717

1718
		AH->version = ( (AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev ) * 256 + 0;
B
Bruce Momjian 已提交
1719 1720


1721 1722 1723
		if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
			die_horribly(AH, "%s: unsupported version (%d.%d) in file header\n", 
					progname, AH->vmaj, AH->vmin);
B
Bruce Momjian 已提交
1724

1725 1726 1727
		AH->intSize = (*AH->ReadBytePtr)(AH);
		if (AH->intSize > 32)
			die_horribly(AH, "Archiver: sanity check on integer size (%d) failes\n", AH->intSize);
B
Bruce Momjian 已提交
1728

1729 1730 1731
		if (AH->intSize > sizeof(int))
			fprintf(stderr, "\n%s: WARNING - archive was made on a machine with larger integers, "
					"some operations may fail\n", progname);
B
Bruce Momjian 已提交
1732

1733
		fmt = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
1734

1735 1736 1737
		if (AH->format != fmt)
			die_horribly(AH, "%s: expected format (%d) differs from format found in file (%d)\n", 
					progname, AH->format, fmt);
1738
    }
B
Bruce Momjian 已提交
1739 1740 1741

    if (AH->version >= K_VERS_1_2)
    {
1742 1743 1744 1745
		if (AH->version < K_VERS_1_4)
			AH->compression = (*AH->ReadBytePtr)(AH);
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
1746
    } else {
1747
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
1748 1749
    }

1750 1751
#ifndef HAVE_LIBZ
    if (AH->compression != 0)
1752 1753
		fprintf(stderr, "%s: WARNING - archive is compressed - any data will not be available\n", 
					progname);
B
Bruce Momjian 已提交
1754 1755
#endif

1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
	if (AH->version >= K_VERS_1_4)
	{
		crtm.tm_sec = ReadInt(AH);
		crtm.tm_min = ReadInt(AH);
		crtm.tm_hour = ReadInt(AH);
		crtm.tm_mday = ReadInt(AH);
		crtm.tm_mon = ReadInt(AH);
		crtm.tm_year = ReadInt(AH);
		crtm.tm_isdst = ReadInt(AH);

		AH->archdbname = ReadStr(AH);

		AH->createDate = mktime(&crtm);

		if (AH->createDate == (time_t)-1)
			fprintf(stderr, "%s: WARNING - bad creation date in header\n", progname);
	}

B
Bruce Momjian 已提交
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
}


static void _SortToc(ArchiveHandle* AH, TocSortCompareFn fn)
{
    TocEntry**	tea;
    TocEntry*	te;
    int		i;

    /* Allocate an array for quicksort (TOC size + head & foot) */
    tea = (TocEntry**)malloc(sizeof(TocEntry*) * (AH->tocCount + 2) );

    /* Build array of toc entries, including header at start and end */
    te = AH->toc;
    for( i = 0 ; i <= AH->tocCount+1 ; i++) {
	/* printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next, te->oidVal); */
	tea[i] = te;
	te = te->next;
    }

    /* Sort it, but ignore the header entries */
    qsort(&(tea[1]), AH->tocCount, sizeof(TocEntry*), fn);

    /* Rebuild list: this works becuase we have headers at each end */
    for( i = 1 ; i <= AH->tocCount ; i++) {
	tea[i]->next = tea[i+1];
	tea[i]->prev = tea[i-1];
    }


    te = AH->toc;
    for( i = 0 ; i <= AH->tocCount+1 ; i++) {
	/* printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next, te->oidVal); */
	te = te->next;
    }


    AH->toc->next = tea[1];
    AH->toc->prev = tea[AH->tocCount];
}

static int	_tocSortCompareByOIDNum(const void* p1, const void* p2)
{
    TocEntry*	te1 = *(TocEntry**)p1;
    TocEntry*	te2 = *(TocEntry**)p2;
    int		id1 = te1->oidVal;
    int 	id2 = te2->oidVal;

    /* printf("Comparing %d to %d\n", id1, id2); */

    if (id1 < id2) {
	return -1;
    } else if (id1 > id2) { 
	return 1;
    } else {
	return _tocSortCompareByIDNum(te1, te2);
    }
}

static int	_tocSortCompareByIDNum(const void* p1, const void* p2)
{
    TocEntry*	te1 = *(TocEntry**)p1;
    TocEntry*	te2 = *(TocEntry**)p2;
    int		id1 = te1->id;
    int 	id2 = te2->id;

    /* printf("Comparing %d to %d\n", id1, id2); */

    if (id1 < id2) {
	return -1;
    } else if (id1 > id2) { 
	return 1;
    } else {
	return 0;
    }
}

1851 1852 1853 1854 1855 1856 1857 1858
/*
 * Maybe I can use this somewhere...
 *
 *create table pgdump_blob_path(p text);
 *insert into pgdump_blob_path values('/home/pjw/work/postgresql-cvs/pgsql/src/bin/pg_dump_140');
 *
 *insert into dump_blob_xref select 12345,lo_import(p || '/q.q') from pgdump_blob_path;
 */
B
Bruce Momjian 已提交
1859