initdb.c 60 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
 *
 * Note:
 *	 The program has some memory leakage - it isn't worth cleaning it up.
30 31 32 33 34 35 36 37
 *
 *
 * 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.
 *
Bruce Momjian's avatar
Bruce Momjian committed
38
 * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
39
 * Portions Copyright (c) 1994, Regents of the University of California
40
 * Portions taken from FreeBSD.
41
 *
42
 * $PostgreSQL: pgsql/src/bin/initdb/initdb.c,v 1.71 2004/12/27 20:39:21 tgl Exp $
43 44 45 46 47 48 49 50 51 52 53
 *
 *-------------------------------------------------------------------------
 */

#include "postgres_fe.h"

#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <locale.h>
#include <signal.h>
54
#include <errno.h>
55
#ifdef HAVE_LANGINFO_H
Bruce Momjian's avatar
Bruce Momjian committed
56
#include <langinfo.h>
57
#endif
58 59 60

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

63
#ifndef HAVE_INT_OPTRESET
Tom Lane's avatar
Tom Lane committed
64 65
int			optreset;
#endif
66 67


Peter Eisentraut's avatar
Peter Eisentraut committed
68 69
#define _(x) gettext((x))

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

73 74 75
/*
 * these values are passed in by makefile defines
 */
Bruce Momjian's avatar
Bruce Momjian committed
76
char	   *share_path = NULL;
77 78 79 80 81 82 83 84 85 86 87 88 89

/* 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;
Bruce Momjian's avatar
Bruce Momjian committed
90 91
char	   *pwfilename = NULL;
char	   *authmethod = "";
92 93 94 95 96 97
bool		debug = false;
bool		noclean = false;
bool		show_setting = false;


/* internal vars */
98
const char *progname;
99 100 101 102 103 104 105 106 107 108 109 110 111 112
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;
113
bool		found_existing_pgdata = false;
114
char		infoversion[100];
115 116
bool		caught_signal = false;
bool		output_failed = false;
117
int			output_errno = 0;
118 119 120

/* defaults */
int			n_connections = 10;
121
int			n_buffers = 50;
122

123 124 125
/*
 * Warning messages for authentication methods
 */
Bruce Momjian's avatar
Bruce Momjian committed
126 127 128 129
char	   *authtrust_warning = \
"# CAUTION: Configuring the system for local \"trust\" authentication allows\n"
"# any local user to connect as any PostgreSQL user, including the database\n"
"# superuser. If you do not trust all your local users, use another\n"
130
"# authentication method.\n";
Bruce Momjian's avatar
Bruce Momjian committed
131
char	   *authwarning = NULL;
132

133 134 135 136 137 138 139 140 141 142
/*
 * 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";

143

144
/* path to 'initdb' binary directory */
Bruce Momjian's avatar
Bruce Momjian committed
145 146
char		bin_path[MAXPGPATH];
char		backend_exec[MAXPGPATH];
147 148 149

static void *xmalloc(size_t size);
static char *xstrdup(const char *s);
150 151
static char **replace_token(char **lines,
							const char *token, const char *replacement);
152
#ifndef HAVE_UNIX_SOCKETS
153
static char **filter_lines_with_token(char **lines, const char *token);
154
#endif
155 156
static char **readfile(char *path);
static void writefile(char *path, char **lines);
157
static FILE *popen_check(const char *command, const char *mode);
Bruce Momjian's avatar
Bruce Momjian committed
158
static int	mkdir_p(char *path, mode_t omode);
159
static void exit_nicely(void);
160
static char *get_id(void);
161
static char *get_encoding_id(char *encoding_name);
162
static char *get_short_version(void);
Bruce Momjian's avatar
Bruce Momjian committed
163
static int	check_data_dir(void);
164
static bool mkdatadir(const char *subdir);
165
static void set_input(char **dest, char *filename);
166
static void check_input(char *path);
167
static void set_short_version(char *short_version, char *extrapath);
168 169
static void set_null_conf(void);
static void test_connections(void);
170
static void test_buffers(void);
171
static void setup_config(void);
172
static void bootstrap_template1(char *short_version);
173
static void setup_shadow(void);
174
static void get_set_pwd(void);
175 176 177 178 179 180 181 182 183 184
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);
185
static void trapsig(int signum);
186
static void check_ok(void);
187
static char *escape_quotes(const char *src);
188 189 190
static bool chklocale(const char *locale);
static void setlocales(void);
static void usage(const char *progname);
191

192

193 194 195
/*
 * macros for running pipes to postgres
 */
196
#define PG_CMD_DECL		char cmd[MAXPGPATH]; FILE *cmdfd
197 198 199

#define PG_CMD_OPEN \
do { \
200 201 202
	cmdfd = popen_check(cmd, "w"); \
	if (cmdfd == NULL) \
		exit_nicely(); /* message already printed by popen_check */ \
203 204 205 206
} while (0)

#define PG_CMD_CLOSE \
do { \
207 208
	if (pclose_check(cmdfd)) \
		exit_nicely(); /* message already printed by pclose_check */ \
209 210
} while (0)

211
#define PG_CMD_PUTS(line) \
212
do { \
213 214 215 216 217 218 219 220 221 222 223 224 225 226
	if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
		output_failed = true, output_errno = errno; \
} while (0)

#define PG_CMD_PRINTF1(fmt, arg1) \
do { \
	if (fprintf(cmdfd, fmt, arg1) < 0 || fflush(cmdfd) < 0) \
		output_failed = true, output_errno = errno; \
} while (0)

#define PG_CMD_PRINTF2(fmt, arg1, arg2) \
do { \
	if (fprintf(cmdfd, fmt, arg1, arg2) < 0 || fflush(cmdfd) < 0) \
		output_failed = true, output_errno = errno; \
227
} while (0)
228

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

/*
238
 * routines to check mem allocations and fail noisily.
239
 *
240 241 242 243 244 245 246 247 248 249 250
 * 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)
	{
251
		fprintf(stderr, _("%s: out of memory\n"), progname);
252 253 254 255 256 257 258 259 260 261 262 263 264
		exit(1);
	}
	return result;
}

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

	result = strdup(s);
	if (!result)
	{
265
		fprintf(stderr, _("%s: out of memory\n"), progname);
266 267 268 269 270 271 272 273
		exit(1);
	}
	return result;
}

/*
 * make a copy of the array of lines, with token replaced by replacement
 * the first time it occurs on each line.
274
 *
275 276 277 278
 * This does most of what sed was used for in the shell script, but
 * doesn't need any regexp stuff.
 */
static char **
279
replace_token(char **lines, const char *token, const char *replacement)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
{
	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;
}

328 329 330
/*
 * make a copy of lines without any that contain the token
 *
331
 * a sort of poor man's grep -v
332
 */
333
#ifndef HAVE_UNIX_SOCKETS
334
static char **
335
filter_lines_with_token(char **lines, const char *token)
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
{
	int			numlines = 1;
	int			i, src, dst;
	char	  **result;

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

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

	for (src = 0, dst = 0; src < numlines; src++)
	{
		if (lines[src] == NULL || strstr(lines[src], token) == NULL)
			result[dst++] = lines[src];
	}

	return result;
}
#endif

356 357 358 359 360 361 362 363 364 365 366 367 368 369
/*
 * 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;

370
	if ((infile = fopen(path, "r")) == NULL)
371
	{
372 373
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, path, strerror(errno));
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 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
		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
421 422 423
 *
 * This is only used to write text files.  Use fopen "w" not PG_BINARY_W
 * so that the resulting configuration files are nicely editable on Windows.
424 425 426 427 428 429 430
 */
