initdb.c 53.8 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * initdb --- initialize a PostgreSQL installation
4
 *
5 6 7
 * initdb creates (initializes) a PostgreSQL database cluster (site,
 * instance, installation, whatever).  A database cluster is a
 * collection of PostgreSQL databases all managed by the same postmaster.
8
 *
9 10 11 12
 * To create the database cluster, we create the directory that contains
 * all its data, create the files that hold the global tables, create
 * a few other control files for it, and create two databases: the
 * template0 and template1 databases.
13
 *
14 15 16 17
 * The template databases are ordinary PostgreSQL databases.  template0
 * is never supposed to change after initdb, whereas template1 can be
 * changed to add site-local standard data.  Either one can be copied
 * to produce a new database.
18
 *
19 20 21 22 23 24 25 26
 * To create template1, we run the postgres (backend) program in bootstrap
 * mode and feed it data from the postgres.bki library file.  After this
 * initial bootstrap phase, some additional stuff is created by normal
 * SQL commands fed to a standalone backend.  Some of those commands are
 * just embedded into this program (yeah, it's ugly), but larger chunks
 * are taken from script files.
 *
 * template0 is made just by copying the completed template1.
27 28 29 30 31 32 33
 *
 *
 * TODO:
 *	 - clean up find_postgres code and return values
 *
 * Note:
 *	 The program has some memory leakage - it isn't worth cleaning it up.
34 35 36 37 38 39 40 41 42 43 44
 *
 *
 * This is a C implementation of the previous shell script for setting up a
 * PostgreSQL cluster location, and should be highly compatible with it.
 * author of C translation: Andrew Dunstan	   mailto:andrew@dunslane.net
 *
 * This code is released under the terms of the PostgreSQL License.
 *
 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
45
 * $Header: /cvsroot/pgsql/src/bin/initdb/initdb.c,v 1.10 2003/11/14 18:32:34 tgl Exp $
46 47 48 49 50 51 52 53
 *
 *-------------------------------------------------------------------------
 */

#include "postgres_fe.h"

#include <dirent.h>
#include <sys/stat.h>
54
#include <sys/wait.h>
55 56 57 58 59 60
#include <unistd.h>
#include <locale.h>
#include <signal.h>

#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
Tom Lane's avatar
Tom Lane committed
61 62 63 64 65
#include "getopt_long.h"

#ifndef HAVE_OPTRESET
int			optreset;
#endif
66 67 68 69 70


/* version string we expect back from postgres */
#define PG_VERSIONSTR "postgres (PostgreSQL) " PG_VERSION "\n"

71 72 73 74 75 76
/*
 * these values are passed in by makefile defines
 *
 * Note that "datadir" is not the directory we're going to initialize,
 * it's merely how Autoconf names PREFIX/share.
 */
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
char	   *bindir = PGBINDIR;
char	   *datadir = PGDATADIR;

/* values to be obtained from arguments */
char	   *pg_data = "";
char	   *encoding = "";
char	   *locale = "";
char	   *lc_collate = "";
char	   *lc_ctype = "";
char	   *lc_monetary = "";
char	   *lc_numeric = "";
char	   *lc_time = "";
char	   *lc_messages = "";
char	   *username = "";
bool		pwprompt = false;
bool		debug = false;
bool		noclean = false;
bool		show_help = false;
bool		show_version = false;
bool		show_setting = false;


/* internal vars */
char	   *progname;
char	   *self_path;
char	   *postgres;
char	   *encodingid = "0";
char	   *bki_file;
char	   *desc_file;
char	   *hba_file;
char	   *ident_file;
char	   *conf_file;
char	   *conversion_file;
char	   *info_schema_file;
char	   *features_file;
char	   *system_views_file;
char	   *effective_user;
bool		testpath = true;
bool		made_new_pgdata = false;
116
bool		found_existing_pgdata = false;
117
char		infoversion[100];
118 119
bool		caught_signal = false;
bool		output_failed = false;
120 121 122

/* defaults */
int			n_connections = 10;
123
int			n_buffers = 50;
124

125 126 127 128 129 130 131 132 133 134
/*
 * Centralized knowledge of switches to pass to backend
 *
 * Note: in the shell-script version, we also passed PGDATA as a -D switch,
 * but here it is more convenient to pass it as an environment variable
 * (no quoting to worry about).
 */
static const char *boot_options = "-F";
static const char *backend_options = "-F -O -c search_path=pg_catalog -c exit_on_error=true";

135 136 137 138 139 140 141 142

/* platform specific path stuff */
#if defined(__CYGWIN__) || defined(WIN32)
#define EXE ".exe"
#define DEVNULL "nul"
#else
#define EXE ""
#define DEVNULL "/dev/null"
143
#endif
144 145 146 147 148

#ifdef WIN32
#define PATHSEP ';'
#else
#define PATHSEP ':'
149
#endif
150 151 152 153 154 155 156

/* detected path to postgres and (we assume) friends */
char	   *pgpath;

/* forward declare all our functions */
static bool rmtree(char *, bool);
static void exit_nicely(void);
157
static void canonicalize_path(char *);
158 159 160
#ifdef WIN32
static char *expanded_path(char *);
#else
161 162
#define expanded_path(x) (x)
#endif
163 164
static char **readfile(char *);
static void writefile(char *, char **);
165
static void pclose_check(FILE *stream);
166 167 168
static char *get_id(void);
static char *get_encoding_id(char *);
static char *get_short_version(void);
169
static int	mkdir_p(char *, mode_t);
170
static int	check_data_dir(void);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
static bool mkdatadir(char *);
static bool chklocale(const char *);
static void setlocales(void);
static void set_input(char **, char *);
static void check_input(char *path);
static int	find_postgres(char *);
static int	set_paths(void);
static char **replace_token(char **, char *, char *);
static void set_short_version(char *, char *);
static void set_null_conf(void);
static void test_buffers(void);
static void test_connections(void);
static void setup_config(void);
static void bootstrap_template1(char *);
static void setup_shadow(void);
186
static void get_set_pwd(void);
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
static void unlimit_systables(void);
static void setup_depend(void);
static void setup_sysviews(void);
static void setup_description(void);
static void setup_conversion(void);
static void setup_privileges(void);
static void set_info_version(void);
static void setup_schema(void);
static void vacuum_db(void);
static void make_template0(void);
static void usage(void);
static void trapsig(int);
static void check_ok(void);
static char *xstrdup(const char *);
static void *xmalloc(size_t);

/*
 * macros for running pipes to postgres
 */
#define PG_CMD_DECL		char cmd[MAXPGPATH]; char ** line ; FILE * pg
#define PG_CMD_DECL_NOLINE		   char cmd[MAXPGPATH]; FILE * pg
208 209 210

#define PG_CMD_OPEN \
do { \
211 212
	fflush(stdout); \
	fflush(stderr); \
213
	pg = popen(cmd, "w"); \
214 215
	if (pg == NULL) \
		exit_nicely(); \
216 217 218 219
} while (0)

#define PG_CMD_CLOSE \
do { \
220
	pclose_check(pg); \
221 222 223 224
} while (0)

#define PG_CMD_PUTLINE \
do { \
225 226
	if (fputs(*line, pg) < 0 || fflush(pg) < 0) \
		output_failed = true; \
227
} while (0)
228

229 230 231 232
#ifndef WIN32
#define QUOTE_PATH	""
#else
#define QUOTE_PATH	"\""
233 234 235
#endif

/*
236
 * routines to check mem allocations and fail noisily.
237
 *
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
 * Note that we can't call exit_nicely() on a memory failure, as it calls
 * rmtree() which needs memory allocation. So we just exit with a bang.
 */
static void *
xmalloc(size_t size)
{
	void	   *result;

	result = malloc(size);
	if (!result)
	{
		fputs("malloc failure - bailing out\n", stderr);
		exit(1);
	}
	return result;
}

static char *
xstrdup(const char *s)
{
	char	   *result;

	result = strdup(s);
	if (!result)
	{
		fputs("strdup failure - bailing out\n", stderr);
		exit(1);
	}
	return result;
}

/*
 * delete a directory tree recursively
 * assumes path points to a valid directory
 * deletes everything under path
 * if rmtopdir is true deletes the directory too
 */
static bool
rmtree(char *path, bool rmtopdir)
{
278
	char		buf[MAXPGPATH + 64];
279

280
#ifndef WIN32
281 282
	/* doesn't handle .* files, but we don't make any... */
	snprintf(buf, sizeof(buf), "rm -rf \"%s\"%s", path,
283
			 rmtopdir ? "" : "/*");
284 285
#else
	snprintf(buf, sizeof(buf), "%s /s /q \"%s\"",
286
			 rmtopdir ? "rmdir" : "del", path);
287
#endif
288

289
	return !system(buf);
290 291 292 293 294
}


/*
 * make all paths look like unix, with forward slashes
295
 * also strip any trailing slash.
296
 *
297 298 299
 * The Windows command processor will accept suitably quoted paths
 * with forward slashes, but barfs badly with mixed forward and back
 * slashes. Removing the trailing slash on a path means we never get
300
 * ugly double slashes.  Don't remove a leading slash, though.
301 302
 */
static void
303
canonicalize_path(char *path)
304 305 306 307 308 309 310 311
{
	char	   *p;

	for (p = path; *p; p++)
	{
#ifdef WIN32
		if (*p == '\\')
			*p = '/';
312
#endif
313
	}
314
	if (p > path+1 && *--p == '/')
315 316 317 318 319 320
		*p = '\0';
}

/*
 * make a copy of the array of lines, with token replaced by replacement
 * the first time it occurs on each line.
321
 *
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
 * This does most of what sed was used for in the shell script, but
 * doesn't need any regexp stuff.
 */
static char **
replace_token(char **lines, char *token, char *replacement)
{
	int			numlines = 1;
	int			i;
	char	  **result;
	int			toklen,
				replen,
				diff;

	for (i = 0; lines[i]; i++)
		numlines++;

	result = (char **) xmalloc(numlines * sizeof(char *));

	toklen = strlen(token);
	replen = strlen(replacement);
	diff = replen - toklen;

	for (i = 0; i < numlines; i++)
	{
		char	   *where;
		char	   *newline;
		int			pre;

		/* just copy pointer if NULL or no change needed */

		if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
		{
			result[i] = lines[i];
			continue;
		}

		/* if we get here a change is needed - set up new line */

		newline = (char *) xmalloc(strlen(lines[i]) + diff + 1);

		pre = where - lines[i];

		strncpy(newline, lines[i], pre);

		strcpy(newline + pre, replacement);

		strcpy(newline + pre + replen, lines[i] + pre + toklen);

		result[i] = newline;

	}

	return result;

}

/*
 * get the lines from a text file
 */
static char **
readfile(char *path)
{
	FILE	   *infile;
	int			maxlength = 0,
				linelen = 0;
	int			nlines = 0;
	char	  **result;
	char	   *buffer;
	int			c;

392
	if ((infile = fopen(path, "r")) == NULL)
393
	{
394
		fprintf(stderr, "could not read %s\n", path);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
		exit_nicely();
	}

	/* pass over the file twice - the first time to size the result */

	while ((c = fgetc(infile)) != EOF)
	{
		linelen++;
		if (c == '\n')
		{
			nlines++;
			if (linelen > maxlength)
				maxlength = linelen;
			linelen = 0;
		}
	}

	/* handle last line without a terminating newline (yuck) */

	if (linelen)
		nlines++;
	if (linelen > maxlength)
		maxlength = linelen;

	/* set up the result and the line buffer */

	result = (char **) xmalloc((nlines + 2) * sizeof(char *));
	buffer = (char *) xmalloc(maxlength + 2);

	/* now reprocess the file and store the lines */

	rewind(infile);
	nlines = 0;
	while (fgets(buffer, maxlength + 1, infile) != NULL)
	{
		result[nlines] = xstrdup(buffer);
		nlines++;
	}

	fclose(infile);
	result[nlines] = NULL;

	return result;
}

/*
 * write an array of lines to a file
 */
static void
writefile(char *path, char **lines)
{
	FILE	   *out_file;
	char	  **line;

449 450
	;
	if ((out_file = fopen(path, PG_BINARY_W)) == NULL)
451
	{
452
		fprintf(stderr, "could not write %s\n", path);
453 454 455 456 457 458 459 460 461 462 463 464
		exit_nicely();
	}
	for (line = lines; *line != NULL; line++)
	{
		if (fputs(*line, out_file) < 0)
			exit_nicely();
		free(*line);
	}
	if (fclose(out_file))
		exit_nicely();
}

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
/* pclose() plus useful error reporting */
static void
pclose_check(FILE *stream)
{
	int		exitstatus;

	exitstatus = pclose(stream);

	if (exitstatus == 0)
		return;					/* all is well */

	if (exitstatus == -1)
	{
		/* pclose() itself failed, and hopefully set errno */
		perror("pclose failed");
	}
	else if (WIFEXITED(exitstatus))
	{
		fprintf(stderr, "child process exited with exit code %d\n",
				WEXITSTATUS(exitstatus));
	}
	else if (WIFSIGNALED(exitstatus))
	{
		fprintf(stderr, "child process was terminated by signal %d\n",
				WTERMSIG(exitstatus));
	}
	else
	{
		fprintf(stderr, "child process exited with unexpected status %d\n",
				exitstatus);
	}

	exit_nicely();
}

500 501 502 503 504 505 506 507
/* source stolen from FreeBSD /src/bin/mkdir/mkdir.c and adapted */

/*
 * this tries to build all the elements of a path to a directory a la mkdir -p
 * we assume the path is in canonical form, i.e. uses / as the separator
 * we also assume it isn't null.
 */
static int
508
mkdir_p(char *path, mode_t omode)
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
{
	struct stat sb;
	mode_t		numask,
				oumask;
	int			first,
				last,
				retval;
	char	   *p;

	p = path;
	oumask = 0;
	retval = 0;

#ifdef WIN32
	/* skip network and drive specifiers for win32 */
	if (strlen(p) >= 2)
	{
		if (p[0] == '/' && p[1] == '/')
		{
			/* network drive */
			p = strstr(p + 2, "/");
			if (p == NULL)
				return 1;
		}
		else if (p[1] == ':' &&
				 ((p[0] >= 'a' && p[0] <= 'z') ||
				  (p[0] >= 'A' && p[0] <= 'Z')))
		{
			/* local drive */
			p += 2;
		}
	}
541
#endif
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

	if (p[0] == '/')			/* Skip leading '/'. */
		++p;
	for (first = 1, last = 0; !last; ++p)
	{
		if (p[0] == '\0')
			last = 1;
		else if (p[0] != '/')
			continue;
		*p = '\0';
		if (p[1] == '\0')
			last = 1;
		if (first)
		{
			/*
			 * POSIX 1003.2: For each dir operand that does not name an
			 * existing directory, effects equivalent to those cased by
			 * the following command shall occcur:
			 *
			 * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode]
			 * dir
			 *
			 * We change the user's umask and then restore it, instead of
			 * doing chmod's.
			 */
			oumask = umask(0);
			numask = oumask & ~(S_IWUSR | S_IXUSR);
			(void) umask(numask);
			first = 0;
		}
		if (last)
			(void) umask(oumask);
		if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
		{
			if (errno == EEXIST || errno == EISDIR)
			{
				if (stat(path, &sb) < 0)
				{
					retval = 1;
					break;
				}
				else if (!S_ISDIR(sb.st_mode))
				{
					if (last)
						errno = EEXIST;
					else
						errno = ENOTDIR;
					retval = 1;
					break;
				}
			}
			else
			{
				retval = 1;
				break;
			}
		}
		if (!last)
			*p = '/';
	}
	if (!first && !last)
		(void) umask(oumask);
604
	return retval;
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
}

/*
 * clean up any files we created on failure
 * if we created the data directory remove it too
 */
static void
exit_nicely(void)
{
	fprintf(stderr, "%s: failed\n", progname);

	if (!noclean)
	{
		if (made_new_pgdata)
		{
			fprintf(stderr, "%s: removing data directory \"%s\"\n",
					progname, pg_data);
			if (!rmtree(pg_data, true))
				fprintf(stderr, "%s: failed\n", progname);
		}
625
		else if (found_existing_pgdata)
626 627 628 629 630 631 632
		{
			fprintf(stderr,
					"%s: removing contents of data directory \"%s\"\n",
					progname, pg_data);
			if (!rmtree(pg_data, false))
				fprintf(stderr, "%s: failed\n", progname);
		}
633
		/* otherwise died during startup, do nothing! */
634
	}
635 636
	else
	{
637 638 639 640
		if (made_new_pgdata || found_existing_pgdata)
			fprintf(stderr,
					"%s: data directory \"%s\" not removed at user's request\n",
					progname, pg_data);
641
	}
642

643 644 645 646 647 648
	exit(1);
}

/*
 * find the current user using code lifted from pg_id.c
 *
649
 * on unix make sure it isn't really root
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
 */
static char *
get_id(void)
{
#ifndef WIN32

	struct passwd *pw;

	pw = getpwuid(getuid());

#ifndef __BEOS__				/* no root check on BEOS */

	if (!geteuid())				/* 0 is root's uid */
	{
		fprintf(stderr,
				"%s: cannot be run as root\n"
666 667 668
				"Please log in (using, e.g., \"su\") as the "
				"(unprivileged) user that will\n"
				"own the server process.\n",
669 670 671
				progname);
		exit(1);
	}
672
#endif
673 674 675 676 677 678 679 680 681 682 683 684 685

#else							/* the windows code */

	struct passwd_win32
	{
		int			pw_uid;
		char		pw_name[128];
	}			pass_win32;
	struct passwd_win32 *pw = &pass_win32;
	DWORD		pwname_size = sizeof(pass_win32.pw_name) - 1;

	pw->pw_uid = 1;
	GetUserName(pw->pw_name, &pwname_size);
686
#endif
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 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

	return xstrdup(pw->pw_name);
}

/*
 * get the encoding id for a given encoding name
 */
static char *
get_encoding_id(char *encoding_name)
{
	int			enc;
	char		result[20];

	if (encoding_name && *encoding_name)
	{
		if ((enc = pg_char_to_encoding(encoding_name)) >= 0 &&
			pg_valid_server_encoding(encoding_name) >= 0)
		{
			sprintf(result, "%d", enc);
			return xstrdup(result);
		}
	}
	fprintf(stderr, "%s: \"%s\" is not a valid server encoding name\n",
			progname, encoding_name ? encoding_name : "(null)");
	exit(1);
}

/*
 * get short version of VERSION
 */
static char *
get_short_version(void)
{
	bool		gotdot = false;
	int			end;
	char	   *vr;

	vr = xstrdup(PG_VERSION);

	for (end = 0; vr[end] != '\0'; end++)
	{
		if (vr[end] == '.')
		{
			if (end == 0)
				return NULL;
			else if (gotdot)
				break;
			else
				gotdot = true;
		}
		else if (vr[end] < '0' || vr[end] > '9')
		{
			/* gone past digits and dots */
			break;
		}
	}
	if (end == 0 || vr[end - 1] == '.' || !gotdot)
		return NULL;

	vr[end] = '\0';
	return vr;
}

/*
 * make sure the data directory either doesn't exist or is empty
752 753 754
 *
 * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty,
 * or -1 if trouble accessing directory
755
 */
756
static int
757 758 759 760
check_data_dir(void)
{
	DIR		   *chkdir;
	struct dirent *file;
761 762 763
	int			result = 1;

	errno = 0;
764 765 766 767

	chkdir = opendir(pg_data);

	if (!chkdir)
768
		return (errno == ENOENT) ? 0 : -1;
769 770 771 772 773 774 775 776 777 778

	while ((file = readdir(chkdir)) != NULL)
	{
		if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0)
		{
			/* skip this and parent directory */
			continue;
		}
		else
		{
779
			result = 2;			/* not empty */
780 781 782 783 784 785
			break;
		}
	}

	closedir(chkdir);

786 787 788 789
	if (errno != 0)
		result = -1;			/* some kind of I/O error? */

	return result;
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
}