static void
writefile(char *path, char **lines)
{
	FILE	   *out_file;
	char	  **line;

431
	if ((out_file = fopen(path, "w")) == NULL)
432
	{
433 434
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, path, strerror(errno));
435 436 437 438 439
		exit_nicely();
	}
	for (line = lines; *line != NULL; line++)
	{
		if (fputs(*line, out_file) < 0)
440 441 442
		{
			fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
					progname, path, strerror(errno));
443
			exit_nicely();
444
		}
445 446 447
		free(*line);
	}
	if (fclose(out_file))
448 449 450
	{
		fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
				progname, path, strerror(errno));
451
		exit_nicely();
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
	}
}

/*
 * Open a subcommand with suitable error messaging
 */
static FILE *
popen_check(const char *command, const char *mode)
{
	FILE   *cmdfd;

	fflush(stdout);
	fflush(stderr);
	errno = 0;
	cmdfd = popen(command, mode);
	if (cmdfd == NULL)
		fprintf(stderr, _("%s: could not execute command \"%s\": %s\n"),
				progname, command, strerror(errno));
	return cmdfd;
471 472 473 474 475 476 477 478 479 480
}

/* 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
481
mkdir_p(char *path, mode_t omode)
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
{
	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;
		}
	}
514
#endif
515 516 517 518 519 520 521 522 523 524

	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';
525
		if (!last && p[1] == '\0')
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 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
			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);
577
	return retval;
578 579 580 581 582 583 584 585 586 587 588 589 590
}

/*
 * clean up any files we created on failure
 * if we created the data directory remove it too
 */
static void
exit_nicely(void)
{
	if (!noclean)
	{
		if (made_new_pgdata)
		{
Peter Eisentraut's avatar
Peter Eisentraut committed
591
			fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
592 593
					progname, pg_data);
			if (!rmtree(pg_data, true))
594 595
				fprintf(stderr, _("%s: failed to remove data directory\n"),
						progname);
596
		}
597
		else if (found_existing_pgdata)
598 599
		{
			fprintf(stderr,
Peter Eisentraut's avatar
Peter Eisentraut committed
600
					_("%s: removing contents of data directory \"%s\"\n"),
601 602
					progname, pg_data);
			if (!rmtree(pg_data, false))
603 604
				fprintf(stderr, _("%s: failed to remove contents of data directory\n"),
						progname);
605
		}
606
		/* otherwise died during startup, do nothing! */
607
	}
608 609
	else
	{
610 611
		if (made_new_pgdata || found_existing_pgdata)
			fprintf(stderr,
Peter Eisentraut's avatar
Peter Eisentraut committed
612
					_("%s: data directory \"%s\" not removed at user's request\n"),
613
					progname, pg_data);
614
	}
615

616 617 618 619
	exit(1);
}

/*
Peter Eisentraut's avatar
Peter Eisentraut committed
620
 * find the current user
621
 *
622
 * on unix make sure it isn't really root
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
 */
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,
Peter Eisentraut's avatar
Peter Eisentraut committed
638
				_("%s: cannot be run as root\n"
Bruce Momjian's avatar
Bruce Momjian committed
639 640 641
				  "Please log in (using, e.g., \"su\") as the "
				  "(unprivileged) user that will\n"
				  "own the server process.\n"),
642 643 644
				progname);
		exit(1);
	}
645
#endif
646 647 648 649 650 651 652 653 654 655 656 657 658

#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);
659
#endif
660 661 662 663

	return xstrdup(pw->pw_name);
}

664 665 666 667 668 669 670 671 672
static char *
encodingid_to_string(int enc)
{
	char		result[20];

	sprintf(result, "%d", enc);
	return xstrdup(result);
}

673 674 675 676 677 678 679 680 681 682 683 684
/*
 * get the encoding id for a given encoding name
 */
static char *
get_encoding_id(char *encoding_name)
{
	int			enc;

	if (encoding_name && *encoding_name)
	{
		if ((enc = pg_char_to_encoding(encoding_name)) >= 0 &&
			pg_valid_server_encoding(encoding_name) >= 0)
685
			return encodingid_to_string(enc);
686
	}
Peter Eisentraut's avatar
Peter Eisentraut committed
687
	fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
688 689 690 691
			progname, encoding_name ? encoding_name : "(null)");
	exit(1);
}

692
#if defined(HAVE_LANGINFO_H) && defined(CODESET)
693 694 695 696 697 698 699
/*
 * Checks whether the encoding selected for PostgreSQL and the
 * encoding used by the system locale match.
 */

struct encoding_match
{
Bruce Momjian's avatar
Bruce Momjian committed
700
	enum pg_enc pg_enc_code;
701 702 703 704
	char	   *system_enc_name;
};

struct encoding_match encoding_match_list[] = {
Bruce Momjian's avatar
Bruce Momjian committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
	{PG_EUC_JP, "EUC-JP"},
	{PG_EUC_JP, "eucJP"},
	{PG_EUC_JP, "IBM-eucJP"},
	{PG_EUC_JP, "sdeckanji"},

	{PG_EUC_CN, "EUC-CN"},
	{PG_EUC_CN, "eucCN"},
	{PG_EUC_CN, "IBM-eucCN"},
	{PG_EUC_CN, "GB2312"},
	{PG_EUC_CN, "dechanzi"},

	{PG_EUC_KR, "EUC-KR"},
	{PG_EUC_KR, "eucKR"},
	{PG_EUC_KR, "IBM-eucKR"},
	{PG_EUC_KR, "deckorean"},
	{PG_EUC_KR, "5601"},