/*
 * make the data directory (or one of its subdirectories if subdir is not NULL)
 */
static bool
mkdatadir(char *subdir)
{
	char	   *path;
	int			res;

	path = xmalloc(strlen(pg_data) + 2 +
				   (subdir == NULL ? 0 : strlen(subdir)));

	if (subdir != NULL)
		sprintf(path, "%s/%s", pg_data, subdir);
	else
		strcpy(path, pg_data);

	res = mkdir(path, 0700);
	if (res == 0)
		return true;
	else if (subdir == NULL || errno != ENOENT)
		return false;
	else
815
		return !mkdir_p(path, 0700);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
}


/*
 * set name of given input file variable under data directory
 */
static void
set_input(char **dest, char *filename)
{
	*dest = xmalloc(strlen(datadir) + strlen(filename) + 2);
	sprintf(*dest, "%s/%s", datadir, filename);
}

/*
 * check that given input file exists
 */
static void
check_input(char *path)
{
	struct stat statbuf;

	if (stat(path, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
	{
		fprintf(stderr,
				"%s: file \"%s\" not found\n"
		   "This means you have a corrupted installation or identified\n"
				"the wrong directory with the invocation option -L.\n",
				progname, path);
		exit(1);
	}

}

/*
 * TODO - clean this up and handle the errors properly
 * don't overkill
 */
#define FIND_SUCCESS 0
#define FIND_NOT_FOUND 1
#define FIND_STAT_ERR 2
#define FIND_NOT_REGFILE 3
#define FIND_BAD_PERM 4
#define FIND_EXEC_ERR 5
#define FIND_WRONG_VERSION 6

/*
 * see if there is a postgres executable in the given path, and giving the
 * right version number
 */
static int
find_postgres(char *path)
{
	char		fn[MAXPGPATH];
	char		cmd[MAXPGPATH];
	char		line[100];

#ifndef WIN32
	int			permmask = S_IROTH | S_IXOTH;
#endif

	struct stat statbuf;
	FILE	   *pgver;
	int			plen = strlen(path);

880 881
	if (plen > 0 && path[plen - 1] != '/')
		snprintf(fn, sizeof(fn), "%s/postgres%s", path, EXE);
882
	else
883
		snprintf(fn, sizeof(fn), "%spostgres%s", path, EXE);
884 885 886 887 888 889 890 891 892 893 894 895

	if (stat(fn, &statbuf) != 0)
	{
		if (errno == ENOENT)
			return FIND_NOT_FOUND;
		else
			return FIND_STAT_ERR;
	}
	if (!S_ISREG(statbuf.st_mode))
		return FIND_NOT_REGFILE;

#ifndef WIN32
896

897 898 899 900
	/*
	 * Only unix requires this test, on WIN32 an .exe file should be
	 * executable
	 */
901 902
	if ((statbuf.st_mode & permmask) != permmask)
		return FIND_BAD_PERM;
903
#endif
904

905
	snprintf(cmd, sizeof(cmd), "\"%s/postgres\" -V 2>%s", path, DEVNULL);
906

907 908 909 910
	/* flush output buffers in case popen does not... */
	fflush(stdout);
	fflush(stderr);

911 912 913 914 915 916
	if ((pgver = popen(cmd, "r")) == NULL)
		return FIND_EXEC_ERR;

	if (fgets(line, sizeof(line), pgver) == NULL)
		perror("fgets failure");

917
	pclose_check(pgver);
918 919 920 921 922 923 924 925 926 927 928

	if (strcmp(line, PG_VERSIONSTR) != 0)
		return FIND_WRONG_VERSION;

	return FIND_SUCCESS;
}

/*
 * Windows doesn't like relative paths to executables (other things work fine)
 * so we call its builtin function to expand them. Elsewhere this is a NOOP
 */
929
#ifdef WIN32
930 931 932 933 934
static char *
expanded_path(char *path)
{
	char		abspath[MAXPGPATH];

935
	if (_fullpath(abspath, path, sizeof(abspath)) == NULL)
936 937 938 939
	{
		perror("expanded path");
		return path;
	}
940
	canonicalize_path(abspath);
941 942
	return xstrdup(abspath);
}
943
#endif
944 945 946

/*
 * set the paths pointing to postgres
947
 *
948 949
 * look for it in the same place we found this program, or in the environment
 * path, or in the configured bindir.
950 951
 * We do it in this order because during upgrades users might move
 * their trees to backup places, so the hard-wired bindir might be inaccurate.
952
 *
953 954 955
 * XXX this needs work, as its error handling is vastly inferior to the
 * shell-script version, in particular the case where a postgres executable
 * is failing
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
 */
static int
set_paths(void)
{
	if (testpath && !self_path)
	{
		char	   *path,
				   *cursor;
		int			pathlen,
					i,
					pathsegs;
		char	  **pathbits;
		char		buf[MAXPGPATH];
		struct stat statbuf;

		path = xstrdup(getenv("PATH"));
		pathlen = strlen(path);

		for (i = 0, pathsegs = 1; i < pathlen; i++)
		{
			if (path[i] == PATHSEP)
				pathsegs++;
		}

		pathbits = (char **) xmalloc(pathsegs * sizeof(char *));
		for (i = 0, pathsegs = 0, cursor = path; i <= pathlen; i++)
		{
			if (path[i] == PATHSEP || path[i] == 0)
			{
				path[i] = 0;
				if (strlen(cursor) == 0)
				{
					/* empty path segment means current directory */
					pathbits[pathsegs] = xstrdup(".");
				}
				else
				{
993
					canonicalize_path(cursor);
994 995 996 997 998 999 1000 1001 1002
					pathbits[pathsegs] = cursor;
				}
				pathsegs++;
				cursor = path + i + 1;
			}
		}

		for (i = 0; i < pathsegs; i++)
		{
1003
			snprintf(buf, sizeof(buf), "%s/%s%s", pathbits[i], progname, EXE);
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
			if (stat(buf, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
			{
				self_path = pathbits[i];
				break;
			}
		}
	}

	if (testpath && self_path &&
		(find_postgres(expanded_path(self_path)) == 0))
	{
		/* we found postgres on out own path */
		pgpath = expanded_path(self_path);
	}
	else
	{
		/* look in the hardcoded bindir */
		int			res;
		char	   *cbindir;

		cbindir = xstrdup(bindir);
1025
		canonicalize_path(cbindir);
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
		res = find_postgres(expanded_path(cbindir));
		if (res == 0)
			pgpath = expanded_path(cbindir);
		else
			return 1;
	}

	return 0;
}

/*
 * write out the PG_VERSION file in the data dir, or its subdirectory
 * if extrapath is not NULL
 */
static void
set_short_version(char *short_version, char *extrapath)
{
	FILE	   *version_file;
	char	   *path;

	if (extrapath == NULL)
	{
		path = xmalloc(strlen(pg_data) + 12);
		sprintf(path, "%s/PG_VERSION", pg_data);
	}
	else
	{
		path = xmalloc(strlen(pg_data) + strlen(extrapath) + 13);
		sprintf(path, "%s/%s/PG_VERSION", pg_data, extrapath);
	}
	version_file = fopen(path, PG_BINARY_W);
	fprintf(version_file, "%s\n", short_version);
	fclose(version_file);
}

/*
 * set up an empty config file so we can check buffers and connections
 */
static void
set_null_conf(void)
{
	FILE	   *conf_file;
	char	   *path;

	path = xmalloc(strlen(pg_data) + 17);
	sprintf(path, "%s/postgresql.conf", pg_data);
	conf_file = fopen(path, PG_BINARY_W);
	fclose(conf_file);
}

/*
1077
 * check how many connections we can sustain
1078 1079
 */
static void
1080
test_connections(void)
1081 1082
{
	char		cmd[MAXPGPATH];
1083 1084
	static const int conns[] = {100, 50, 40, 30, 20, 10};
	static const int len = sizeof(conns) / sizeof(int);
1085 1086 1087
	int			i,
				status;

1088 1089 1090
	printf("selecting default max_connections ... ");
	fflush(stdout);

1091 1092
	for (i = 0; i < len; i++)
	{
1093 1094 1095 1096 1097 1098 1099
		snprintf(cmd, sizeof(cmd),
				 "\"%s/postgres\" -boot -x0 %s "
				 "-c shared_buffers=%d -c max_connections=%d template1 "
				 "<%s >%s 2>&1",
				 pgpath, boot_options,
				 conns[i] * 5, conns[i],
				 DEVNULL, DEVNULL);
1100 1101 1102 1103 1104 1105
		status = system(cmd);
		if (status == 0)
			break;
	}
	if (i >= len)
		i = len - 1;
1106
	n_connections = conns[i];
1107 1108

	printf("%d\n", n_connections);
1109 1110 1111
}

/*
1112
 * check how many buffers we can run with
1113 1114
 */
static void
1115
test_buffers(void)
1116 1117
{
	char		cmd[MAXPGPATH];
1118 1119 1120
	static const int bufs[] = {1000, 900, 800, 700, 600, 500,
							   400, 300, 200, 100, 50};
	static const int len = sizeof(bufs) / sizeof(int);
1121 1122 1123
	int			i,
				status;

1124 1125 1126
	printf("selecting default shared_buffers ... ");
	fflush(stdout);

1127 1128
	for (i = 0; i < len; i++)
	{
1129 1130 1131 1132 1133 1134
		snprintf(cmd, sizeof(cmd),
				 "\"%s/postgres\" -boot -x0 %s "
				 "-c shared_buffers=%d -c max_connections=%d template1 "
				 "<%s >%s 2>&1",
				 pgpath, boot_options,
				 bufs[i], n_connections,
1135
				 DEVNULL, DEVNULL);
1136 1137 1138 1139 1140 1141
		status = system(cmd);
		if (status == 0)
			break;
	}
	if (i >= len)
		i = len - 1;
1142
	n_buffers = bufs[i];
1143 1144

	printf("%d\n", n_buffers);
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
}

/*
 * set up all the config files
 */
static void
setup_config(void)
{
	char	  **conflines;
	char		repltok[100];
	char		path[MAXPGPATH];

	fputs("creating configuration files ... ", stdout);
1158
	fflush(stdout);
1159 1160 1161 1162 1163 1164 1165 1166

	/* postgresql.conf */

	conflines = readfile(conf_file);

	snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
	conflines = replace_token(conflines, "#max_connections = 100", repltok);

1167 1168 1169
	snprintf(repltok, sizeof(repltok), "shared_buffers = %d", n_buffers);
	conflines = replace_token(conflines, "#shared_buffers = 1000", repltok);

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
	snprintf(repltok, sizeof(repltok), "lc_messages = '%s'", lc_messages);
	conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);

	snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'", lc_monetary);
	conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);

	snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'", lc_numeric);

	conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);

	snprintf(repltok, sizeof(repltok), "lc_time = '%s'", lc_time);
	conflines = replace_token(conflines, "#lc_time = 'C'", repltok);

1183
	snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

	writefile(path, conflines);
	chmod(path, 0600);

	free(conflines);


	/* pg_hba.conf */

	conflines = readfile(hba_file);

#ifndef HAVE_IPV6
	conflines = replace_token(conflines,
							  "host    all         all         ::1",
							  "#host    all         all         ::1");
1199
#endif
1200

1201
	snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

	writefile(path, conflines);
	chmod(path, 0600);

	free(conflines);

	/* pg_ident.conf */

	conflines = readfile(ident_file);

1212
	snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

	writefile(path, conflines);
	chmod(path, 0600);

	free(conflines);

	check_ok();
}


/*
1224
 * run the BKI script in bootstrap mode to create template1
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
 */
static void
bootstrap_template1(char *short_version)
{
	char	   *talkargs = "";
	char	  **bki_lines;
	char		headerline[MAXPGPATH];

	PG_CMD_DECL;

	printf("creating template1 database in %s/base/1 ... ", pg_data);
1236
	fflush(stdout);
1237 1238 1239 1240 1241 1242

	if (debug)
		talkargs = "-d 5";

	bki_lines = readfile(bki_file);

1243 1244 1245 1246
	/* Check that bki file appears to be of the right version */

	snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
			 short_version);
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263

	if (strcmp(headerline, *bki_lines) != 0)
	{
		fprintf(stderr,
				"%s: input file \"%s\" does not belong to PostgreSQL %s\n"
				"Check your installation or specify the correct path "
				"using the option -L.\n",
				progname, bki_file, PG_VERSION);
		exit_nicely();

	}

	bki_lines = replace_token(bki_lines, "POSTGRES", effective_user);

	bki_lines = replace_token(bki_lines, "ENCODING", encodingid);

	/*
1264
	 * Pass correct LC_xxx environment to bootstrap.
1265
	 *
1266 1267
	 * The shell script arranged to restore the LC settings afterwards,
	 * but there doesn't seem to be any compelling reason to do that.
1268
	 */
1269
	snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1270 1271
	putenv(xstrdup(cmd));

1272
	snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1273 1274 1275 1276
	putenv(xstrdup(cmd));

	putenv("LC_ALL");

1277 1278 1279
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" -boot -x1 %s %s template1",
			 pgpath, boot_options, talkargs);
1280 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 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

	PG_CMD_OPEN;

	for (line = bki_lines; *line != NULL; line++)
	{
		PG_CMD_PUTLINE;
		free(*line);
	}

	PG_CMD_CLOSE;

	free(bki_lines);

	check_ok();
}

/*
 * set up the shadow password table
 */
static void
setup_shadow(void)
{
	char	   *pg_shadow_setup[] = {
		/*
		 * Create a trigger so that direct updates to pg_shadow will be
		 * written to the flat password/group files pg_pwd and pg_group
		 */
		"CREATE TRIGGER pg_sync_pg_pwd "
		"  AFTER INSERT OR UPDATE OR DELETE ON pg_shadow "
		"  FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
		"CREATE TRIGGER pg_sync_pg_group "
		"  AFTER INSERT OR UPDATE OR DELETE ON pg_group "
		"  FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",

		/*
		 * needs to be done before alter user, because alter user checks
		 * that pg_shadow is secure ...
		 */
		"REVOKE ALL on pg_shadow FROM public;\n",
		NULL
	};

	PG_CMD_DECL;

	fputs("initializing pg_shadow ... ", stdout);
1325
	fflush(stdout);
1326

1327 1328 1329 1330
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

	PG_CMD_OPEN;

	for (line = pg_shadow_setup; *line != NULL; line++)
		PG_CMD_PUTLINE;

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * get the superuser password if required, and call postgres to set it
 */
static void
1346
get_set_pwd(void)
1347 1348 1349
{
	PG_CMD_DECL_NOLINE;

1350 1351 1352
	char	   *pwd1,
			   *pwd2;
	char		pwdpath[MAXPGPATH];
1353 1354
	struct stat statbuf;

1355 1356 1357
	pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
	pwd2 = simple_prompt("Enter it again: ", 100, false);
	if (strcmp(pwd1, pwd2) != 0)
1358 1359 1360 1361
	{
		fprintf(stderr, "Passwords didn't match.\n");
		exit_nicely();
	}
1362
	free(pwd2);
1363

1364
	printf("setting password ... ");
1365
	fflush(stdout);
1366

1367 1368 1369 1370
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1371 1372 1373

	PG_CMD_OPEN;

1374
	if (fprintf(pg,
1375
		  "ALTER USER \"%s\" WITH PASSWORD '%s';\n", username, pwd1) < 0)
1376 1377 1378 1379 1380 1381 1382 1383
	{
		/* write failure */
		exit_nicely();
	}
	fflush(pg);

	PG_CMD_CLOSE;

1384
	snprintf(pwdpath, sizeof(pwdpath), "%s/global/pg_pwd", pg_data);
1385
	if (stat(pwdpath, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
1386 1387
	{
		fprintf(stderr,
1388 1389
				"%s: The password file was not generated. "
				"Please report this problem.\n",
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
				progname);
		exit_nicely();
	}

	check_ok();
}

/*
 * toast sys tables
 */
static void
unlimit_systables(void)
{
	char	   *systables_setup[] = {
		"ALTER TABLE pg_attrdef CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_constraint CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_database CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_description CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_group CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_proc CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_rewrite CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_shadow CREATE TOAST TABLE;\n",
		"ALTER TABLE pg_statistic CREATE TOAST TABLE;\n",
		NULL
	};

	PG_CMD_DECL;

	fputs("enabling unlimited row size for system tables ... ", stdout);
1419
	fflush(stdout);
1420

1421 1422 1423 1424
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447

	PG_CMD_OPEN;

	for (line = systables_setup; *line != NULL; line++)
		PG_CMD_PUTLINE;

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * set up pg_depend
 */
static void
setup_depend(void)
{
	char	   *pg_depend_setup[] = {
		/*
		 * Make PIN entries in pg_depend for all objects made so far in
		 * the tables that the dependency code handles.  This is overkill
		 * (the system doesn't really depend on having every last weird
		 * datatype, for instance) but generating only the minimum
1448 1449 1450 1451 1452 1453 1454
		 * required set of dependencies seems hard.
		 *
		 * Note that we deliberately do not pin the system views, which
		 * haven't been created yet.
		 *
		 * First delete any already-made entries; PINs override all else, and
		 * must be the only entries for their objects.
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
		 */
		"DELETE FROM pg_depend;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_class;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_proc;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_type;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_cast;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_constraint;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_attrdef;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_language;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_operator;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_opclass;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_rewrite;\n",
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_trigger;\n",

		/*
		 * restriction here to avoid pinning the public namespace
		 */
		"INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
		" FROM pg_namespace "
		"    WHERE nspname LIKE 'pg%';\n",
		NULL
	};

	PG_CMD_DECL;

	fputs("initializing pg_depend ... ", stdout);
1492
	fflush(stdout);
1493

1494 1495 1496 1497
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

	PG_CMD_OPEN;

	for (line = pg_depend_setup; *line != NULL; line++)
		PG_CMD_PUTLINE;

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * set up system views
 */
static void
setup_sysviews(void)
{
	PG_CMD_DECL;

	char	  **sysviews_setup;

	fputs("creating system views ... ", stdout);
1520
	fflush(stdout);
1521 1522 1523

	sysviews_setup = readfile(system_views_file);

1524 1525 1526 1527 1528 1529 1530
	/*
	 * We use -N here to avoid backslashing stuff in system_views.sql
	 */
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s -N template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552

	PG_CMD_OPEN;

	for (line = sysviews_setup; *line != NULL; line++)
	{
		PG_CMD_PUTLINE;
		free(*line);
	}

	PG_CMD_CLOSE;

	free(sysviews_setup);

	check_ok();
}

/*
 * load description data
 */
static void
setup_description(void)
{
1553 1554
	PG_CMD_DECL_NOLINE;
	int			fres;
1555 1556

	fputs("loading pg_description ... ", stdout);
1557
	fflush(stdout);
1558

1559 1560 1561 1562
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1563 1564 1565

	PG_CMD_OPEN;

1566 1567 1568 1569 1570 1571 1572 1573
	fres = fprintf(pg,
				   "CREATE TEMP TABLE tmp_pg_description ( "
				   "	objoid oid, "
				   "	classname name, "
				   "	objsubid int4, "
				   "	description text) WITHOUT OIDS;\n");
	if (fres < 0)
		exit_nicely();
1574

1575 1576 1577 1578 1579
	fres = fprintf(pg,
				   "COPY tmp_pg_description FROM '%s';\n",
				   desc_file);
	if (fres < 0)
		exit_nicely();
1580

1581 1582 1583 1584 1585 1586 1587
	fres = fprintf(pg,
				   "INSERT INTO pg_description "
				   " SELECT t.objoid, c.oid, t.objsubid, t.description "
				   "  FROM tmp_pg_description t, pg_class c "
				   "    WHERE c.relname = t.classname;\n");
	if (fres < 0)
		exit_nicely();
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * load conversion functions
 */
static void
setup_conversion(void)
{
	PG_CMD_DECL;

	char	  **conv_lines;

	fputs("creating conversions ... ", stdout);
1605
	fflush(stdout);
1606

1607 1608 1609 1610
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630

	PG_CMD_OPEN;

	conv_lines = readfile(conversion_file);
	for (line = conv_lines; *line != NULL; line++)
	{
		if (strstr(*line, "DROP CONVERSION") != *line)
			PG_CMD_PUTLINE;

		free(*line);
	}

	free(conv_lines);

	PG_CMD_CLOSE;

	check_ok();
}

/*
1631
 * Set up privileges
1632
 *
1633 1634 1635 1636
 * We set most system catalogs and built-in functions as world-accessible.
 * Some objects may require different permissions by default, so we
 * make sure we don't overwrite privilege sets that have already been
 * set (NOT NULL).
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
 */
static void
setup_privileges(void)
{
	char	   *privileges_setup[] = {
		"UPDATE pg_class "
		"  SET relacl = '{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
		"  WHERE relkind IN ('r', 'v', 'S') AND relacl IS NULL;\n",
		"UPDATE pg_proc "
		"  SET proacl = '{\"=X/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
		"  WHERE proacl IS NULL;\n",
		"UPDATE pg_language "
		"  SET lanacl = '{\"=U/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
		"  WHERE lanpltrusted;\n",
		"GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
		"GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
		NULL
	};

	PG_CMD_DECL;

	char	  **priv_lines;

1660 1661
	fputs("setting privileges on built-in objects ... ", stdout);
	fflush(stdout);
1662

1663 1664 1665 1666
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680

	PG_CMD_OPEN;

	priv_lines = replace_token(privileges_setup,
							   "$POSTGRES_SUPERUSERNAME", username);
	for (line = priv_lines; *line != NULL; line++)
		PG_CMD_PUTLINE;

	PG_CMD_CLOSE;

	check_ok();
}

/*
1681 1682
 * extract the strange version of version required for information schema
 * (09.08.0007abc)
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
 */
static void
set_info_version(void)
{
	char	   *letterversion;
	long		major = 0,
				minor = 0,
				micro = 0;
	char	   *endptr;
	char	   *vstr = xstrdup(PG_VERSION);
	char	   *ptr;

	ptr = vstr + (strlen(vstr) - 1);
	while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
		ptr--;
	letterversion = ptr + 1;
	major = strtol(vstr, &endptr, 10);
	if (*endptr)
		minor = strtol(endptr + 1, &endptr, 10);
	if (*endptr)
		micro = strtol(endptr + 1, &endptr, 10);
	snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
			 major, minor, micro, letterversion);
}

/*
 * load info schema and populate from features file
 */
static void
setup_schema(void)
{
	PG_CMD_DECL;
	char	  **lines;
	int			fres;

	fputs("creating information schema ... ", stdout);
1719
	fflush(stdout);
1720 1721 1722 1723

	lines = readfile(info_schema_file);

	/*
1724
	 * We use -N here to avoid backslashing stuff in information_schema.sql
1725
	 */
1726 1727 1728 1729
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s -N template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742

	PG_CMD_OPEN;

	for (line = lines; *line != NULL; line++)
	{
		PG_CMD_PUTLINE;
		free(*line);
	}

	free(lines);

	PG_CMD_CLOSE;

1743 1744 1745 1746
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757

	PG_CMD_OPEN;

	fres = fprintf(pg,
				   "UPDATE information_schema.sql_implementation_info "
				   "  SET character_value = '%s' "
				   "  WHERE implementation_info_name = 'DBMS VERSION';\n",
				   infoversion);
	if (fres < 0)
		exit_nicely();

1758 1759 1760 1761 1762 1763
	fres = fprintf(pg,
				   "COPY information_schema.sql_features "
				   "  (feature_id, feature_name, sub_feature_id, "
				   "  sub_feature_name, is_supported, comments) "
				   " FROM '%s';\n",
				   features_file);
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
	if (fres < 0)
		exit_nicely();

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * clean everything up in template1
 */
static void
vacuum_db(void)
{
	PG_CMD_DECL_NOLINE;

	fputs("vacuuming database template1 ... ", stdout);
1781
	fflush(stdout);
1782

1783 1784 1785 1786
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1787 1788 1789

	PG_CMD_OPEN;

1790
	if (fputs("ANALYZE;\nVACUUM FULL FREEZE;\n", pg) < 0)
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
		exit_nicely();
	fflush(pg);

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * copy template1 to template0
 */
static void
make_template0(void)
{
	char	   *template0_setup[] = {
		"CREATE DATABASE template0;\n",
		"UPDATE pg_database SET "
		"	datistemplate = 't', "
		"	datallowconn = 'f' "
		"    WHERE datname = 'template0';\n",

		/*
		 * We use the OID of template0 to determine lastsysoid
		 */
		"UPDATE pg_database SET datlastsysoid = "
		"    (SELECT oid::int4 - 1 FROM pg_database "
		"    WHERE datname = 'template0');\n",

		/*
		 * Explicitly revoke public create-schema and create-temp-table
		 * privileges in template1 and template0; else the latter would be
		 * on by default
		 */
		"REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
		"REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",

		/*
		 * Finally vacuum to clean up dead rows in pg_database
		 */
		"VACUUM FULL pg_database;\n",
		NULL
	};

	PG_CMD_DECL;

	fputs("copying template1 to template0 ... ", stdout);
1837
	fflush(stdout);
1838

1839 1840 1841 1842
	snprintf(cmd, sizeof(cmd),
			 "\"%s/postgres\" %s template1 >%s",
			 pgpath, backend_options,
			 DEVNULL);
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881

	PG_CMD_OPEN;

	for (line = template0_setup; *line; line++)
		PG_CMD_PUTLINE;

	PG_CMD_CLOSE;

	check_ok();
}


/*
 * signal handler in case we are interrupted.
 *
 * The Windows runtime docs at
 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
 * specifically forbid a number of things being done from a signal handler,
 * including IO, memory allocation and system calls, and only allow jmpbuf
 * if you are handling SIGFPE.
 *
 * I avoided doing the forbidden things by setting a flag instead of calling
 * exit_nicely() directly.
 *
 * Also note the behaviour of Windows with SIGINT, which says this:
 *	 Note	SIGINT is not supported for any Win32 application, including
 *	 Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
 *	 Win32 operating systems generate a new thread to specifically handle
 *	 that interrupt. This can cause a single-thread application such as UNIX,
 *	 to become multithreaded, resulting in unexpected behavior.
 *
 * I have no idea how to handle this. (Strange they call UNIX an application!)
 * So this will need some testing on Windows.
 */
static void
trapsig(int signum)
{
	/* handle systems that reset the handler, like Windows (grr) */
	pqsignal(signum, trapsig);
1882
	caught_signal = true;
1883 1884 1885 1886 1887 1888 1889 1890
}

/*
 * call exit_nicely() if we got a signal, or else output "ok".
 */
static void
check_ok()
{
1891 1892 1893 1894 1895 1896
	if (caught_signal)
	{
		printf("caught signal\n");
		exit_nicely();
	}
	else if (output_failed)
1897
	{
1898
		printf("failed to write to child process\n");
1899 1900 1901 1902
		exit_nicely();
	}
	else
	{
1903
		/* all seems well */
1904
		printf("ok\n");
1905 1906 1907 1908 1909
	}
}


/*
1910
 * check if given string is a valid locale specifier
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
 * based on some code given to me by Peter Eisentraut
 * (but I take responsibility for it :-)
 */
static bool
chklocale(const char *locale)
{
	bool		ret;
	int			category = LC_CTYPE;
	char	   *save;

	save = setlocale(category, NULL);
	if (!save)
		return false;			/* should not happen; */

	save = xstrdup(save);

	ret = (setlocale(category, locale) != NULL);

	setlocale(category, save);
	free(save);

	/* should we exit here? */
	if (!ret)
		fprintf(stderr, "%s: invalid locale name \"%s\"\n", progname, locale);

	return ret;
}

/*
 * set up the locale variables
 *
1942
 * assumes we have called setlocale(LC_ALL,"")
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
 */
static void
setlocales(void)
{
	/* set empty lc_* values to locale config if set */

	if (strlen(locale) > 0)
	{
		if (strlen(lc_ctype) == 0)
			lc_ctype = locale;
		if (strlen(lc_collate) == 0)
			lc_collate = locale;
		if (strlen(lc_numeric) == 0)
			lc_numeric = locale;
		if (strlen(lc_time) == 0)
			lc_time = locale;
		if (strlen(lc_monetary) == 0)
			lc_monetary = locale;
		if (strlen(lc_messages) == 0)
			lc_messages = locale;
	}

	/*
	 * override absent/invalid config settings from initdb's locale
	 * settings
	 */

	if (strlen(lc_ctype) == 0 || !chklocale(lc_ctype))
		lc_ctype = xstrdup(setlocale(LC_CTYPE, NULL));
	if (strlen(lc_collate) == 0 || !chklocale(lc_collate))
		lc_collate = xstrdup(setlocale(LC_COLLATE, NULL));
	if (strlen(lc_numeric) == 0 || !chklocale(lc_numeric))
		lc_numeric = xstrdup(setlocale(LC_NUMERIC, NULL));
	if (strlen(lc_time) == 0 || !chklocale(lc_time))
		lc_time = xstrdup(setlocale(LC_TIME, NULL));
	if (strlen(lc_monetary) == 0 || !chklocale(lc_monetary))
		lc_monetary = xstrdup(setlocale(LC_MONETARY, NULL));
	if (strlen(lc_messages) == 0 || !chklocale(lc_messages))
#ifdef LC_MESSAGES
	{
		/* when available get the current locale setting */
		lc_messages = xstrdup(setlocale(LC_MESSAGES, NULL));
	}
#else
	{
		/* when not available, get the CTYPE setting */
		lc_messages = xstrdup(setlocale(LC_CTYPE, NULL));
	}
1991
#endif
1992 1993 1994 1995 1996 1997

}

/*
 * help text data
 *
1998
 * Note: $CMDNAME is replaced by the right thing in usage()
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
 */
char	   *usage_text[] = {
	"$CMDNAME initializes a PostgreSQL database cluster.\n",
	"\n",
	"Usage:\n",
	"  $CMDNAME [OPTION]... [DATADIR]\n",
	"\n",
	"Options:\n",
	" [-D, --pgdata=]DATADIR     location for this database cluster\n",
	"  -E, --encoding=ENCODING   set default encoding for new databases\n",
	"  --locale=LOCALE           initialize database cluster with given locale\n",
	"  --lc-collate, --lc-ctype, --lc-messages=LOCALE\n",
	"  --lc-monetary, --lc-numeric, --lc-time=LOCALE\n",
	"                            initialize database cluster with given locale\n",
	"                            in the respective category (default taken from\n",
	"                            environment)\n",
	"  --no-locale               equivalent to --locale=C\n",
	"  -U, --username=NAME       database superuser name\n",
	"  -W, --pwprompt            prompt for a password for the new superuser\n",
	"  -?, --help                show this help, then exit\n",
	"  -V, --version             output version information, then exit\n",
	"\n",
	"Less commonly used options: \n",
	"  -d, --debug               generate lots of debugging output\n",
	"  -s, --show                show internal settings\n",
	"  -L DIRECTORY              where to find the input files\n",
	"  -n, --noclean             do not clean up after errors\n",
	"\n",
	"If the data directory is not specified, the environment variable PGDATA\n",
	"is used.\n",
	"\n",
	"Report bugs to <pgsql-bugs@postgresql.org>.\n",
	NULL
};


/*
 * print help text
 */
static void
usage(void)
{
	int			i;
	char	  **newtext;

	newtext = replace_token(usage_text, "$CMDNAME", progname);

	for (i = 0; newtext[i]; i++)
		fputs(newtext[i], stdout);		/* faster than printf */
}

2050

2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
int
main(int argc, char *argv[])
{
	/*
	 * options with no short version return a low integer, the rest return
	 * their short version value
	 */
	static struct option long_options[] = {
		{"pgdata", required_argument, NULL, 'D'},
		{"encoding", required_argument, NULL, 'E'},
		{"locale", required_argument, NULL, 1},
		{"lc-collate", required_argument, NULL, 2},
		{"lc-ctype", required_argument, NULL, 3},
		{"lc-monetary", required_argument, NULL, 4},
		{"lc-numeric", required_argument, NULL, 5},
		{"lc-time", required_argument, NULL, 6},
		{"lc-messages", required_argument, NULL, 7},
		{"no-locale", no_argument, NULL, 8},
		{"pwprompt", no_argument, NULL, 'W'},
		{"username", required_argument, NULL, 'U'},
		{"help", no_argument, NULL, '?'},
		{"version", no_argument, NULL, 'V'},
		{"debug", no_argument, NULL, 'd'},
		{"show", no_argument, NULL, 's'},
		{"noclean", no_argument, NULL, 'n'},
		{0, 0, 0, 0}
	};

	int			c,
				i;
	int			option_index;
	char	   *short_version;
	char	   *pgdenv;			/* PGDATA value got from sent to
								 * environment */
	char	   *subdirs[] =
	{"global", "pg_xlog", "pg_clog", "base", "base/1"};
	char	   *lastsep;
	char	   *carg0;
#if defined(__CYGWIN__) || defined(WIN32)
	char	   *exe;			/* location of exe suffix in progname */
2091
#endif
2092 2093 2094

	setlocale(LC_ALL, "");

2095
	/* parse argv[0] - detect explicit path if there was one */
2096
	carg0 = xstrdup(argv[0]);
2097
	canonicalize_path(carg0);
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109

	lastsep = strrchr(carg0, '/');
	progname = lastsep ? xstrdup(lastsep + 1) : carg0;

#if defined(__CYGWIN__) || defined(WIN32)
	if (strlen(progname) > 4 &&
		(exe = progname + (strlen(progname) - 4)) &&
		stricmp(exe, EXE) == 0)
	{
		/* strip .exe suffix, regardless of case */
		*exe = '\0';
	}
2110
#endif
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122

	if (lastsep)
	{
		self_path = carg0;
		*lastsep = '\0';
	}
	else
	{
		/* no path known to ourselves from argv[0] */
		self_path = NULL;
	}

2123
	/* process command-line options */
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152

	while (1)
	{
		/*
		 * a : as the first option char here lets us use ? as a short
		 * option
		 */
		c = getopt_long(argc, argv, ":D:E:WU:?sVdnL:",
						long_options, &option_index);

		if (c == -1)
			break;

		switch (c)
		{
			case 'D':
				pg_data = xstrdup(optarg);
				break;
			case 'E':
				encoding = xstrdup(optarg);
				break;
			case 'W':
				pwprompt = true;
				break;
			case 'U':
				username = xstrdup(optarg);
				break;
			case 'd':
				debug = true;
2153
                printf("Running in debug mode.\n");
2154 2155 2156
				break;
			case 'n':
				noclean = true;
2157
				printf("Running in noclean mode.  Mistakes will not be cleaned up.\n");
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
				break;
			case 'L':
				datadir = xstrdup(optarg);
				break;
			case 1:
				locale = xstrdup(optarg);
				break;
			case 2:
				lc_collate = xstrdup(optarg);
				break;
			case 3:
				lc_ctype = xstrdup(optarg);
				break;
			case 4:
				lc_monetary = xstrdup(optarg);
				break;
			case 5:
				lc_numeric = xstrdup(optarg);
				break;
			case 6:
				lc_time = xstrdup(optarg);
				break;
			case 7:
				lc_messages = xstrdup(optarg);
				break;
			case 8:
				locale = "C";
				break;
			case '?':
				show_help = true;
				break;
			case 's':
				show_setting = true;
				break;
			case 'V':
				show_version = true;
				break;
			default:
				show_help = true;
				printf("Unrecognized option: %c\n", c);
		}

	}

2202
	/* Non-option argument specifies data directory */
2203 2204 2205 2206 2207 2208
	if (optind < argc)
	{
		pg_data = xstrdup(argv[optind]);
		optind++;
	}

2209 2210 2211 2212 2213 2214 2215 2216 2217
	if (optind < argc)
		show_help = true;

	if (show_version)
	{
		/* hard coded name here, in case they rename executable */
		printf("initdb (PostgreSQL) %s\n", PG_VERSION);
		exit(0);
	}
2218

2219 2220 2221 2222 2223 2224 2225
	if (show_help)
	{
		usage();
		exit(0);
	}

	if (strlen(pg_data) == 0)
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
	{
		pgdenv = getenv("PGDATA");
		if (pgdenv && strlen(pgdenv))
		{
			/* PGDATA found */
			pg_data = xstrdup(pgdenv);
		}
		else
		{
			fprintf(stderr,
					"%s: no data directory specified\n"
2237 2238 2239 2240 2241
					"You must identify the directory where the data "
					"for this database system\n"
					"will reside.  Do this with either the invocation "
					"option -D or the\n"
					"environment variable PGDATA.\n",
2242
					progname);
2243
			exit(1);
2244 2245 2246
		}
	}

2247
	canonicalize_path(pg_data);
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291

	/*
	 * we have to set PGDATA for postgres rather than pass it on the
	 * commnd line to avoid dumb quoting problems on Windows, and we would
	 * expecially need quotes otherwise on Windows because paths there are
	 * most likely to have embedded spaces.
	 */
	pgdenv = xmalloc(8 + strlen(pg_data));
	sprintf(pgdenv, "PGDATA=%s", pg_data);
	putenv(pgdenv);

	if (set_paths() != 0)
	{
		fprintf(stderr,
				"The program \"postgres\" is needed by %s "
				"but was not found in \n"
				"the directory \"%s\". Check your installation.\n",
				progname, bindir);
		exit(1);
	}

	if ((short_version = get_short_version()) == NULL)
	{
		fprintf(stderr, "%s: could not get valid short version\n", progname);
		exit(1);
	}

	effective_user = get_id();
	if (!strlen(username))
		username = effective_user;

	if (strlen(encoding))
		encodingid = get_encoding_id(encoding);

	set_input(&bki_file, "postgres.bki");
	set_input(&desc_file, "postgres.description");
	set_input(&hba_file, "pg_hba.conf.sample");
	set_input(&ident_file, "pg_ident.conf.sample");
	set_input(&conf_file, "postgresql.conf.sample");
	set_input(&conversion_file, "conversion_create.sql");
	set_input(&info_schema_file, "information_schema.sql");
	set_input(&features_file, "sql_features.txt");
	set_input(&system_views_file, "system_views.sql");

2292 2293
	set_info_version();

2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
	if (show_setting || debug)
	{
		fprintf(stderr,
				"VERSION=%s\n"
				"PGDATA=%s\ndatadir=%s\nPGPATH=%s\n"
				"ENCODING=%s\nENCODINGID=%s\n"
				"POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
				"POSTGRES_DESCR=%s\nPOSTGRESQL_CONF_SAMPLE=%s\n"
				"PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
				PG_VERSION,
				pg_data, datadir, pgpath,
				encoding, encodingid,
				username, bki_file,
				desc_file, conf_file,
				hba_file, ident_file);
2309 2310
		if (show_setting)
			exit(0);
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
	}

	check_input(bki_file);
	check_input(desc_file);
	check_input(hba_file);
	check_input(ident_file);
	check_input(conf_file);
	check_input(conversion_file);
	check_input(info_schema_file);
	check_input(features_file);
	check_input(system_views_file);

2323
	printf("The files belonging to this database system will be owned "
2324 2325 2326
		   "by user \"%s\".\n"
		   "This user must also own the server process.\n\n",
		   effective_user);
2327

2328 2329 2330 2331 2332 2333 2334 2335
	setlocales();

	if (strcmp(lc_ctype, lc_collate) == 0 &&
		strcmp(lc_ctype, lc_time) == 0 &&
		strcmp(lc_ctype, lc_numeric) == 0 &&
		strcmp(lc_ctype, lc_monetary) == 0 &&
		strcmp(lc_ctype, lc_messages) == 0)
	{
2336
		printf("The database cluster will be initialized with locale %s.\n\n",
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
			   lc_ctype);
	}
	else
	{
		printf("The database cluster will be initialized with locales\n"
			   "  COLLATE:  %s\n"
			   "  CTYPE:    %s\n"
			   "  MESSAGES: %s\n"
			   "  MONETARY: %s\n"
			   "  NUMERIC:  %s\n"
2347
			   "  TIME:     %s\n\n",
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
			   lc_collate,
			   lc_ctype,
			   lc_messages,
			   lc_monetary,
			   lc_numeric,
			   lc_time);
	}

	umask(077);

	/*
	 * now we are starting to do real work, trap signals so we can clean
	 * up
	 */

	/* some of these are not valid on Windows */
#ifdef SIGHUP
	pqsignal(SIGHUP, trapsig);
2366
#endif
2367 2368
#ifdef SIGINT
	pqsignal(SIGINT, trapsig);
2369
#endif
2370 2371
#ifdef SIGQUIT
	pqsignal(SIGQUIT, trapsig);
2372
#endif
2373 2374
#ifdef SIGTERM
	pqsignal(SIGTERM, trapsig);
2375
#endif
2376

2377 2378 2379 2380 2381
	/* Ignore SIGPIPE when writing to backend, so we can clean up */
#ifdef SIGPIPE
	pqsignal(SIGPIPE, SIG_IGN);
#endif

2382
	switch (check_data_dir())
2383
	{
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
		case 0:
			/* PGDATA not there, must create it */
			printf("creating directory %s ... ",
				   pg_data);
			fflush(stdout);

			if (!mkdatadir(NULL))
				exit_nicely();
			else
				check_ok();
2394

2395 2396
			made_new_pgdata = true;
			break;
2397

2398 2399 2400 2401 2402
		case 1:
			/* Present but empty, fix permissions and use it */
			printf("fixing permissions on existing directory %s ... ",
				   pg_data);
			fflush(stdout);
2403

2404 2405 2406
			if (chmod(pg_data, 0700) != 0)
			{
				perror(pg_data);
2407
				exit_nicely();
2408 2409 2410
			}
			else
				check_ok();
2411 2412

			found_existing_pgdata = true;
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
			break;

		case 2:
			/* Present and not empty */
			fprintf(stderr,
					"%s: directory \"%s\" exists but is not empty\n"
					"If you want to create a new database system, either remove or empty\n"
					"the directory \"%s\" or run %s\n"
					"with an argument other than \"%s\".\n",
					progname, pg_data, pg_data, progname, pg_data);
2423
			exit(1);			/* no further message needed */
2424 2425 2426 2427

		default:
			/* Trouble accessing directory */
			perror(pg_data);
2428
			exit_nicely();
2429 2430
	}

2431 2432
	/* Create required subdirectories */

2433 2434 2435
	for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
	{
		printf("creating directory %s/%s ... ", pg_data, subdirs[i]);
2436
		fflush(stdout);
2437 2438 2439 2440 2441 2442 2443

		if (!mkdatadir(subdirs[i]))
			exit_nicely();
		else
			check_ok();
	}

2444
	/* Top level PG_VERSION is checked by bootstrapper, so make it first */
2445 2446
	set_short_version(short_version, NULL);

2447 2448 2449 2450 2451 2452 2453 2454
	/*
	 * Determine platform-specific config settings
	 *
	 * Use reasonable values if kernel will let us, else scale back.  Probe for
	 * max_connections first since it is subject to more constraints than
	 * shared_buffers.
	 */

2455 2456 2457
	set_null_conf();

	test_connections();
2458
	test_buffers();
2459

2460
	/* Now create all the text config files */
2461 2462
	setup_config();

2463
	/* Bootstrap template1 */
2464 2465
	bootstrap_template1(short_version);

2466
	/* Make the per-database PGVERSION for template1 only after init'ing it */
2467 2468
	set_short_version(short_version, "base/1");

2469 2470
	/* Create the stuff we don't need to use bootstrap mode for */

2471 2472
	setup_shadow();
	if (pwprompt)
2473
		get_set_pwd();
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492

	unlimit_systables();

	setup_depend();

	setup_sysviews();

	setup_description();

	setup_conversion();

	setup_privileges();

	setup_schema();

	vacuum_db();

	make_template0();

2493 2494
	printf("\nSuccess. You can now start the database server using:\n\n"
		   "    %s%s%s/postmaster -D %s%s%s\n"
2495
		   "or\n"
2496
		   "    %s%s%s/pg_ctl -D %s%s%s -l logfile start\n\n",
2497 2498
		 QUOTE_PATH, pgpath, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH,
		QUOTE_PATH, pgpath, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH);
2499 2500 2501

	return 0;
}