	{PG_EUC_TW, "EUC-TW"},
	{PG_EUC_TW, "eucTW"},
	{PG_EUC_TW, "IBM-eucTW"},
	{PG_EUC_TW, "cns11643"},
726 727

#ifdef NOT_VERIFIED
Bruce Momjian's avatar
Bruce Momjian committed
728
	{PG_JOHAB, "???"},
729 730
#endif

Bruce Momjian's avatar
Bruce Momjian committed
731 732
	{PG_UTF8, "UTF-8"},
	{PG_UTF8, "utf8"},
733

Bruce Momjian's avatar
Bruce Momjian committed
734 735 736
	{PG_LATIN1, "ISO-8859-1"},
	{PG_LATIN1, "ISO8859-1"},
	{PG_LATIN1, "iso88591"},
737

Bruce Momjian's avatar
Bruce Momjian committed
738 739 740
	{PG_LATIN2, "ISO-8859-2"},
	{PG_LATIN2, "ISO8859-2"},
	{PG_LATIN2, "iso88592"},
741

Bruce Momjian's avatar
Bruce Momjian committed
742 743 744
	{PG_LATIN3, "ISO-8859-3"},
	{PG_LATIN3, "ISO8859-3"},
	{PG_LATIN3, "iso88593"},
745

Bruce Momjian's avatar
Bruce Momjian committed
746 747 748
	{PG_LATIN4, "ISO-8859-4"},
	{PG_LATIN4, "ISO8859-4"},
	{PG_LATIN4, "iso88594"},
749

Bruce Momjian's avatar
Bruce Momjian committed
750 751 752
	{PG_LATIN5, "ISO-8859-9"},
	{PG_LATIN5, "ISO8859-9"},
	{PG_LATIN5, "iso88599"},
753

Bruce Momjian's avatar
Bruce Momjian committed
754 755 756
	{PG_LATIN6, "ISO-8859-10"},
	{PG_LATIN6, "ISO8859-10"},
	{PG_LATIN6, "iso885910"},
757

Bruce Momjian's avatar
Bruce Momjian committed
758 759 760
	{PG_LATIN7, "ISO-8859-13"},
	{PG_LATIN7, "ISO8859-13"},
	{PG_LATIN7, "iso885913"},
761

Bruce Momjian's avatar
Bruce Momjian committed
762 763 764
	{PG_LATIN8, "ISO-8859-14"},
	{PG_LATIN8, "ISO8859-14"},
	{PG_LATIN8, "iso885914"},
765

Bruce Momjian's avatar
Bruce Momjian committed
766 767 768
	{PG_LATIN9, "ISO-8859-15"},
	{PG_LATIN9, "ISO8859-15"},
	{PG_LATIN9, "iso885915"},
769

Bruce Momjian's avatar
Bruce Momjian committed
770 771 772
	{PG_LATIN10, "ISO-8859-16"},
	{PG_LATIN10, "ISO8859-16"},
	{PG_LATIN10, "iso885916"},
773

Bruce Momjian's avatar
Bruce Momjian committed
774 775
	{PG_WIN1256, "CP1256"},
	{PG_TCVN, "CP1258"},
776
#ifdef NOT_VERIFIED
Bruce Momjian's avatar
Bruce Momjian committed
777
	{PG_WIN874, "???"},
778
#endif
Bruce Momjian's avatar
Bruce Momjian committed
779 780 781
	{PG_KOI8R, "KOI8-R"},
	{PG_WIN1251, "CP1251"},
	{PG_ALT, "CP866"},
782

Bruce Momjian's avatar
Bruce Momjian committed
783 784 785
	{PG_ISO_8859_5, "ISO-8859-5"},
	{PG_ISO_8859_5, "ISO8859-5"},
	{PG_ISO_8859_5, "iso88595"},
786

Bruce Momjian's avatar
Bruce Momjian committed
787 788 789
	{PG_ISO_8859_6, "ISO-8859-6"},
	{PG_ISO_8859_6, "ISO8859-6"},
	{PG_ISO_8859_6, "iso88596"},
790

Bruce Momjian's avatar
Bruce Momjian committed
791 792 793
	{PG_ISO_8859_7, "ISO-8859-7"},
	{PG_ISO_8859_7, "ISO8859-7"},
	{PG_ISO_8859_7, "iso88597"},
794

Bruce Momjian's avatar
Bruce Momjian committed
795 796 797
	{PG_ISO_8859_8, "ISO-8859-8"},
	{PG_ISO_8859_8, "ISO8859-8"},
	{PG_ISO_8859_8, "iso88598"},
798

Bruce Momjian's avatar
Bruce Momjian committed
799
	{PG_SQL_ASCII, NULL}		/* end marker */
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
};

static char *
get_encoding_from_locale(const char *ctype)
{
	char	   *save;
	char	   *sys;

	save = setlocale(LC_CTYPE, NULL);
	if (!save)
		return NULL;
	save = xstrdup(save);

	setlocale(LC_CTYPE, ctype);
	sys = nl_langinfo(CODESET);
	sys = xstrdup(sys);

	setlocale(LC_CTYPE, save);
	free(save);

	return sys;
}

static void
check_encodings_match(int pg_enc, const char *ctype)
{
Bruce Momjian's avatar
Bruce Momjian committed
826 827
	char	   *sys;
	int			i;
828 829 830 831 832 833

	sys = get_encoding_from_locale(ctype);

	for (i = 0; encoding_match_list[i].system_enc_name; i++)
	{
		if (pg_enc == encoding_match_list[i].pg_enc_code
Bruce Momjian's avatar
Bruce Momjian committed
834
		 && strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
835 836 837 838 839 840 841 842 843 844
		{
			free(sys);
			return;
		}
	}

	fprintf(stderr,
			_("%s: warning: encoding mismatch\n"), progname);
	fprintf(stderr,
			_("The encoding you selected (%s) and the encoding that the selected\n"
Bruce Momjian's avatar
Bruce Momjian committed
845
		   "locale uses (%s) are not known to match.  This may lead to\n"
846
			  "misbehavior in various character string processing functions.  To fix\n"
Bruce Momjian's avatar
Bruce Momjian committed
847
	   "this situation, rerun %s and either do not specify an encoding\n"
848 849 850 851 852 853 854 855 856 857
			  "explicitly, or choose a matching combination.\n"),
			pg_encoding_to_char(pg_enc), sys, progname);

	free(sys);
	return;
}

static int
find_matching_encoding(const char *ctype)
{
Bruce Momjian's avatar
Bruce Momjian committed
858 859
	char	   *sys;
	int			i;
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

	sys = get_encoding_from_locale(ctype);

	for (i = 0; encoding_match_list[i].system_enc_name; i++)
	{
		if (strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
		{
			free(sys);
			return encoding_match_list[i].pg_enc_code;
		}
	}

	free(sys);
	return -1;
}
Bruce Momjian's avatar
Bruce Momjian committed
875
#endif   /* HAVE_LANGINFO_H && CODESET */
876

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
/*
 * 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
915 916 917
 *
 * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty,
 * or -1 if trouble accessing directory
918
 */
919
static int
920 921 922 923
check_data_dir(void)
{
	DIR		   *chkdir;
	struct dirent *file;
924 925 926
	int			result = 1;

	errno = 0;
927 928 929 930

	chkdir = opendir(pg_data);

	if (!chkdir)
931
		return (errno == ENOENT) ? 0 : -1;
932 933 934 935 936 937 938 939 940 941

	while ((file = readdir(chkdir)) != NULL)
	{
		if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0)
		{
			/* skip this and parent directory */
			continue;
		}
		else
		{
942
			result = 2;			/* not empty */
943 944 945 946 947 948
			break;
		}
	}

	closedir(chkdir);

949 950 951 952
	if (errno != 0)
		result = -1;			/* some kind of I/O error? */

	return result;
953 954 955 956 957 958
}

/*
 * make the data directory (or one of its subdirectories if subdir is not NULL)
 */
static bool
959
mkdatadir(const char *subdir)
960 961 962 963 964 965 966 967 968 969 970
{
	char	   *path;

	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);

971 972 973 974 975 976 977
	if (mkdir_p(path, 0700) == 0)
		return true;

	fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
			progname, path, strerror(errno));

	return false;
978 979 980 981 982 983 984 985 986
}


/*
 * set name of given input file variable under data directory
 */
static void
set_input(char **dest, char *filename)
{
987 988
	*dest = xmalloc(strlen(share_path) + strlen(filename) + 2);
	sprintf(*dest, "%s/%s", share_path, filename);
989 990 991 992 993 994 995 996 997 998 999 1000 1001
}

/*
 * 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,
1002
				_("%s: file \"%s\" does not exist\n"
Bruce Momjian's avatar
Bruce Momjian committed
1003
		   "This means you have a corrupted installation or identified\n"
1004
				  "the wrong directory with the invocation option -L.\n"),
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
				progname, path);
		exit(1);
	}
}

/*
 * 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);
1031
	if (version_file == NULL)
1032 1033 1034
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, path, strerror(errno));
1035
		exit_nicely();
1036 1037 1038 1039 1040 1041
	}
	if (fprintf(version_file, "%s\n", short_version) < 0 ||
		fclose(version_file))
	{
		fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
				progname, path, strerror(errno));
1042
		exit_nicely();
1043
	}
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
}

/*
 * 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);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
	if (conf_file == NULL)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, path, strerror(errno));
		exit_nicely();
	}
	if (fclose(conf_file))
	{
		fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
				progname, path, strerror(errno));
1068
		exit_nicely();
1069
	}
1070 1071 1072
}

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

Peter Eisentraut's avatar
Peter Eisentraut committed
1084
	printf(_("selecting default max_connections ... "));
1085 1086
	fflush(stdout);

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

	printf("%d\n", n_connections);
1105 1106 1107
}

/*
1108
 * check how many buffers we can run with
1109 1110
 */
static void
1111
test_buffers(void)
1112 1113
{
	char		cmd[MAXPGPATH];
1114
	static const int bufs[] = {1000, 900, 800, 700, 600, 500,
Bruce Momjian's avatar
Bruce Momjian committed
1115
	400, 300, 200, 100, 50};
1116
	static const int len = sizeof(bufs) / sizeof(int);
1117 1118 1119
	int			i,
				status;

Peter Eisentraut's avatar
Peter Eisentraut committed
1120
	printf(_("selecting default shared_buffers ... "));
1121 1122
	fflush(stdout);

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

	printf("%d\n", n_buffers);
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
}

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

Peter Eisentraut's avatar
Peter Eisentraut committed
1153
	fputs(_("creating configuration files ... "), stdout);
1154
	fflush(stdout);
1155 1156 1157 1158 1159 1160 1161 1162

	/* postgresql.conf */

	conflines = readfile(conf_file);

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

1163 1164 1165
	snprintf(repltok, sizeof(repltok), "shared_buffers = %d", n_buffers);
	conflines = replace_token(conflines, "#shared_buffers = 1000", repltok);

1166 1167 1168 1169 1170
#if DEF_PGPORT != 5432
	snprintf(repltok, sizeof(repltok), "#port = %d", DEF_PGPORT);
	conflines = replace_token(conflines, "#port = 5432", repltok);
#endif

1171
	lc_messages = escape_quotes(lc_messages);
1172 1173 1174
	snprintf(repltok, sizeof(repltok), "lc_messages = '%s'", lc_messages);
	conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);

1175
	lc_monetary = escape_quotes(lc_monetary);
1176 1177 1178
	snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'", lc_monetary);
	conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);

1179
	lc_numeric = escape_quotes(lc_numeric);
1180 1181 1182
	snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'", lc_numeric);
	conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);

1183
	lc_time = escape_quotes(lc_time);
1184 1185 1186
	snprintf(repltok, sizeof(repltok), "lc_time = '%s'", lc_time);
	conflines = replace_token(conflines, "#lc_time = 'C'", repltok);

1187
	snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
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);

1199 1200
#ifndef HAVE_UNIX_SOCKETS
	conflines = filter_lines_with_token(conflines,"@remove-line-for-nolocal@");
1201
#else
1202
	conflines = replace_token(conflines,"@remove-line-for-nolocal@","");
1203 1204
#endif

1205 1206 1207 1208
#ifndef HAVE_IPV6
	conflines = replace_token(conflines,
							  "host    all         all         ::1",
							  "#host    all         all         ::1");
1209
#endif
Bruce Momjian's avatar
Bruce Momjian committed
1210

1211 1212
	/* Replace default authentication methods */
	conflines = replace_token(conflines,
Bruce Momjian's avatar
Bruce Momjian committed
1213
							  "@authmethod@",
1214
							  authmethod);
Bruce Momjian's avatar
Bruce Momjian committed
1215

1216 1217
	conflines = replace_token(conflines,
							  "@authcomment@",
Bruce Momjian's avatar
Bruce Momjian committed
1218 1219
				   strcmp(authmethod, "trust") ? "" : authtrust_warning);

1220
	snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

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

	free(conflines);

	/* pg_ident.conf */

	conflines = readfile(ident_file);

1231
	snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

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

	free(conflines);

	check_ok();
}


/*
1243
 * run the BKI script in bootstrap mode to create template1
1244 1245 1246 1247
 */
static void
bootstrap_template1(char *short_version)
{
1248 1249
	PG_CMD_DECL;
	char	  **line;
1250 1251 1252 1253
	char	   *talkargs = "";
	char	  **bki_lines;
	char		headerline[MAXPGPATH];

Peter Eisentraut's avatar
Peter Eisentraut committed
1254
	printf(_("creating template1 database in %s/base/1 ... "), pg_data);
1255
	fflush(stdout);
1256 1257 1258 1259 1260 1261

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

	bki_lines = readfile(bki_file);

1262 1263 1264 1265
	/* Check that bki file appears to be of the right version */

	snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
			 short_version);
1266 1267 1268 1269

	if (strcmp(headerline, *bki_lines) != 0)
	{
		fprintf(stderr,
Bruce Momjian's avatar
Bruce Momjian committed
1270 1271 1272
			 _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
			   "Check your installation or specify the correct path "
			   "using the option -L.\n"),
1273 1274 1275 1276 1277 1278 1279 1280 1281
				progname, bki_file, PG_VERSION);
		exit_nicely();
	}

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

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

	/*
1282
	 * Pass correct LC_xxx environment to bootstrap.
1283
	 *
Bruce Momjian's avatar
Bruce Momjian committed
1284 1285
	 * The shell script arranged to restore the LC settings afterwards, but
	 * there doesn't seem to be any compelling reason to do that.
1286
	 */
1287
	snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1288 1289
	putenv(xstrdup(cmd));

1290
	snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1291 1292
	putenv(xstrdup(cmd));

1293
	unsetenv("LC_ALL");
1294 1295

	/* Also ensure backend isn't confused by this environment var: */
1296
	unsetenv("PGCLIENTENCODING");
1297

1298
	snprintf(cmd, sizeof(cmd),
1299
			 "\"%s\" -boot -x1 %s %s template1",
1300
			 backend_exec, boot_options, talkargs);
1301 1302 1303 1304 1305

	PG_CMD_OPEN;

	for (line = bki_lines; *line != NULL; line++)
	{
1306
		PG_CMD_PUTS(*line);
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
		free(*line);
	}

	PG_CMD_CLOSE;

	free(bki_lines);

	check_ok();
}

/*
 * set up the shadow password table
 */
static void
setup_shadow(void)
{
1323 1324 1325
	PG_CMD_DECL;
	char	  **line;
	static char *pg_shadow_setup[] = {
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
		/*
		 * 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
	};

Peter Eisentraut's avatar
Peter Eisentraut committed
1345
	fputs(_("initializing pg_shadow ... "), stdout);
1346
	fflush(stdout);
1347

1348
	snprintf(cmd, sizeof(cmd),
1349
			 "\"%s\" %s template1 >%s",
1350
			 backend_exec, backend_options,
1351
			 DEVNULL);
1352 1353 1354 1355

	PG_CMD_OPEN;

	for (line = pg_shadow_setup; *line != NULL; line++)
1356
		PG_CMD_PUTS(*line);
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * get the superuser password if required, and call postgres to set it
 */
static void
1367
get_set_pwd(void)
1368
{
1369
	PG_CMD_DECL;
1370

1371 1372 1373
	char	   *pwd1,
			   *pwd2;
	char		pwdpath[MAXPGPATH];
1374 1375
	struct stat statbuf;

1376
	if (pwprompt)
1377
	{
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
		/*
		 * Read password from terminal
		 */
		pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
		pwd2 = simple_prompt("Enter it again: ", 100, false);
		if (strcmp(pwd1, pwd2) != 0)
		{
			fprintf(stderr, _("Passwords didn't match.\n"));
			exit_nicely();
		}
		free(pwd2);
1389
	}
1390 1391 1392 1393 1394 1395
	else
	{
		/*
		 * Read password from file
		 *
		 * Ideally this should insist that the file not be world-readable.
Bruce Momjian's avatar
Bruce Momjian committed
1396 1397 1398
		 * However, this option is mainly intended for use on Windows
		 * where file permissions may not exist at all, so we'll skip the
		 * paranoia for now.
1399
		 */
Bruce Momjian's avatar
Bruce Momjian committed
1400 1401 1402
		FILE	   *pwf = fopen(pwfilename, "r");
		char		pwdbuf[MAXPGPATH];
		int			i;
1403

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
		if (!pwf)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
					progname, pwfilename, strerror(errno));
			exit_nicely();
		}
		if (!fgets(pwdbuf, sizeof(pwdbuf), pwf))
		{
			fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
					progname, pwfilename, strerror(errno));
			exit_nicely();
		}
		fclose(pwf);

		i = strlen(pwdbuf);
Bruce Momjian's avatar
Bruce Momjian committed
1419
		while (i > 0 && (pwdbuf[i - 1] == '\r' || pwdbuf[i - 1] == '\n'))
1420
			pwdbuf[--i] = '\0';
Bruce Momjian's avatar
Bruce Momjian committed
1421

1422
		pwd1 = xstrdup(pwdbuf);
Bruce Momjian's avatar
Bruce Momjian committed
1423

1424
	}
Peter Eisentraut's avatar
Peter Eisentraut committed
1425
	printf(_("setting password ... "));
1426
	fflush(stdout);
1427

1428
	snprintf(cmd, sizeof(cmd),
1429
			 "\"%s\" %s template1 >%s",
1430
			 backend_exec, backend_options,
1431
			 DEVNULL);
1432 1433 1434

	PG_CMD_OPEN;

1435 1436
	PG_CMD_PRINTF2("ALTER USER \"%s\" WITH PASSWORD '%s';\n",
				   effective_user, pwd1);
1437 1438 1439

	PG_CMD_CLOSE;

1440 1441
	check_ok();

1442
	snprintf(pwdpath, sizeof(pwdpath), "%s/global/pg_pwd", pg_data);
1443
	if (stat(pwdpath, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
1444 1445
	{
		fprintf(stderr,
Peter Eisentraut's avatar
Peter Eisentraut committed
1446
				_("%s: The password file was not generated. "
Bruce Momjian's avatar
Bruce Momjian committed
1447
				  "Please report this problem.\n"),
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
				progname);
		exit_nicely();
	}
}

/*
 * toast sys tables
 */
static void
unlimit_systables(void)
{
1459 1460 1461
	PG_CMD_DECL;
	char	  **line;
	static char *systables_setup[] = {
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
		"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
	};

Peter Eisentraut's avatar
Peter Eisentraut committed
1474
	fputs(_("enabling unlimited row size for system tables ... "), stdout);
1475
	fflush(stdout);
1476

1477
	snprintf(cmd, sizeof(cmd),
1478
			 "\"%s\" %s template1 >%s",
1479
			 backend_exec, backend_options,
1480
			 DEVNULL);
1481 1482 1483 1484

	PG_CMD_OPEN;

	for (line = systables_setup; *line != NULL; line++)
1485
		PG_CMD_PUTS(*line);
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * set up pg_depend
 */
static void
setup_depend(void)
{
1498 1499 1500
	PG_CMD_DECL;
	char	  **line;
	static char *pg_depend_setup[] = {
1501 1502 1503 1504 1505
		/*
		 * 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
1506 1507 1508 1509 1510 1511 1512
		 * 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.
1513 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 1544 1545 1546
		 */
		"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
	};

Peter Eisentraut's avatar
Peter Eisentraut committed
1547
	fputs(_("initializing pg_depend ... "), stdout);
1548
	fflush(stdout);
1549

1550
	snprintf(cmd, sizeof(cmd),
1551
			 "\"%s\" %s template1 >%s",
1552
			 backend_exec, backend_options,
1553
			 DEVNULL);
1554 1555 1556 1557

	PG_CMD_OPEN;

	for (line = pg_depend_setup; *line != NULL; line++)
1558
		PG_CMD_PUTS(*line);
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * set up system views
 */
static void
setup_sysviews(void)
{
	PG_CMD_DECL;
1572
	char	  **line;
1573 1574
	char	  **sysviews_setup;

Peter Eisentraut's avatar
Peter Eisentraut committed
1575
	fputs(_("creating system views ... "), stdout);
1576
	fflush(stdout);
1577 1578 1579

	sysviews_setup = readfile(system_views_file);

1580 1581 1582 1583
	/*
	 * We use -N here to avoid backslashing stuff in system_views.sql
	 */
	snprintf(cmd, sizeof(cmd),
1584
			 "\"%s\" %s -N template1 >%s",
1585
			 backend_exec, backend_options,
1586
			 DEVNULL);
1587 1588 1589 1590 1591

	PG_CMD_OPEN;

	for (line = sysviews_setup; *line != NULL; line++)
	{
1592
		PG_CMD_PUTS(*line);
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
		free(*line);
	}

	PG_CMD_CLOSE;

	free(sysviews_setup);

	check_ok();
}

/*
 * load description data
 */
static void
setup_description(void)
{
1609
	PG_CMD_DECL;
1610

Peter Eisentraut's avatar
Peter Eisentraut committed
1611
	fputs(_("loading pg_description ... "), stdout);
1612
	fflush(stdout);
1613

1614
	snprintf(cmd, sizeof(cmd),
1615
			 "\"%s\" %s template1 >%s",
1616
			 backend_exec, backend_options,
1617
			 DEVNULL);
1618 1619 1620

	PG_CMD_OPEN;

1621 1622 1623 1624 1625
	PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_description ( "
				"	objoid oid, "
				"	classname name, "
				"	objsubid int4, "
				"	description text) WITHOUT OIDS;\n");
1626

1627
	PG_CMD_PRINTF1("COPY tmp_pg_description FROM '%s';\n",
1628
				   desc_file);
1629

1630 1631 1632 1633
	PG_CMD_PUTS("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");
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * load conversion functions
 */
static void
setup_conversion(void)
{
	PG_CMD_DECL;
1647
	char	  **line;
1648 1649
	char	  **conv_lines;

Peter Eisentraut's avatar
Peter Eisentraut committed
1650
	fputs(_("creating conversions ... "), stdout);
1651
	fflush(stdout);
1652

1653
	snprintf(cmd, sizeof(cmd),
1654
			 "\"%s\" %s template1 >%s",
1655
			 backend_exec, backend_options,
1656
			 DEVNULL);
1657 1658 1659 1660 1661 1662 1663

	PG_CMD_OPEN;

	conv_lines = readfile(conversion_file);
	for (line = conv_lines; *line != NULL; line++)
	{
		if (strstr(*line, "DROP CONVERSION") != *line)
1664
			PG_CMD_PUTS(*line);
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
		free(*line);
	}

	free(conv_lines);

	PG_CMD_CLOSE;

	check_ok();
}

/*
1676
 * Set up privileges
1677
 *
1678 1679 1680 1681
 * 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).
1682 1683 1684 1685
 */
static void
setup_privileges(void)
{
1686 1687 1688 1689
	PG_CMD_DECL;
	char	  **line;
	char	  **priv_lines;
	static char *privileges_setup[] = {
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
		"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
	};

Peter Eisentraut's avatar
Peter Eisentraut committed
1704
	fputs(_("setting privileges on built-in objects ... "), stdout);
1705
	fflush(stdout);
1706

1707
	snprintf(cmd, sizeof(cmd),
1708
			 "\"%s\" %s template1 >%s",
1709
			 backend_exec, backend_options,
1710
			 DEVNULL);
1711 1712 1713 1714

	PG_CMD_OPEN;

	priv_lines = replace_token(privileges_setup,
1715
							   "$POSTGRES_SUPERUSERNAME", effective_user);
1716
	for (line = priv_lines; *line != NULL; line++)
1717
		PG_CMD_PUTS(*line);
1718 1719 1720 1721 1722 1723 1724

	PG_CMD_CLOSE;

	check_ok();
}

/*
1725 1726
 * extract the strange version of version required for information schema
 * (09.08.0007abc)
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
 */
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;
1759
	char	  **line;
1760 1761
	char	  **lines;

Peter Eisentraut's avatar
Peter Eisentraut committed
1762
	fputs(_("creating information schema ... "), stdout);
1763
	fflush(stdout);
1764 1765 1766 1767

	lines = readfile(info_schema_file);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1768 1769
	 * We use -N here to avoid backslashing stuff in
	 * information_schema.sql
1770
	 */
1771
	snprintf(cmd, sizeof(cmd),
1772
			 "\"%s\" %s -N template1 >%s",
1773
			 backend_exec, backend_options,
1774
			 DEVNULL);
1775 1776 1777 1778 1779

	PG_CMD_OPEN;

	for (line = lines; *line != NULL; line++)
	{
1780
		PG_CMD_PUTS(*line);
1781 1782 1783 1784 1785 1786 1787
		free(*line);
	}

	free(lines);

	PG_CMD_CLOSE;

1788
	snprintf(cmd, sizeof(cmd),
1789
			 "\"%s\" %s template1 >%s",
1790
			 backend_exec, backend_options,
1791
			 DEVNULL);
1792 1793 1794

	PG_CMD_OPEN;

1795
	PG_CMD_PRINTF1("UPDATE information_schema.sql_implementation_info "
1796 1797 1798 1799
				   "  SET character_value = '%s' "
				   "  WHERE implementation_info_name = 'DBMS VERSION';\n",
				   infoversion);

1800
	PG_CMD_PRINTF1("COPY information_schema.sql_features "
1801 1802 1803 1804
				   "  (feature_id, feature_name, sub_feature_id, "
				   "  sub_feature_name, is_supported, comments) "
				   " FROM '%s';\n",
				   features_file);
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * clean everything up in template1
 */
static void
vacuum_db(void)
{
1817
	PG_CMD_DECL;
1818

Peter Eisentraut's avatar
Peter Eisentraut committed
1819
	fputs(_("vacuuming database template1 ... "), stdout);
1820
	fflush(stdout);
1821

1822
	snprintf(cmd, sizeof(cmd),
1823
			 "\"%s\" %s template1 >%s",
1824
			 backend_exec, backend_options,
1825
			 DEVNULL);
1826 1827 1828

	PG_CMD_OPEN;

1829
	PG_CMD_PUTS("ANALYZE;\nVACUUM FULL;\nVACUUM FREEZE;\n");
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841

	PG_CMD_CLOSE;

	check_ok();
}

/*
 * copy template1 to template0
 */
static void
make_template0(void)
{
1842 1843 1844
	PG_CMD_DECL;
	char	  **line;
	static char *template0_setup[] = {
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
		"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
	};

Peter Eisentraut's avatar
Peter Eisentraut committed
1873
	fputs(_("copying template1 to template0 ... "), stdout);
1874
	fflush(stdout);
1875

1876
	snprintf(cmd, sizeof(cmd),
1877
			 "\"%s\" %s template1 >%s",
1878
			 backend_exec, backend_options,
1879
			 DEVNULL);
1880 1881 1882 1883

	PG_CMD_OPEN;

	for (line = template0_setup; *line; line++)
1884
		PG_CMD_PUTS(*line);
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

	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);
1919
	caught_signal = true;
1920 1921 1922 1923 1924 1925
}

/*
 * call exit_nicely() if we got a signal, or else output "ok".
 */
static void
1926
check_ok(void)
1927
{
1928 1929
	if (caught_signal)
	{
Peter Eisentraut's avatar
Peter Eisentraut committed
1930
		printf(_("caught signal\n"));
1931
		fflush(stdout);
1932 1933 1934
		exit_nicely();
	}
	else if (output_failed)
1935
	{
1936 1937 1938
		printf(_("could not write to child process: %s\n"),
			   strerror(output_errno));
		fflush(stdout);
1939 1940 1941 1942
		exit_nicely();
	}
	else
	{
1943
		/* all seems well */
Peter Eisentraut's avatar
Peter Eisentraut committed
1944
		printf(_("ok\n"));
1945
		fflush(stdout);
1946 1947 1948
	}
}

1949
/*
1950
 * Escape any single quotes or backslashes in given string
1951
 */
1952 1953
static char *
escape_quotes(const char *src)
1954
{
1955
	int			len = strlen(src),
1956
				i, j;
1957
	char		*result = xmalloc(len * 2 + 1);
1958 1959 1960
	
	for (i = 0, j = 0; i < len; i++)
	{
1961 1962 1963
		if (src[i] == '\'' || src[i] == '\\')
			result[j++] = '\\';
		result[j++] = src[i];
1964
	}
1965 1966
	result[j] = '\0';
	return result;
1967
}
1968 1969

/*
1970
 * check if given string is a valid locale specifier
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
 */
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)
Peter Eisentraut's avatar
Peter Eisentraut committed
1992
		fprintf(stderr, _("%s: invalid locale name \"%s\"\n"), progname, locale);
1993 1994 1995 1996 1997 1998 1999

	return ret;
}

/*
 * set up the locale variables
 *
2000
 * assumes we have called setlocale(LC_ALL,"")
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
 */
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))
2039
#if defined(LC_MESSAGES) && !defined(WIN32)
2040 2041 2042 2043 2044 2045 2046 2047 2048
	{
		/* 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));
	}
2049
#endif
2050 2051 2052 2053 2054 2055 2056

}

/*
 * print help text
 */
static void
Peter Eisentraut's avatar
Peter Eisentraut committed
2057
usage(const char *progname)
2058
{
Peter Eisentraut's avatar
Peter Eisentraut committed
2059 2060 2061 2062 2063 2064 2065
	printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
	printf(_("Usage:\n"));
	printf(_("  %s [OPTION]... [DATADIR]\n"), progname);
	printf(_("\nOptions:\n"));
	printf(_(" [-D, --pgdata=]DATADIR     location for this database cluster\n"));
	printf(_("  -E, --encoding=ENCODING   set default encoding for new databases\n"));
	printf(_("  --locale=LOCALE           initialize database cluster with given locale\n"));
2066 2067 2068 2069 2070
	printf(_("  --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"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2071
	printf(_("  --no-locale               equivalent to --locale=C\n"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2072
	printf(_("  -A, --auth=METHOD         default authentication method for local connections\n"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2073 2074
	printf(_("  -U, --username=NAME       database superuser name\n"));
	printf(_("  -W, --pwprompt            prompt for a password for the new superuser\n"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2075
	printf(_("  --pwfile=FILE             read password for the new superuser from file\n"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2076 2077
	printf(_("  -?, --help                show this help, then exit\n"));
	printf(_("  -V, --version             output version information, then exit\n"));
2078
	printf(_("\nLess commonly used options:\n"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2079 2080 2081 2082
	printf(_("  -d, --debug               generate lots of debugging output\n"));
	printf(_("  -s, --show                show internal settings\n"));
	printf(_("  -L DIRECTORY              where to find the input files\n"));
	printf(_("  -n, --noclean             do not clean up after errors\n"));
2083 2084
	printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
			 "is used.\n"));
Peter Eisentraut's avatar
Peter Eisentraut committed
2085 2086
	printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
}
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105

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},
Bruce Momjian's avatar
Bruce Momjian committed
2106
		{"auth", required_argument, NULL, 'A'},
2107
		{"pwprompt", no_argument, NULL, 'W'},
2108
		{"pwfile", required_argument, NULL, 9},
2109 2110 2111 2112 2113 2114
		{"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'},
2115
		{NULL, 0, NULL, 0}
2116 2117 2118
	};

	int			c,
2119 2120
				i,
				ret;
2121 2122
	int			option_index;
	char	   *short_version;
2123
	char	   *pgdenv;			/* PGDATA value gotten from and sent to
2124
								 * environment */
2125 2126
	char		bin_dir[MAXPGPATH];
	char		*pg_data_native;
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
	static const char *subdirs[] = {
		"global",
		"pg_xlog",
		"pg_xlog/archive_status",
		"pg_clog",
		"pg_subtrans",
		"base",
		"base/1",
		"pg_tblspc"
	};
2137

2138
	progname = get_progname(argv[0]);
2139
	set_pglocale_pgservice(argv[0], "initdb");
2140

Bruce Momjian's avatar
Bruce Momjian committed
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			usage(progname);
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("initdb (PostgreSQL) " PG_VERSION);
			exit(0);
		}
	}
2154

2155
	/* process command-line options */
2156

2157
	while ((c = getopt_long(argc, argv, "dD:E:L:nU:WA:s", long_options, &option_index)) != -1)
2158 2159 2160
	{
		switch (c)
		{
2161 2162 2163
			case 'A':
				authmethod = xstrdup(optarg);
				break;
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
			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;
Bruce Momjian's avatar
Bruce Momjian committed
2178
				printf(_("Running in debug mode.\n"));
2179 2180 2181
				break;
			case 'n':
				noclean = true;
Peter Eisentraut's avatar
Peter Eisentraut committed
2182
				printf(_("Running in noclean mode.  Mistakes will not be cleaned up.\n"));
2183 2184
				break;
			case 'L':
2185
				share_path = xstrdup(optarg);
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
				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;
2211 2212 2213
			case 9:
				pwfilename = xstrdup(optarg);
				break;
2214 2215 2216 2217
			case 's':
				show_setting = true;
				break;
			default:
2218
				/* getopt_long already emitted a complaint */
2219
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
Bruce Momjian's avatar
Bruce Momjian committed
2220
						progname);
2221
				exit(1);
2222 2223 2224
		}
	}

2225
	/* Non-option argument specifies data directory */
2226 2227 2228 2229 2230 2231
	if (optind < argc)
	{
		pg_data = xstrdup(argv[optind]);
		optind++;
	}

2232 2233
	if (optind < argc)
	{
2234
		fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
Bruce Momjian's avatar
Bruce Momjian committed
2235
				progname, argv[optind + 1]);
2236 2237
		fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
				progname);
2238 2239
	}

2240 2241
	if (pwprompt && pwfilename)
	{
Peter Eisentraut's avatar
Peter Eisentraut committed
2242
		fprintf(stderr, _("%s: password prompt and password file may not be specified together\n"), progname);
2243 2244
		exit(1);
	}
Bruce Momjian's avatar
Bruce Momjian committed
2245

2246 2247
	if (authmethod == NULL || !strlen(authmethod))
	{
Peter Eisentraut's avatar
Peter Eisentraut committed
2248
		authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
Peter Eisentraut's avatar
Peter Eisentraut committed
2249
						"You can change this by editing pg_hba.conf or using the -A option the\n"
2250
						"next time you run initdb.\n");
Bruce Momjian's avatar
Bruce Momjian committed
2251
		authmethod = "trust";
2252 2253
	}

Bruce Momjian's avatar
Bruce Momjian committed
2254 2255 2256 2257 2258
	if (strcmp(authmethod, "md5") &&
		strcmp(authmethod, "ident") &&
		strncmp(authmethod, "ident ", 6) &&		/* ident with space =
												 * param */
		strcmp(authmethod, "trust") &&
2259
#ifdef USE_PAM
Bruce Momjian's avatar
Bruce Momjian committed
2260 2261
		strcmp(authmethod, "pam") &&
		strncmp(authmethod, "pam ", 4) &&		/* pam with space = param */
2262
#endif
Bruce Momjian's avatar
Bruce Momjian committed
2263 2264
		strcmp(authmethod, "crypt") &&
		strcmp(authmethod, "password")
2265
		)
Bruce Momjian's avatar
Bruce Momjian committed
2266

2267
		/*
Bruce Momjian's avatar
Bruce Momjian committed
2268 2269
		 * Kerberos methods not listed because they are not supported over
		 * local connections and are rejected in hba.c
2270 2271
		 */
	{
2272 2273
		fprintf(stderr, _("%s: unrecognized authentication method \"%s\"\n"),
				progname, authmethod);
2274 2275 2276
		exit(1);
	}

Bruce Momjian's avatar
Bruce Momjian committed
2277 2278 2279 2280
	if ((!strcmp(authmethod, "md5") ||
		 !strcmp(authmethod, "crypt") ||
		 !strcmp(authmethod, "password")) &&
		!(pwprompt || pwfilename))
2281
	{
Peter Eisentraut's avatar
Peter Eisentraut committed
2282
		fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname, authmethod);
2283 2284
		exit(1);
	}
2285

2286
	if (strlen(pg_data) == 0)
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
	{
		pgdenv = getenv("PGDATA");
		if (pgdenv && strlen(pgdenv))
		{
			/* PGDATA found */
			pg_data = xstrdup(pgdenv);
		}
		else
		{
			fprintf(stderr,
Peter Eisentraut's avatar
Peter Eisentraut committed
2297
					_("%s: no data directory specified\n"
2298 2299 2300
					  "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"),
2301
					progname);
2302
			exit(1);
2303 2304 2305
		}
	}

2306
	pg_data_native = pg_data;
2307
	canonicalize_path(pg_data);
2308 2309 2310

	/*
	 * we have to set PGDATA for postgres rather than pass it on the
Bruce Momjian's avatar
Bruce Momjian committed
2311 2312 2313
	 * command line to avoid dumb quoting problems on Windows, and we
	 * would especially need quotes otherwise on Windows because paths
	 * there are most likely to have embedded spaces.
2314 2315 2316 2317 2318
	 */
	pgdenv = xmalloc(8 + strlen(pg_data));
	sprintf(pgdenv, "PGDATA=%s", pg_data);
	putenv(pgdenv);

2319
	if ((ret = find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
2320
							   backend_exec)) < 0)
2321
	{
2322 2323 2324 2325 2326
		char full_path[MAXPGPATH];

		if (find_my_exec(argv[0], full_path) < 0)
			StrNCpy(full_path, progname, MAXPGPATH);

2327 2328
		if (ret == -1)
			fprintf(stderr,
Bruce Momjian's avatar
Bruce Momjian committed
2329
					_("The program \"postgres\" is needed by %s "
2330 2331
					  "but was not found in the\n"
					  "same directory as \"%s\".\n"
Bruce Momjian's avatar
Bruce Momjian committed
2332
					  "Check your installation.\n"),
2333
					progname, full_path);
2334 2335
		else
			fprintf(stderr,
2336 2337
					_("The program \"postgres\" was found by \"%s\"\n"
					  "but was not the same version as %s.\n"
Bruce Momjian's avatar
Bruce Momjian committed
2338
					  "Check your installation.\n"),
2339
					full_path, progname);
2340 2341 2342
		exit(1);
	}

2343
	/* store binary directory */
2344
	strcpy(bin_path, backend_exec);
2345
	*last_dir_separator(bin_path) = '\0';
2346
	canonicalize_path(bin_path);
2347 2348 2349 2350 2351 2352

	if (!share_path)
	{
		share_path = xmalloc(MAXPGPATH);
		get_share_path(backend_exec, share_path);
	}
2353 2354 2355 2356 2357
	else if (!is_absolute_path(share_path))
	{
		fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
		exit(1);
	}
Bruce Momjian's avatar
Bruce Momjian committed
2358

2359 2360
	canonicalize_path(share_path);

2361 2362
	if ((short_version = get_short_version()) == NULL)
	{
2363
		fprintf(stderr, _("%s: could not determine valid short version string\n"), progname);
2364 2365 2366
		exit(1);
	}

2367 2368 2369 2370
	if (strlen(username))
		effective_user = username;
	else
		effective_user = get_id();
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384

	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");

2385 2386
	set_info_version();

2387 2388 2389 2390
	if (show_setting || debug)
	{
		fprintf(stderr,
				"VERSION=%s\n"
2391
				"PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2392 2393 2394 2395
				"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,
2396
				pg_data, share_path, bin_path,
2397
				effective_user, bki_file,
2398 2399
				desc_file, conf_file,
				hba_file, ident_file);
2400 2401
		if (show_setting)
			exit(0);
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
	}

	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);

2414 2415
	setlocales();

Peter Eisentraut's avatar
Peter Eisentraut committed
2416
	printf(_("The files belonging to this database system will be owned "
Bruce Momjian's avatar
Bruce Momjian committed
2417 2418
			 "by user \"%s\".\n"
			 "This user must also own the server process.\n\n"),
2419
		   effective_user);
2420

2421 2422 2423 2424 2425
	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)
2426
		printf(_("The database cluster will be initialized with locale %s.\n"), lc_ctype);
2427 2428
	else
	{
Peter Eisentraut's avatar
Peter Eisentraut committed
2429
		printf(_("The database cluster will be initialized with locales\n"
Bruce Momjian's avatar
Bruce Momjian committed
2430 2431 2432 2433 2434 2435
				 "  COLLATE:  %s\n"
				 "  CTYPE:    %s\n"
				 "  MESSAGES: %s\n"
				 "  MONETARY: %s\n"
				 "  NUMERIC:  %s\n"
				 "  TIME:     %s\n"),
2436 2437 2438 2439 2440 2441 2442 2443
			   lc_collate,
			   lc_ctype,
			   lc_messages,
			   lc_monetary,
			   lc_numeric,
			   lc_time);
	}

2444
#if defined(HAVE_LANGINFO_H) && defined(CODESET)
2445 2446 2447 2448
	if (strcmp(lc_ctype, "C") != 0 && strcmp(lc_ctype, "POSIX") != 0)
	{
		if (strlen(encoding) == 0)
		{
Bruce Momjian's avatar
Bruce Momjian committed
2449 2450
			int			tmp;

2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
			tmp = find_matching_encoding(lc_ctype);
			if (tmp == -1)
			{
				fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"), progname, lc_ctype);
				fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
				exit(1);
			}
			else
			{
				encodingid = encodingid_to_string(tmp);
Bruce Momjian's avatar
Bruce Momjian committed
2462
				printf(_("The default database encoding has accordingly been set to %s.\n"),
2463 2464 2465 2466 2467 2468
					   pg_encoding_to_char(tmp));
			}
		}
		else
			check_encodings_match(atoi(encodingid), lc_ctype);
	}
Bruce Momjian's avatar
Bruce Momjian committed
2469
#endif   /* HAVE_LANGINFO_H && CODESET */
2470 2471 2472

	printf("\n");

2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
	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);
2483
#endif
2484 2485
#ifdef SIGINT
	pqsignal(SIGINT, trapsig);
2486
#endif
2487 2488
#ifdef SIGQUIT
	pqsignal(SIGQUIT, trapsig);
2489
#endif
2490 2491
#ifdef SIGTERM
	pqsignal(SIGTERM, trapsig);
2492
#endif
2493

2494 2495 2496 2497 2498
	/* Ignore SIGPIPE when writing to backend, so we can clean up */
#ifdef SIGPIPE
	pqsignal(SIGPIPE, SIG_IGN);
#endif

2499
	switch (check_data_dir())
2500
	{
2501 2502
		case 0:
			/* PGDATA not there, must create it */
Peter Eisentraut's avatar
Peter Eisentraut committed
2503
			printf(_("creating directory %s ... "),
2504 2505 2506 2507 2508 2509 2510
				   pg_data);
			fflush(stdout);

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

2512 2513
			made_new_pgdata = true;
			break;
2514

2515 2516
		case 1:
			/* Present but empty, fix permissions and use it */
Peter Eisentraut's avatar
Peter Eisentraut committed
2517
			printf(_("fixing permissions on existing directory %s ... "),
2518 2519
				   pg_data);
			fflush(stdout);
2520

2521 2522
			if (chmod(pg_data, 0700) != 0)
			{
2523
				fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
2524
						progname, pg_data, strerror(errno));
2525
				exit_nicely();
2526 2527 2528
			}
			else
				check_ok();
2529 2530

			found_existing_pgdata = true;
2531 2532 2533 2534 2535
			break;

		case 2:
			/* Present and not empty */
			fprintf(stderr,
Peter Eisentraut's avatar
Peter Eisentraut committed
2536
					_("%s: directory \"%s\" exists but is not empty\n"
Bruce Momjian's avatar
Bruce Momjian committed
2537 2538 2539
					  "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"),
2540
					progname, pg_data, pg_data, progname, pg_data);
2541
			exit(1);			/* no further message needed */
2542 2543 2544

		default:
			/* Trouble accessing directory */
2545
			fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
2546
					progname, pg_data, strerror(errno));
2547
			exit_nicely();
2548 2549
	}

2550 2551
	/* Create required subdirectories */

2552 2553
	for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
	{
Peter Eisentraut's avatar
Peter Eisentraut committed
2554
		printf(_("creating directory %s/%s ... "), pg_data, subdirs[i]);
2555
		fflush(stdout);
2556 2557 2558 2559 2560 2561 2562

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

2563
	/* Top level PG_VERSION is checked by bootstrapper, so make it first */
2564 2565
	set_short_version(short_version, NULL);

2566 2567 2568
	/*
	 * Determine platform-specific config settings
	 *
Bruce Momjian's avatar
Bruce Momjian committed
2569 2570 2571
	 * 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.
2572 2573
	 */

2574 2575 2576
	set_null_conf();

	test_connections();
2577
	test_buffers();
2578

2579
	/* Now create all the text config files */
2580 2581
	setup_config();

2582
	/* Bootstrap template1 */
2583 2584
	bootstrap_template1(short_version);

Bruce Momjian's avatar
Bruce Momjian committed
2585 2586 2587 2588
	/*
	 * Make the per-database PG_VERSION for template1 only after init'ing
	 * it
	 */
2589 2590
	set_short_version(short_version, "base/1");

2591 2592
	/* Create the stuff we don't need to use bootstrap mode for */

2593
	setup_shadow();
2594
	if (pwprompt || pwfilename)
2595
		get_set_pwd();
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614

	unlimit_systables();

	setup_depend();

	setup_sysviews();

	setup_description();

	setup_conversion();

	setup_privileges();

	setup_schema();

	vacuum_db();

	make_template0();

2615 2616 2617
	if (authwarning != NULL)
		fprintf(stderr, authwarning);

2618 2619 2620 2621
	/* Get directory specification used to start this executable */
	strcpy(bin_dir, argv[0]);
	get_parent_directory(bin_dir);
	
Peter Eisentraut's avatar
Peter Eisentraut committed
2622
	printf(_("\nSuccess. You can now start the database server using:\n\n"
2623
			 "    %s%s%s%spostmaster -D %s%s%s\n"
Bruce Momjian's avatar
Bruce Momjian committed
2624
			 "or\n"
2625 2626 2627 2628 2629
			 "    %s%s%s%spg_ctl -D %s%s%s -l logfile start\n\n"),
	  QUOTE_PATH, bin_dir, QUOTE_PATH, (strlen(bin_dir) > 0) ? DIR_SEP : "",
	  QUOTE_PATH, pg_data_native, QUOTE_PATH,
	  QUOTE_PATH, bin_dir, QUOTE_PATH, (strlen(bin_dir) > 0) ? DIR_SEP : "",
	  QUOTE_PATH, pg_data_native, QUOTE_PATH);
2630 2631 2632

	return 0;
}