1 /*-------------------------------------------------------------------------
3 * initdb --- initialize a PostgreSQL installation
5 * initdb creates (initializes) a PostgreSQL database cluster (site,
6 * instance, installation, whatever). A database cluster is a
7 * collection of PostgreSQL databases all managed by the same server.
9 * To create the database cluster, we create the directory that contains
10 * all its data, create the files that hold the global tables, create
11 * a few other control files for it, and create three databases: the
12 * template databases "template0" and "template1", and a default user
13 * database "postgres".
15 * The template databases are ordinary PostgreSQL databases. template0
16 * is never supposed to change after initdb, whereas template1 can be
17 * changed to add site-local standard data. Either one can be copied
18 * to produce a new database.
20 * For largely-historical reasons, the template1 database is the one built
21 * by the basic bootstrap process. After it is complete, template0 and
22 * the default database, postgres, are made just by copying template1.
24 * To create template1, we run the postgres (backend) program in bootstrap
25 * mode and feed it data from the postgres.bki library file. After this
26 * initial bootstrap phase, some additional stuff is created by normal
27 * SQL commands fed to a standalone backend. Some of those commands are
28 * just embedded into this program (yeah, it's ugly), but larger chunks
29 * are taken from script files.
33 * The program has some memory leakage - it isn't worth cleaning it up.
35 * This is a C implementation of the previous shell script for setting up a
36 * PostgreSQL cluster location, and should be highly compatible with it.
37 * author of C translation: Andrew Dunstan mailto:andrew@dunslane.net
39 * This code is released under the terms of the PostgreSQL License.
41 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
42 * Portions Copyright (c) 1994, Regents of the University of California
44 * src/bin/initdb/initdb.c
46 *-------------------------------------------------------------------------
49 #include "postgres_fe.h"
63 #include "common/username.h"
64 #include "mb/pg_wchar.h"
65 #include "getaddrinfo.h"
66 #include "getopt_long.h"
67 #include "miscadmin.h"
69 /* Ideally this would be in a .h file, but it hardly seems worth the trouble */
70 extern const char *select_default_timezone(const char *share_path);
72 static const char *auth_methods_host[] = {"trust", "reject", "md5", "password", "ident", "radius",
89 static const char *auth_methods_local[] = {"trust", "reject", "md5", "password", "peer", "radius",
99 * these values are passed in by makefile defines
101 static char *share_path = NULL;
103 /* values to be obtained from arguments */
104 static char *pg_data = "";
105 static char *encoding = "";
106 static char *locale = "";
107 static char *lc_collate = "";
108 static char *lc_ctype = "";
109 static char *lc_monetary = "";
110 static char *lc_numeric = "";
111 static char *lc_time = "";
112 static char *lc_messages = "";
113 static const char *default_text_search_config = "";
114 static char *username = "";
115 static bool pwprompt = false;
116 static char *pwfilename = NULL;
117 static const char *authmethodhost = "";
118 static const char *authmethodlocal = "";
119 static bool debug = false;
120 static bool noclean = false;
121 static bool do_sync = true;
122 static bool sync_only = false;
123 static bool show_setting = false;
124 static bool data_checksums = false;
125 static char *xlog_dir = "";
129 static const char *progname;
130 static char *encodingid = "0";
131 static char *bki_file;
132 static char *desc_file;
133 static char *shdesc_file;
134 static char *hba_file;
135 static char *ident_file;
136 static char *conf_file;
137 static char *conversion_file;
138 static char *dictionary_file;
139 static char *info_schema_file;
140 static char *features_file;
141 static char *system_views_file;
142 static bool made_new_pgdata = false;
143 static bool found_existing_pgdata = false;
144 static bool made_new_xlogdir = false;
145 static bool found_existing_xlogdir = false;
146 static char infoversion[100];
147 static bool caught_signal = false;
148 static bool output_failed = false;
149 static int output_errno = 0;
150 static char *pgdata_native;
153 static int n_connections = 10;
154 static int n_buffers = 50;
155 static char *dynamic_shared_memory_type = NULL;
158 * Warning messages for authentication methods
160 #define AUTHTRUST_WARNING \
161 "# CAUTION: Configuring the system for local \"trust\" authentication\n" \
162 "# allows any local user to connect as any PostgreSQL user, including\n" \
163 "# the database superuser. If you do not trust all your local users,\n" \
164 "# use another authentication method.\n"
165 static char *authwarning = NULL;
168 * Centralized knowledge of switches to pass to backend
170 * Note: we run the backend with -F (fsync disabled) and then do a single
171 * pass of fsync'ing at the end. This is faster than fsync'ing each step.
173 * Note: in the shell-script version, we also passed PGDATA as a -D switch,
174 * but here it is more convenient to pass it as an environment variable
175 * (no quoting to worry about).
177 static const char *boot_options = "-F";
178 static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true";
183 static const char *subdirs[] = {
186 "pg_xlog/archive_status",
194 "pg_multixact/members",
195 "pg_multixact/offsets",
208 /* path to 'initdb' binary directory */
209 static char bin_path[MAXPGPATH];
210 static char backend_exec[MAXPGPATH];
212 static char **replace_token(char **lines,
213 const char *token, const char *replacement);
215 #ifndef HAVE_UNIX_SOCKETS
216 static char **filter_lines_with_token(char **lines, const char *token);
218 static char **readfile(const char *path);
219 static void writefile(char *path, char **lines);
220 static void walkdir(char *path, void (*action) (char *fname, bool isdir));
221 static void pre_sync_fname(char *fname, bool isdir);
222 static void fsync_fname(char *fname, bool isdir);
223 static FILE *popen_check(const char *command, const char *mode);
224 static void exit_nicely(void);
225 static char *get_id(void);
226 static char *get_encoding_id(char *encoding_name);
227 static bool mkdatadir(const char *subdir);
228 static void set_input(char **dest, char *filename);
229 static void check_input(char *path);
230 static void write_version_file(char *extrapath);
231 static void set_null_conf(void);
232 static void test_config_settings(void);
233 static void setup_config(void);
234 static void bootstrap_template1(void);
235 static void setup_auth(void);
236 static void get_set_pwd(void);
237 static void setup_depend(void);
238 static void setup_sysviews(void);
239 static void setup_description(void);
240 static void setup_collation(void);
241 static void setup_conversion(void);
242 static void setup_dictionary(void);
243 static void setup_privileges(void);
244 static void set_info_version(void);
245 static void setup_schema(void);
246 static void load_plpgsql(void);
247 static void vacuum_db(void);
248 static void make_template0(void);
249 static void make_postgres(void);
250 static void perform_fsync(void);
251 static void trapsig(int signum);
252 static void check_ok(void);
253 static char *escape_quotes(const char *src);
254 static int locale_date_order(const char *locale);
255 static bool check_locale_name(int category, const char *locale,
257 static bool check_locale_encoding(const char *locale, int encoding);
258 static void setlocales(void);
259 static void usage(const char *progname);
260 void get_restricted_token(void);
261 void setup_pgdata(void);
262 void setup_bin_paths(const char *argv0);
263 void setup_data_file_paths(void);
264 void setup_locale_encoding(void);
265 void setup_signals(void);
266 void setup_text_search(void);
267 void create_data_directory(void);
268 void create_xlog_symlink(void);
269 void warn_on_mount_point(int error);
270 void initialize_data_directory(void);
274 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo);
279 * macros for running pipes to postgres
281 #define PG_CMD_DECL char cmd[MAXPGPATH]; FILE *cmdfd
283 #define PG_CMD_OPEN \
285 cmdfd = popen_check(cmd, "w"); \
287 exit_nicely(); /* message already printed by popen_check */ \
290 #define PG_CMD_CLOSE \
292 if (pclose_check(cmdfd)) \
293 exit_nicely(); /* message already printed by pclose_check */ \
296 #define PG_CMD_PUTS(line) \
298 if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
299 output_failed = true, output_errno = errno; \
302 #define PG_CMD_PRINTF1(fmt, arg1) \
304 if (fprintf(cmdfd, fmt, arg1) < 0 || fflush(cmdfd) < 0) \
305 output_failed = true, output_errno = errno; \
308 #define PG_CMD_PRINTF2(fmt, arg1, arg2) \
310 if (fprintf(cmdfd, fmt, arg1, arg2) < 0 || fflush(cmdfd) < 0) \
311 output_failed = true, output_errno = errno; \
314 #define PG_CMD_PRINTF3(fmt, arg1, arg2, arg3) \
316 if (fprintf(cmdfd, fmt, arg1, arg2, arg3) < 0 || fflush(cmdfd) < 0) \
317 output_failed = true, output_errno = errno; \
321 #define QUOTE_PATH ""
324 #define QUOTE_PATH "\""
329 escape_quotes(const char *src)
331 char *result = escape_single_quotes_ascii(src);
335 fprintf(stderr, _("%s: out of memory\n"), progname);
342 * make a copy of the array of lines, with token replaced by replacement
343 * the first time it occurs on each line.
345 * This does most of what sed was used for in the shell script, but
346 * doesn't need any regexp stuff.
349 replace_token(char **lines, const char *token, const char *replacement)
358 for (i = 0; lines[i]; i++)
361 result = (char **) pg_malloc(numlines * sizeof(char *));
363 toklen = strlen(token);
364 replen = strlen(replacement);
365 diff = replen - toklen;
367 for (i = 0; i < numlines; i++)
373 /* just copy pointer if NULL or no change needed */
374 if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
376 result[i] = lines[i];
380 /* if we get here a change is needed - set up new line */
382 newline = (char *) pg_malloc(strlen(lines[i]) + diff + 1);
384 pre = where - lines[i];
386 strncpy(newline, lines[i], pre);
388 strcpy(newline + pre, replacement);
390 strcpy(newline + pre + replen, lines[i] + pre + toklen);
399 * make a copy of lines without any that contain the token
401 * a sort of poor man's grep -v
403 #ifndef HAVE_UNIX_SOCKETS
405 filter_lines_with_token(char **lines, const char *token)
413 for (i = 0; lines[i]; i++)
416 result = (char **) pg_malloc(numlines * sizeof(char *));
418 for (src = 0, dst = 0; src < numlines; src++)
420 if (lines[src] == NULL || strstr(lines[src], token) == NULL)
421 result[dst++] = lines[src];
429 * get the lines from a text file
432 readfile(const char *path)
443 if ((infile = fopen(path, "r")) == NULL)
445 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
446 progname, path, strerror(errno));
450 /* pass over the file twice - the first time to size the result */
452 while ((c = fgetc(infile)) != EOF)
458 if (linelen > maxlength)
464 /* handle last line without a terminating newline (yuck) */
467 if (linelen > maxlength)
470 /* set up the result and the line buffer */
471 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
472 buffer = (char *) pg_malloc(maxlength + 1);
474 /* now reprocess the file and store the lines */
477 while (fgets(buffer, maxlength + 1, infile) != NULL && n < nlines)
478 result[n++] = pg_strdup(buffer);
488 * write an array of lines to a file
490 * This is only used to write text files. Use fopen "w" not PG_BINARY_W
491 * so that the resulting configuration files are nicely editable on Windows.
494 writefile(char *path, char **lines)
499 if ((out_file = fopen(path, "w")) == NULL)
501 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
502 progname, path, strerror(errno));
505 for (line = lines; *line != NULL; line++)
507 if (fputs(*line, out_file) < 0)
509 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
510 progname, path, strerror(errno));
515 if (fclose(out_file))
517 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
518 progname, path, strerror(errno));
524 * walkdir: recursively walk a directory, applying the action to each
525 * regular file and directory (including the named directory itself).
527 * Adapted from copydir() in copydir.c.
530 walkdir(char *path, void (*action) (char *fname, bool isdir))
533 struct dirent *direntry;
534 char subpath[MAXPGPATH];
539 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
540 progname, path, strerror(errno));
544 while (errno = 0, (direntry = readdir(dir)) != NULL)
548 if (strcmp(direntry->d_name, ".") == 0 ||
549 strcmp(direntry->d_name, "..") == 0)
552 snprintf(subpath, MAXPGPATH, "%s/%s", path, direntry->d_name);
554 if (lstat(subpath, &fst) < 0)
556 fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
557 progname, subpath, strerror(errno));
561 if (S_ISDIR(fst.st_mode))
562 walkdir(subpath, action);
563 else if (S_ISREG(fst.st_mode))
564 (*action) (subpath, false);
569 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
572 if (GetLastError() == ERROR_NO_MORE_FILES)
578 fprintf(stderr, _("%s: could not read directory \"%s\": %s\n"),
579 progname, path, strerror(errno));
586 * It's important to fsync the destination directory itself as individual
587 * file fsyncs don't guarantee that the directory entry for the file is
588 * synced. Recent versions of ext4 have made the window much wider but
589 * it's been an issue for ext3 and other filesystems in the past.
591 (*action) (path, true);
595 * Hint to the OS that it should get ready to fsync() this file.
598 pre_sync_fname(char *fname, bool isdir)
600 #if defined(HAVE_SYNC_FILE_RANGE) || \
601 (defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED))
604 fd = open(fname, O_RDONLY | PG_BINARY);
607 * Some OSs don't allow us to open directories at all (Windows returns
610 if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
615 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
616 progname, fname, strerror(errno));
621 * Prefer sync_file_range, else use posix_fadvise. We ignore any error
622 * here since this operation is only a hint anyway.
624 #if defined(HAVE_SYNC_FILE_RANGE)
625 sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WRITE);
626 #elif defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
627 posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
635 * fsync a file or directory
637 * Try to fsync directories but ignore errors that indicate the OS
638 * just doesn't allow/require fsyncing directories.
640 * Adapted from fsync_fname() in copydir.c.
643 fsync_fname(char *fname, bool isdir)
649 * Some OSs require directories to be opened read-only whereas other
650 * systems don't allow us to fsync files opened read-only; so we need both
654 fd = open(fname, O_RDWR | PG_BINARY);
656 fd = open(fname, O_RDONLY | PG_BINARY);
659 * Some OSs don't allow us to open directories at all (Windows returns
662 if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
667 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
668 progname, fname, strerror(errno));
672 returncode = fsync(fd);
674 /* Some OSs don't allow us to fsync directories at all */
675 if (returncode != 0 && isdir && errno == EBADF)
683 fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
684 progname, fname, strerror(errno));
692 * Open a subcommand with suitable error messaging
695 popen_check(const char *command, const char *mode)
702 cmdfd = popen(command, mode);
704 fprintf(stderr, _("%s: could not execute command \"%s\": %s\n"),
705 progname, command, strerror(errno));
710 * clean up any files we created on failure
711 * if we created the data directory remove it too
720 fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
722 if (!rmtree(pg_data, true))
723 fprintf(stderr, _("%s: failed to remove data directory\n"),
726 else if (found_existing_pgdata)
729 _("%s: removing contents of data directory \"%s\"\n"),
731 if (!rmtree(pg_data, false))
732 fprintf(stderr, _("%s: failed to remove contents of data directory\n"),
736 if (made_new_xlogdir)
738 fprintf(stderr, _("%s: removing transaction log directory \"%s\"\n"),
740 if (!rmtree(xlog_dir, true))
741 fprintf(stderr, _("%s: failed to remove transaction log directory\n"),
744 else if (found_existing_xlogdir)
747 _("%s: removing contents of transaction log directory \"%s\"\n"),
749 if (!rmtree(xlog_dir, false))
750 fprintf(stderr, _("%s: failed to remove contents of transaction log directory\n"),
753 /* otherwise died during startup, do nothing! */
757 if (made_new_pgdata || found_existing_pgdata)
759 _("%s: data directory \"%s\" not removed at user's request\n"),
762 if (made_new_xlogdir || found_existing_xlogdir)
764 _("%s: transaction log directory \"%s\" not removed at user's request\n"),
772 * find the current user
774 * on unix make sure it isn't root
779 const char *username;
782 if (geteuid() == 0) /* 0 is root's uid */
785 _("%s: cannot be run as root\n"
786 "Please log in (using, e.g., \"su\") as the "
787 "(unprivileged) user that will\n"
788 "own the server process.\n"),
794 username = get_user_name_or_exit(progname);
796 return pg_strdup(username);
800 encodingid_to_string(int enc)
804 sprintf(result, "%d", enc);
805 return pg_strdup(result);
809 * get the encoding id for a given encoding name
812 get_encoding_id(char *encoding_name)
816 if (encoding_name && *encoding_name)
818 if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
819 return encodingid_to_string(enc);
821 fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
822 progname, encoding_name ? encoding_name : "(null)");
827 * Support for determining the best default text search configuration.
828 * We key this off the first part of LC_CTYPE (ie, the language name).
830 struct tsearch_config_match
832 const char *tsconfname;
833 const char *langname;
836 static const struct tsearch_config_match tsearch_config_languages[] =
839 {"danish", "Danish"},
843 {"english", "POSIX"},
845 {"english", "English"},
847 {"finnish", "Finnish"},
849 {"french", "French"},
851 {"german", "German"},
853 {"hungarian", "Hungarian"},
855 {"italian", "Italian"},
857 {"norwegian", "Norwegian"},
858 {"portuguese", "pt"},
859 {"portuguese", "Portuguese"},
862 {"russian", "Russian"},
864 {"spanish", "Spanish"},
866 {"swedish", "Swedish"},
868 {"turkish", "Turkish"},
869 {NULL, NULL} /* end marker */
873 * Look for a text search configuration matching lc_ctype, and return its
874 * name; return NULL if no match.
877 find_matching_ts_config(const char *lc_type)
884 * Convert lc_ctype to a language name by stripping everything after an
885 * underscore (usual case) or a hyphen (Windows "locale name"; see
886 * comments at IsoLocaleName()).
888 * XXX Should ' ' be a stop character? This would select "norwegian" for
889 * the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
890 * should also accept the "nn" and "nb" Unix locales.
892 * Just for paranoia, we also stop at '.' or '@'.
895 langname = pg_strdup("");
898 ptr = langname = pg_strdup(lc_type);
900 *ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
905 for (i = 0; tsearch_config_languages[i].tsconfname; i++)
907 if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
910 return tsearch_config_languages[i].tsconfname;
920 * make the data directory (or one of its subdirectories if subdir is not NULL)
923 mkdatadir(const char *subdir)
928 path = psprintf("%s/%s", pg_data, subdir);
930 path = pg_strdup(pg_data);
932 if (pg_mkdir_p(path, S_IRWXU) == 0)
935 fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
936 progname, path, strerror(errno));
943 * set name of given input file variable under data directory
946 set_input(char **dest, char *filename)
948 *dest = psprintf("%s/%s", share_path, filename);
952 * check that given input file exists
955 check_input(char *path)
959 if (stat(path, &statbuf) != 0)
964 _("%s: file \"%s\" does not exist\n"), progname, path);
966 _("This might mean you have a corrupted installation or identified\n"
967 "the wrong directory with the invocation option -L.\n"));
972 _("%s: could not access file \"%s\": %s\n"), progname, path,
975 _("This might mean you have a corrupted installation or identified\n"
976 "the wrong directory with the invocation option -L.\n"));
980 if (!S_ISREG(statbuf.st_mode))
983 _("%s: file \"%s\" is not a regular file\n"), progname, path);
985 _("This might mean you have a corrupted installation or identified\n"
986 "the wrong directory with the invocation option -L.\n"));
992 * write out the PG_VERSION file in the data dir, or its subdirectory
993 * if extrapath is not NULL
996 write_version_file(char *extrapath)
1001 if (extrapath == NULL)
1002 path = psprintf("%s/PG_VERSION", pg_data);
1004 path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
1006 if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
1008 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1009 progname, path, strerror(errno));
1012 if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
1013 fclose(version_file))
1015 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
1016 progname, path, strerror(errno));
1023 * set up an empty config file so we can check config settings by launching
1032 path = psprintf("%s/postgresql.conf", pg_data);
1033 conf_file = fopen(path, PG_BINARY_W);
1034 if (conf_file == NULL)
1036 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1037 progname, path, strerror(errno));
1040 if (fclose(conf_file))
1042 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
1043 progname, path, strerror(errno));
1050 * Determine which dynamic shared memory implementation should be used on
1051 * this platform. POSIX shared memory is preferable because the default
1052 * allocation limits are much higher than the limits for System V on most
1053 * systems that support both, but the fact that a platform has shm_open
1054 * doesn't guarantee that that call will succeed when attempted. So, we
1055 * attempt to reproduce what the postmaster will do when allocating a POSIX
1056 * segment in dsm_impl.c; if it doesn't work, we assume it won't work for
1057 * the postmaster either, and configure the cluster for System V shared
1061 choose_dsm_implementation(void)
1063 #ifdef HAVE_SHM_OPEN
1073 snprintf(name, 64, "/PostgreSQL.%u", handle);
1074 if ((fd = shm_open(name, O_CREAT | O_RDWR | O_EXCL, 0600)) != -1)
1080 if (errno != EEXIST)
1094 * Determine platform-specific config settings
1096 * Use reasonable values if kernel will let us, else scale back. Probe
1097 * for max_connections first since it is subject to more constraints than
1101 test_config_settings(void)
1104 * This macro defines the minimum shared_buffers we want for a given
1105 * max_connections value. The arrays show the settings to try.
1107 #define MIN_BUFS_FOR_CONNS(nconns) ((nconns) * 10)
1109 static const int trial_conns[] = {
1110 100, 50, 40, 30, 20, 10
1112 static const int trial_bufs[] = {
1113 16384, 8192, 4096, 3584, 3072, 2560, 2048, 1536,
1114 1000, 900, 800, 700, 600, 500,
1115 400, 300, 200, 100, 50
1118 char cmd[MAXPGPATH];
1119 const int connslen = sizeof(trial_conns) / sizeof(int);
1120 const int bufslen = sizeof(trial_bufs) / sizeof(int);
1128 printf(_("selecting default max_connections ... "));
1131 for (i = 0; i < connslen; i++)
1133 test_conns = trial_conns[i];
1134 test_buffs = MIN_BUFS_FOR_CONNS(test_conns);
1136 snprintf(cmd, sizeof(cmd),
1137 SYSTEMQUOTE "\"%s\" --boot -x0 %s "
1138 "-c max_connections=%d "
1139 "-c shared_buffers=%d "
1140 "-c dynamic_shared_memory_type=none "
1141 "< \"%s\" > \"%s\" 2>&1" SYSTEMQUOTE,
1142 backend_exec, boot_options,
1143 test_conns, test_buffs,
1145 status = system(cmd);
1148 ok_buffers = test_buffs;
1154 n_connections = trial_conns[i];
1156 printf("%d\n", n_connections);
1158 printf(_("selecting default shared_buffers ... "));
1161 for (i = 0; i < bufslen; i++)
1163 /* Use same amount of memory, independent of BLCKSZ */
1164 test_buffs = (trial_bufs[i] * 8192) / BLCKSZ;
1165 if (test_buffs <= ok_buffers)
1167 test_buffs = ok_buffers;
1171 snprintf(cmd, sizeof(cmd),
1172 SYSTEMQUOTE "\"%s\" --boot -x0 %s "
1173 "-c max_connections=%d "
1174 "-c shared_buffers=%d "
1175 "-c dynamic_shared_memory_type=none "
1176 "< \"%s\" > \"%s\" 2>&1" SYSTEMQUOTE,
1177 backend_exec, boot_options,
1178 n_connections, test_buffs,
1180 status = system(cmd);
1184 n_buffers = test_buffs;
1186 if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1187 printf("%dMB\n", (n_buffers * (BLCKSZ / 1024)) / 1024);
1189 printf("%dkB\n", n_buffers * (BLCKSZ / 1024));
1191 printf(_("selecting dynamic shared memory implementation ... "));
1193 dynamic_shared_memory_type = choose_dsm_implementation();
1194 printf("%s\n", dynamic_shared_memory_type);
1198 * set up all the config files
1204 char repltok[MAXPGPATH];
1205 char path[MAXPGPATH];
1206 const char *default_timezone;
1207 char *autoconflines[3];
1209 fputs(_("creating configuration files ... "), stdout);
1212 /* postgresql.conf */
1214 conflines = readfile(conf_file);
1216 snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1217 conflines = replace_token(conflines, "#max_connections = 100", repltok);
1219 if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1220 snprintf(repltok, sizeof(repltok), "shared_buffers = %dMB",
1221 (n_buffers * (BLCKSZ / 1024)) / 1024);
1223 snprintf(repltok, sizeof(repltok), "shared_buffers = %dkB",
1224 n_buffers * (BLCKSZ / 1024));
1225 conflines = replace_token(conflines, "#shared_buffers = 32MB", repltok);
1227 #ifdef HAVE_UNIX_SOCKETS
1228 snprintf(repltok, sizeof(repltok), "#unix_socket_directories = '%s'",
1229 DEFAULT_PGSOCKET_DIR);
1231 snprintf(repltok, sizeof(repltok), "#unix_socket_directories = ''");
1233 conflines = replace_token(conflines, "#unix_socket_directories = '/tmp'",
1236 #if DEF_PGPORT != 5432
1237 snprintf(repltok, sizeof(repltok), "#port = %d", DEF_PGPORT);
1238 conflines = replace_token(conflines, "#port = 5432", repltok);
1241 snprintf(repltok, sizeof(repltok), "lc_messages = '%s'",
1242 escape_quotes(lc_messages));
1243 conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1245 snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'",
1246 escape_quotes(lc_monetary));
1247 conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1249 snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'",
1250 escape_quotes(lc_numeric));
1251 conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1253 snprintf(repltok, sizeof(repltok), "lc_time = '%s'",
1254 escape_quotes(lc_time));
1255 conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1257 switch (locale_date_order(lc_time))
1260 strcpy(repltok, "datestyle = 'iso, ymd'");
1263 strcpy(repltok, "datestyle = 'iso, dmy'");
1267 strcpy(repltok, "datestyle = 'iso, mdy'");
1270 conflines = replace_token(conflines, "#datestyle = 'iso, mdy'", repltok);
1272 snprintf(repltok, sizeof(repltok),
1273 "default_text_search_config = 'pg_catalog.%s'",
1274 escape_quotes(default_text_search_config));
1275 conflines = replace_token(conflines,
1276 "#default_text_search_config = 'pg_catalog.simple'",
1279 default_timezone = select_default_timezone(share_path);
1280 if (default_timezone)
1282 snprintf(repltok, sizeof(repltok), "timezone = '%s'",
1283 escape_quotes(default_timezone));
1284 conflines = replace_token(conflines, "#timezone = 'GMT'", repltok);
1285 snprintf(repltok, sizeof(repltok), "log_timezone = '%s'",
1286 escape_quotes(default_timezone));
1287 conflines = replace_token(conflines, "#log_timezone = 'GMT'", repltok);
1290 snprintf(repltok, sizeof(repltok), "dynamic_shared_memory_type = %s",
1291 dynamic_shared_memory_type);
1292 conflines = replace_token(conflines, "#dynamic_shared_memory_type = posix",
1295 snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1297 writefile(path, conflines);
1298 if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1300 fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1301 progname, path, strerror(errno));
1306 * create the automatic configuration file to store the configuration
1307 * parameters set by ALTER SYSTEM command. The parameters present in this
1308 * file will override the value of parameters that exists before parse of
1311 autoconflines[0] = pg_strdup("# Do not edit this file manually!\n");
1312 autoconflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
1313 autoconflines[2] = NULL;
1315 sprintf(path, "%s/%s", pg_data, PG_AUTOCONF_FILENAME);
1317 writefile(path, autoconflines);
1318 if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1320 fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1321 progname, path, strerror(errno));
1330 conflines = readfile(hba_file);
1332 #ifndef HAVE_UNIX_SOCKETS
1333 conflines = filter_lines_with_token(conflines, "@remove-line-for-nolocal@");
1335 conflines = replace_token(conflines, "@remove-line-for-nolocal@", "");
1341 * Probe to see if there is really any platform support for IPv6, and
1342 * comment out the relevant pg_hba line if not. This avoids runtime
1343 * warnings if getaddrinfo doesn't actually cope with IPv6. Particularly
1344 * useful on Windows, where executables built on a machine with IPv6 may
1345 * have to run on a machine without.
1348 struct addrinfo *gai_result;
1349 struct addrinfo hints;
1353 /* need to call WSAStartup before calling getaddrinfo */
1356 err = WSAStartup(MAKEWORD(2, 2), &wsaData);
1359 /* for best results, this code should match parse_hba() */
1360 hints.ai_flags = AI_NUMERICHOST;
1361 hints.ai_family = PF_UNSPEC;
1362 hints.ai_socktype = 0;
1363 hints.ai_protocol = 0;
1364 hints.ai_addrlen = 0;
1365 hints.ai_canonname = NULL;
1366 hints.ai_addr = NULL;
1367 hints.ai_next = NULL;
1370 getaddrinfo("::1", NULL, &hints, &gai_result) != 0)
1371 conflines = replace_token(conflines,
1373 "#host all all ::1");
1375 #else /* !HAVE_IPV6 */
1376 /* If we didn't compile IPV6 support at all, always comment it out */
1377 conflines = replace_token(conflines,
1379 "#host all all ::1");
1380 #endif /* HAVE_IPV6 */
1382 /* Replace default authentication methods */
1383 conflines = replace_token(conflines,
1386 conflines = replace_token(conflines,
1387 "@authmethodlocal@",
1390 conflines = replace_token(conflines,
1392 (strcmp(authmethodlocal, "trust") == 0 || strcmp(authmethodhost, "trust") == 0) ? AUTHTRUST_WARNING : "");
1394 /* Replace username for replication */
1395 conflines = replace_token(conflines,
1396 "@default_username@",
1399 snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1401 writefile(path, conflines);
1402 if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1404 fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1405 progname, path, strerror(errno));
1413 conflines = readfile(ident_file);
1415 snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1417 writefile(path, conflines);
1418 if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1420 fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1421 progname, path, strerror(errno));
1432 * run the BKI script in bootstrap mode to create template1
1435 bootstrap_template1(void)
1439 char *talkargs = "";
1441 char headerline[MAXPGPATH];
1444 printf(_("creating template1 database in %s/base/1 ... "), pg_data);
1450 bki_lines = readfile(bki_file);
1452 /* Check that bki file appears to be of the right version */
1454 snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1457 if (strcmp(headerline, *bki_lines) != 0)
1460 _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
1461 "Check your installation or specify the correct path "
1462 "using the option -L.\n"),
1463 progname, bki_file, PG_VERSION);
1467 /* Substitute for various symbols used in the BKI file */
1469 sprintf(buf, "%d", NAMEDATALEN);
1470 bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
1472 sprintf(buf, "%d", (int) sizeof(Pointer));
1473 bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
1475 bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
1476 (sizeof(Pointer) == 4) ? "i" : "d");
1478 bki_lines = replace_token(bki_lines, "FLOAT4PASSBYVAL",
1479 FLOAT4PASSBYVAL ? "true" : "false");
1481 bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
1482 FLOAT8PASSBYVAL ? "true" : "false");
1484 bki_lines = replace_token(bki_lines, "POSTGRES", escape_quotes(username));
1486 bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
1488 bki_lines = replace_token(bki_lines, "LC_COLLATE", escape_quotes(lc_collate));
1490 bki_lines = replace_token(bki_lines, "LC_CTYPE", escape_quotes(lc_ctype));
1493 * Pass correct LC_xxx environment to bootstrap.
1495 * The shell script arranged to restore the LC settings afterwards, but
1496 * there doesn't seem to be any compelling reason to do that.
1498 snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1499 putenv(pg_strdup(cmd));
1501 snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1502 putenv(pg_strdup(cmd));
1506 /* Also ensure backend isn't confused by this environment var: */
1507 unsetenv("PGCLIENTENCODING");
1509 snprintf(cmd, sizeof(cmd),
1510 "\"%s\" --boot -x1 %s %s %s",
1512 data_checksums ? "-k" : "",
1513 boot_options, talkargs);
1517 for (line = bki_lines; *line != NULL; line++)
1531 * set up the shadow password table
1538 static const char *pg_authid_setup[] = {
1540 * The authid table shouldn't be readable except through views, to
1541 * ensure passwords are not publicly visible.
1543 "REVOKE ALL on pg_authid FROM public;\n",
1547 fputs(_("initializing pg_authid ... "), stdout);
1550 snprintf(cmd, sizeof(cmd),
1551 "\"%s\" %s template1 >%s",
1552 backend_exec, backend_options,
1557 for (line = pg_authid_setup; *line != NULL; line++)
1566 * get the superuser password if required, and call postgres to set it
1579 * Read password from terminal
1581 pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
1582 pwd2 = simple_prompt("Enter it again: ", 100, false);
1583 if (strcmp(pwd1, pwd2) != 0)
1585 fprintf(stderr, _("Passwords didn't match.\n"));
1593 * Read password from file
1595 * Ideally this should insist that the file not be world-readable.
1596 * However, this option is mainly intended for use on Windows where
1597 * file permissions may not exist at all, so we'll skip the paranoia
1600 FILE *pwf = fopen(pwfilename, "r");
1601 char pwdbuf[MAXPGPATH];
1606 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1607 progname, pwfilename, strerror(errno));
1610 if (!fgets(pwdbuf, sizeof(pwdbuf), pwf))
1612 fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
1613 progname, pwfilename, strerror(errno));
1619 while (i > 0 && (pwdbuf[i - 1] == '\r' || pwdbuf[i - 1] == '\n'))
1622 pwd1 = pg_strdup(pwdbuf);
1625 printf(_("setting password ... "));
1628 snprintf(cmd, sizeof(cmd),
1629 "\"%s\" %s template1 >%s",
1630 backend_exec, backend_options,
1635 PG_CMD_PRINTF2("ALTER USER \"%s\" WITH PASSWORD E'%s';\n",
1636 username, escape_quotes(pwd1));
1638 /* MM: pwd1 is no longer needed, freeing it */
1654 static const char *pg_depend_setup[] = {
1656 * Make PIN entries in pg_depend for all objects made so far in the
1657 * tables that the dependency code handles. This is overkill (the
1658 * system doesn't really depend on having every last weird datatype,
1659 * for instance) but generating only the minimum required set of
1660 * dependencies seems hard.
1662 * Note that we deliberately do not pin the system views, which
1663 * haven't been created yet. Also, no conversions, databases, or
1664 * tablespaces are pinned.
1666 * First delete any already-made entries; PINs override all else, and
1667 * must be the only entries for their objects.
1669 "DELETE FROM pg_depend;\n",
1670 "VACUUM pg_depend;\n",
1671 "DELETE FROM pg_shdepend;\n",
1672 "VACUUM pg_shdepend;\n",
1674 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1675 " FROM pg_class;\n",
1676 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1678 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1680 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1682 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1683 " FROM pg_constraint;\n",
1684 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1685 " FROM pg_attrdef;\n",
1686 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1687 " FROM pg_language;\n",
1688 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1689 " FROM pg_operator;\n",
1690 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1691 " FROM pg_opclass;\n",
1692 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1693 " FROM pg_opfamily;\n",
1694 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1696 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1697 " FROM pg_amproc;\n",
1698 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1699 " FROM pg_rewrite;\n",
1700 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1701 " FROM pg_trigger;\n",
1704 * restriction here to avoid pinning the public namespace
1706 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1707 " FROM pg_namespace "
1708 " WHERE nspname LIKE 'pg%';\n",
1710 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1711 " FROM pg_ts_parser;\n",
1712 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1713 " FROM pg_ts_dict;\n",
1714 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1715 " FROM pg_ts_template;\n",
1716 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1717 " FROM pg_ts_config;\n",
1718 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1719 " FROM pg_collation;\n",
1720 "INSERT INTO pg_shdepend SELECT 0,0,0,0, tableoid,oid, 'p' "
1721 " FROM pg_authid;\n",
1725 fputs(_("initializing dependencies ... "), stdout);
1728 snprintf(cmd, sizeof(cmd),
1729 "\"%s\" %s template1 >%s",
1730 backend_exec, backend_options,
1735 for (line = pg_depend_setup; *line != NULL; line++)
1744 * set up system views
1747 setup_sysviews(void)
1751 char **sysviews_setup;
1753 fputs(_("creating system views ... "), stdout);
1756 sysviews_setup = readfile(system_views_file);
1759 * We use -j here to avoid backslashing stuff in system_views.sql
1761 snprintf(cmd, sizeof(cmd),
1762 "\"%s\" %s -j template1 >%s",
1763 backend_exec, backend_options,
1768 for (line = sysviews_setup; *line != NULL; line++)
1776 free(sysviews_setup);
1782 * load description data
1785 setup_description(void)
1789 fputs(_("loading system objects' descriptions ... "), stdout);
1792 snprintf(cmd, sizeof(cmd),
1793 "\"%s\" %s template1 >%s",
1794 backend_exec, backend_options,
1799 PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_description ( "
1803 " description text) WITHOUT OIDS;\n");
1805 PG_CMD_PRINTF1("COPY tmp_pg_description FROM E'%s';\n",
1806 escape_quotes(desc_file));
1808 PG_CMD_PUTS("INSERT INTO pg_description "
1809 " SELECT t.objoid, c.oid, t.objsubid, t.description "
1810 " FROM tmp_pg_description t, pg_class c "
1811 " WHERE c.relname = t.classname;\n");
1813 PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_shdescription ( "
1816 " description text) WITHOUT OIDS;\n");
1818 PG_CMD_PRINTF1("COPY tmp_pg_shdescription FROM E'%s';\n",
1819 escape_quotes(shdesc_file));
1821 PG_CMD_PUTS("INSERT INTO pg_shdescription "
1822 " SELECT t.objoid, c.oid, t.description "
1823 " FROM tmp_pg_shdescription t, pg_class c "
1824 " WHERE c.relname = t.classname;\n");
1826 /* Create default descriptions for operator implementation functions */
1827 PG_CMD_PUTS("WITH funcdescs AS ( "
1828 "SELECT p.oid as p_oid, oprname, "
1829 "coalesce(obj_description(o.oid, 'pg_operator'),'') as opdesc "
1830 "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
1831 "INSERT INTO pg_description "
1832 " SELECT p_oid, 'pg_proc'::regclass, 0, "
1833 " 'implementation of ' || oprname || ' operator' "
1835 " WHERE opdesc NOT LIKE 'deprecated%' AND "
1836 " NOT EXISTS (SELECT 1 FROM pg_description "
1837 " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass);\n");
1844 #ifdef HAVE_LOCALE_T
1846 * "Normalize" a locale name, stripping off encoding tags such as
1847 * ".utf8" (e.g., "en_US.utf8" -> "en_US", but "br_FR.iso885915@euro"
1848 * -> "br_FR@euro"). Return true if a new, different name was
1852 normalize_locale_name(char *new, const char *old)
1855 const char *o = old;
1856 bool changed = false;
1862 /* skip over encoding tag such as ".utf8" or ".UTF-8" */
1864 while ((*o >= 'A' && *o <= 'Z')
1865 || (*o >= 'a' && *o <= 'z')
1866 || (*o >= '0' && *o <= '9')
1878 #endif /* HAVE_LOCALE_T */
1881 * populate pg_collation
1884 setup_collation(void)
1886 #if defined(HAVE_LOCALE_T) && !defined(WIN32)
1888 FILE *locale_a_handle;
1889 char localebuf[NAMEDATALEN]; /* we assume ASCII so this is fine */
1895 fputs(_("creating collations ... "), stdout);
1898 #if defined(HAVE_LOCALE_T) && !defined(WIN32)
1899 snprintf(cmd, sizeof(cmd),
1900 "\"%s\" %s template1 >%s",
1901 backend_exec, backend_options,
1904 locale_a_handle = popen_check("locale -a", "r");
1905 if (!locale_a_handle)
1906 return; /* complaint already printed */
1910 PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_collation ( "
1913 " encoding int) WITHOUT OIDS;\n");
1915 while (fgets(localebuf, sizeof(localebuf), locale_a_handle))
1920 char *quoted_locale;
1921 char alias[NAMEDATALEN];
1923 len = strlen(localebuf);
1925 if (len == 0 || localebuf[len - 1] != '\n')
1928 fprintf(stderr, _("%s: locale name too long, skipped: \"%s\"\n"),
1929 progname, localebuf);
1932 localebuf[len - 1] = '\0';
1935 * Some systems have locale names that don't consist entirely of ASCII
1936 * letters (such as "bokmål" or "français"). This is
1937 * pretty silly, since we need the locale itself to interpret the
1938 * non-ASCII characters. We can't do much with those, so we filter
1942 for (i = 0; i < len; i++)
1944 if (IS_HIGHBIT_SET(localebuf[i]))
1953 fprintf(stderr, _("%s: locale name has non-ASCII characters, skipped: \"%s\"\n"),
1954 progname, localebuf);
1958 enc = pg_get_encoding_from_locale(localebuf, debug);
1961 /* error message printed by pg_get_encoding_from_locale() */
1964 if (!PG_VALID_BE_ENCODING(enc))
1965 continue; /* ignore locales for client-only encodings */
1966 if (enc == PG_SQL_ASCII)
1967 continue; /* C/POSIX are already in the catalog */
1971 quoted_locale = escape_quotes(localebuf);
1973 PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n",
1974 quoted_locale, quoted_locale, enc);
1977 * Generate aliases such as "en_US" in addition to "en_US.utf8" for
1978 * ease of use. Note that collation names are unique per encoding
1979 * only, so this doesn't clash with "en_US" for LATIN1, say.
1981 if (normalize_locale_name(alias, localebuf))
1983 char *quoted_alias = escape_quotes(alias);
1985 PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n",
1986 quoted_alias, quoted_locale, enc);
1989 free(quoted_locale);
1992 /* Add an SQL-standard name */
1993 PG_CMD_PRINTF1("INSERT INTO tmp_pg_collation VALUES ('ucs_basic', 'C', %d);\n", PG_UTF8);
1996 * When copying collations to the final location, eliminate aliases that
1997 * conflict with an existing locale name for the same encoding. For
1998 * example, "br_FR.iso88591" is normalized to "br_FR", both for encoding
1999 * LATIN1. But the unnormalized locale "br_FR" already exists for LATIN1.
2000 * Prefer the alias that matches the OS locale name, else the first locale
2001 * name by sort order (arbitrary choice to be deterministic).
2003 * Also, eliminate any aliases that conflict with pg_collation's
2004 * hard-wired entries for "C" etc.
2006 PG_CMD_PUTS("INSERT INTO pg_collation (collname, collnamespace, collowner, collencoding, collcollate, collctype) "
2007 " SELECT DISTINCT ON (collname, encoding)"
2009 " (SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog') AS collnamespace, "
2010 " (SELECT relowner FROM pg_class WHERE relname = 'pg_collation') AS collowner, "
2011 " encoding, locale, locale "
2012 " FROM tmp_pg_collation"
2013 " WHERE NOT EXISTS (SELECT 1 FROM pg_collation WHERE collname = tmp_pg_collation.collname)"
2014 " ORDER BY collname, encoding, (collname = locale) DESC, locale;\n");
2016 pclose(locale_a_handle);
2020 if (count == 0 && !debug)
2022 printf(_("No usable system locales were found.\n"));
2023 printf(_("Use the option \"--debug\" to see details.\n"));
2025 #else /* not HAVE_LOCALE_T && not WIN32 */
2026 printf(_("not supported on this platform\n"));
2028 #endif /* not HAVE_LOCALE_T && not WIN32 */
2032 * load conversion functions
2035 setup_conversion(void)
2041 fputs(_("creating conversions ... "), stdout);
2044 snprintf(cmd, sizeof(cmd),
2045 "\"%s\" %s template1 >%s",
2046 backend_exec, backend_options,
2051 conv_lines = readfile(conversion_file);
2052 for (line = conv_lines; *line != NULL; line++)
2054 if (strstr(*line, "DROP CONVERSION") != *line)
2067 * load extra dictionaries (Snowball stemmers)
2070 setup_dictionary(void)
2076 fputs(_("creating dictionaries ... "), stdout);
2080 * We use -j here to avoid backslashing stuff
2082 snprintf(cmd, sizeof(cmd),
2083 "\"%s\" %s -j template1 >%s",
2084 backend_exec, backend_options,
2089 conv_lines = readfile(dictionary_file);
2090 for (line = conv_lines; *line != NULL; line++)
2106 * We mark most system catalogs as world-readable. We don't currently have
2107 * to touch functions, languages, or databases, because their default
2108 * permissions are OK.
2110 * Some objects may require different permissions by default, so we
2111 * make sure we don't overwrite privilege sets that have already been
2115 setup_privileges(void)
2120 static char *privileges_setup[] = {
2122 " SET relacl = E'{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
2123 " WHERE relkind IN ('r', 'v', 'm', 'S') AND relacl IS NULL;\n",
2124 "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
2125 "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
2126 "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n",
2130 fputs(_("setting privileges on built-in objects ... "), stdout);
2133 snprintf(cmd, sizeof(cmd),
2134 "\"%s\" %s template1 >%s",
2135 backend_exec, backend_options,
2140 priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
2141 escape_quotes(username));
2142 for (line = priv_lines; *line != NULL; line++)
2151 * extract the strange version of version required for information schema
2155 set_info_version(void)
2157 char *letterversion;
2162 char *vstr = pg_strdup(PG_VERSION);
2165 ptr = vstr + (strlen(vstr) - 1);
2166 while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
2168 letterversion = ptr + 1;
2169 major = strtol(vstr, &endptr, 10);
2171 minor = strtol(endptr + 1, &endptr, 10);
2173 micro = strtol(endptr + 1, &endptr, 10);
2174 snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
2175 major, minor, micro, letterversion);
2179 * load info schema and populate from features file
2188 fputs(_("creating information schema ... "), stdout);
2191 lines = readfile(info_schema_file);
2194 * We use -j here to avoid backslashing stuff in information_schema.sql
2196 snprintf(cmd, sizeof(cmd),
2197 "\"%s\" %s -j template1 >%s",
2198 backend_exec, backend_options,
2203 for (line = lines; *line != NULL; line++)
2213 snprintf(cmd, sizeof(cmd),
2214 "\"%s\" %s template1 >%s",
2215 backend_exec, backend_options,
2220 PG_CMD_PRINTF1("UPDATE information_schema.sql_implementation_info "
2221 " SET character_value = '%s' "
2222 " WHERE implementation_info_name = 'DBMS VERSION';\n",
2225 PG_CMD_PRINTF1("COPY information_schema.sql_features "
2226 " (feature_id, feature_name, sub_feature_id, "
2227 " sub_feature_name, is_supported, comments) "
2229 escape_quotes(features_file));
2237 * load PL/pgsql server-side language
2244 fputs(_("loading PL/pgSQL server-side language ... "), stdout);
2247 snprintf(cmd, sizeof(cmd),
2248 "\"%s\" %s template1 >%s",
2249 backend_exec, backend_options,
2254 PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n");
2262 * clean everything up in template1
2269 fputs(_("vacuuming database template1 ... "), stdout);
2272 snprintf(cmd, sizeof(cmd),
2273 "\"%s\" %s template1 >%s",
2274 backend_exec, backend_options,
2279 PG_CMD_PUTS("ANALYZE;\nVACUUM FULL;\nVACUUM FREEZE;\n");
2287 * copy template1 to template0
2290 make_template0(void)
2294 static const char *template0_setup[] = {
2295 "CREATE DATABASE template0;\n",
2296 "UPDATE pg_database SET "
2297 " datistemplate = 't', "
2298 " datallowconn = 'f' "
2299 " WHERE datname = 'template0';\n",
2302 * We use the OID of template0 to determine lastsysoid
2304 "UPDATE pg_database SET datlastsysoid = "
2305 " (SELECT oid FROM pg_database "
2306 " WHERE datname = 'template0');\n",
2309 * Explicitly revoke public create-schema and create-temp-table
2310 * privileges in template1 and template0; else the latter would be on
2313 "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
2314 "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",
2316 "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n",
2319 * Finally vacuum to clean up dead rows in pg_database
2321 "VACUUM FULL pg_database;\n",
2325 fputs(_("copying template1 to template0 ... "), stdout);
2328 snprintf(cmd, sizeof(cmd),
2329 "\"%s\" %s template1 >%s",
2330 backend_exec, backend_options,
2335 for (line = template0_setup; *line; line++)
2344 * copy template1 to postgres
2351 static const char *postgres_setup[] = {
2352 "CREATE DATABASE postgres;\n",
2353 "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n",
2357 fputs(_("copying template1 to postgres ... "), stdout);
2360 snprintf(cmd, sizeof(cmd),
2361 "\"%s\" %s template1 >%s",
2362 backend_exec, backend_options,
2367 for (line = postgres_setup; *line; line++)
2376 * fsync everything down to disk
2381 char pdir[MAXPGPATH];
2383 fputs(_("syncing data to disk ... "), stdout);
2387 * We need to name the parent of PGDATA. get_parent_directory() isn't
2388 * enough here, because it can result in an empty string.
2390 snprintf(pdir, MAXPGPATH, "%s/..", pg_data);
2391 canonicalize_path(pdir);
2394 * Hint to the OS so that we're going to fsync each of these files soon.
2397 /* first the parent of the PGDATA directory */
2398 pre_sync_fname(pdir, true);
2400 /* then recursively through the directory */
2401 walkdir(pg_data, pre_sync_fname);
2404 * Now, do the fsync()s in the same order.
2407 /* first the parent of the PGDATA directory */
2408 fsync_fname(pdir, true);
2410 /* then recursively through the directory */
2411 walkdir(pg_data, fsync_fname);
2418 * signal handler in case we are interrupted.
2420 * The Windows runtime docs at
2421 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
2422 * specifically forbid a number of things being done from a signal handler,
2423 * including IO, memory allocation and system calls, and only allow jmpbuf
2424 * if you are handling SIGFPE.
2426 * I avoided doing the forbidden things by setting a flag instead of calling
2427 * exit_nicely() directly.
2429 * Also note the behaviour of Windows with SIGINT, which says this:
2430 * Note SIGINT is not supported for any Win32 application, including
2431 * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
2432 * Win32 operating systems generate a new thread to specifically handle
2433 * that interrupt. This can cause a single-thread application such as UNIX,
2434 * to become multithreaded, resulting in unexpected behavior.
2436 * I have no idea how to handle this. (Strange they call UNIX an application!)
2437 * So this will need some testing on Windows.
2442 /* handle systems that reset the handler, like Windows (grr) */
2443 pqsignal(signum, trapsig);
2444 caught_signal = true;
2448 * call exit_nicely() if we got a signal, or else output "ok".
2455 printf(_("caught signal\n"));
2459 else if (output_failed)
2461 printf(_("could not write to child process: %s\n"),
2462 strerror(output_errno));
2468 /* all seems well */
2474 /* Hack to suppress a warning about %x from some versions of gcc */
2475 static inline size_t
2476 my_strftime(char *s, size_t max, const char *fmt, const struct tm * tm)
2478 return strftime(s, max, fmt, tm);
2482 * Determine likely date order from locale
2485 locale_date_order(const char *locale)
2496 result = DATEORDER_MDY; /* default */
2498 save = setlocale(LC_TIME, NULL);
2501 save = pg_strdup(save);
2503 setlocale(LC_TIME, locale);
2505 memset(&testtime, 0, sizeof(testtime));
2506 testtime.tm_mday = 22;
2507 testtime.tm_mon = 10; /* November, should come out as "11" */
2508 testtime.tm_year = 133; /* 2033 */
2510 res = my_strftime(buf, sizeof(buf), "%x", &testtime);
2512 setlocale(LC_TIME, save);
2518 posM = strstr(buf, "11");
2519 posD = strstr(buf, "22");
2520 posY = strstr(buf, "33");
2522 if (!posM || !posD || !posY)
2525 if (posY < posM && posM < posD)
2526 result = DATEORDER_YMD;
2527 else if (posD < posM)
2528 result = DATEORDER_DMY;
2530 result = DATEORDER_MDY;
2536 * Is the locale name valid for the locale category?
2538 * If successful, and canonname isn't NULL, a malloc'd copy of the locale's
2539 * canonical name is stored there. This is especially useful for figuring out
2540 * what locale name "" means (ie, the environment value). (Actually,
2541 * it seems that on most implementations that's the only thing it's good for;
2542 * we could wish that setlocale gave back a canonically spelled version of
2543 * the locale name, but typically it doesn't.)
2545 * this should match the backend's check_locale() function
2548 check_locale_name(int category, const char *locale, char **canonname)
2554 *canonname = NULL; /* in case of failure */
2556 save = setlocale(category, NULL);
2558 return false; /* won't happen, we hope */
2560 /* save may be pointing at a modifiable scratch variable, so copy it. */
2561 save = pg_strdup(save);
2563 /* set the locale with setlocale, to see if it accepts it. */
2564 res = setlocale(category, locale);
2566 /* save canonical name if requested. */
2567 if (res && canonname)
2568 *canonname = pg_strdup(res);
2570 /* restore old value. */
2571 if (!setlocale(category, save))
2572 fprintf(stderr, _("%s: failed to restore old locale \"%s\"\n"),
2576 /* should we exit here? */
2578 fprintf(stderr, _("%s: invalid locale name \"%s\"\n"),
2581 return (res != NULL);
2585 * check if the chosen encoding matches the encoding required by the locale
2587 * this should match the similar check in the backend createdb() function
2590 check_locale_encoding(const char *locale, int user_enc)
2594 locale_enc = pg_get_encoding_from_locale(locale, true);
2596 /* See notes in createdb() to understand these tests */
2597 if (!(locale_enc == user_enc ||
2598 locale_enc == PG_SQL_ASCII ||
2601 user_enc == PG_UTF8 ||
2603 user_enc == PG_SQL_ASCII))
2605 fprintf(stderr, _("%s: encoding mismatch\n"), progname);
2607 _("The encoding you selected (%s) and the encoding that the\n"
2608 "selected locale uses (%s) do not match. This would lead to\n"
2609 "misbehavior in various character string processing functions.\n"
2610 "Rerun %s and either do not specify an encoding explicitly,\n"
2611 "or choose a matching combination.\n"),
2612 pg_encoding_to_char(user_enc),
2613 pg_encoding_to_char(locale_enc),
2621 * set up the locale variables
2623 * assumes we have called setlocale(LC_ALL, "") -- see set_pglocale_pgservice
2630 /* set empty lc_* values to locale config if set */
2632 if (strlen(locale) > 0)
2634 if (strlen(lc_ctype) == 0)
2636 if (strlen(lc_collate) == 0)
2637 lc_collate = locale;
2638 if (strlen(lc_numeric) == 0)
2639 lc_numeric = locale;
2640 if (strlen(lc_time) == 0)
2642 if (strlen(lc_monetary) == 0)
2643 lc_monetary = locale;
2644 if (strlen(lc_messages) == 0)
2645 lc_messages = locale;
2649 * canonicalize locale names, and override any missing/invalid values from
2650 * our current environment
2653 if (check_locale_name(LC_CTYPE, lc_ctype, &canonname))
2654 lc_ctype = canonname;
2656 lc_ctype = pg_strdup(setlocale(LC_CTYPE, NULL));
2657 if (check_locale_name(LC_COLLATE, lc_collate, &canonname))
2658 lc_collate = canonname;
2660 lc_collate = pg_strdup(setlocale(LC_COLLATE, NULL));
2661 if (check_locale_name(LC_NUMERIC, lc_numeric, &canonname))
2662 lc_numeric = canonname;
2664 lc_numeric = pg_strdup(setlocale(LC_NUMERIC, NULL));
2665 if (check_locale_name(LC_TIME, lc_time, &canonname))
2666 lc_time = canonname;
2668 lc_time = pg_strdup(setlocale(LC_TIME, NULL));
2669 if (check_locale_name(LC_MONETARY, lc_monetary, &canonname))
2670 lc_monetary = canonname;
2672 lc_monetary = pg_strdup(setlocale(LC_MONETARY, NULL));
2673 #if defined(LC_MESSAGES) && !defined(WIN32)
2674 if (check_locale_name(LC_MESSAGES, lc_messages, &canonname))
2675 lc_messages = canonname;
2677 lc_messages = pg_strdup(setlocale(LC_MESSAGES, NULL));
2679 /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2680 if (check_locale_name(LC_CTYPE, lc_messages, &canonname))
2681 lc_messages = canonname;
2683 lc_messages = pg_strdup(setlocale(LC_CTYPE, NULL));
2688 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
2690 /* Windows API define missing from some versions of MingW headers */
2691 #ifndef DISABLE_MAX_PRIVILEGE
2692 #define DISABLE_MAX_PRIVILEGE 0x1
2696 * Create a restricted token and execute the specified process with it.
2698 * Returns 0 on failure, non-zero on success, same as CreateProcess().
2700 * On NT4, or any other system not containing the required functions, will
2701 * NOT execute anything.
2704 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo)
2709 HANDLE restrictedToken;
2710 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
2711 SID_AND_ATTRIBUTES dropSids[2];
2712 __CreateRestrictedToken _CreateRestrictedToken = NULL;
2713 HANDLE Advapi32Handle;
2715 ZeroMemory(&si, sizeof(si));
2718 Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
2719 if (Advapi32Handle != NULL)
2721 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
2724 if (_CreateRestrictedToken == NULL)
2726 fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
2727 if (Advapi32Handle != NULL)
2728 FreeLibrary(Advapi32Handle);
2732 /* Open the current token to use as a base for the restricted one */
2733 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
2735 fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError());
2739 /* Allocate list of SIDs to remove */
2740 ZeroMemory(&dropSids, sizeof(dropSids));
2741 if (!AllocateAndInitializeSid(&NtAuthority, 2,
2742 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
2743 0, &dropSids[0].Sid) ||
2744 !AllocateAndInitializeSid(&NtAuthority, 2,
2745 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
2746 0, &dropSids[1].Sid))
2748 fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError());
2752 b = _CreateRestrictedToken(origToken,
2753 DISABLE_MAX_PRIVILEGE,
2754 sizeof(dropSids) / sizeof(dropSids[0]),
2760 FreeSid(dropSids[1].Sid);
2761 FreeSid(dropSids[0].Sid);
2762 CloseHandle(origToken);
2763 FreeLibrary(Advapi32Handle);
2767 fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError());
2772 AddUserToTokenDacl(restrictedToken);
2775 if (!CreateProcessAsUser(restrictedToken,
2788 fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError());
2792 return ResumeThread(processInfo->hThread);
2800 usage(const char *progname)
2802 printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2803 printf(_("Usage:\n"));
2804 printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2805 printf(_("\nOptions:\n"));
2806 printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2807 printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2808 printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2809 printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2810 printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2811 printf(_(" --locale=LOCALE set default locale for new databases\n"));
2812 printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2813 " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2814 " set default locale in the respective category for\n"
2815 " new databases (default taken from environment)\n"));
2816 printf(_(" --no-locale equivalent to --locale=C\n"));
2817 printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2818 printf(_(" -T, --text-search-config=CFG\n"
2819 " default text search configuration\n"));
2820 printf(_(" -U, --username=NAME database superuser name\n"));
2821 printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2822 printf(_(" -X, --xlogdir=XLOGDIR location for the transaction log directory\n"));
2823 printf(_("\nLess commonly used options:\n"));
2824 printf(_(" -d, --debug generate lots of debugging output\n"));
2825 printf(_(" -k, --data-checksums use data page checksums\n"));
2826 printf(_(" -L DIRECTORY where to find the input files\n"));
2827 printf(_(" -n, --noclean do not clean up after errors\n"));
2828 printf(_(" -N, --nosync do not wait for changes to be written safely to disk\n"));
2829 printf(_(" -s, --show show internal settings\n"));
2830 printf(_(" -S, --sync-only only sync data directory\n"));
2831 printf(_("\nOther options:\n"));
2832 printf(_(" -V, --version output version information, then exit\n"));
2833 printf(_(" -?, --help show this help, then exit\n"));
2834 printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2836 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2840 check_authmethod_unspecified(const char **authmethod)
2842 if (*authmethod == NULL || strlen(*authmethod) == 0)
2844 authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
2845 "You can change this by editing pg_hba.conf or using the option -A, or\n"
2846 "--auth-local and --auth-host, the next time you run initdb.\n");
2847 *authmethod = "trust";
2852 check_authmethod_valid(const char *authmethod, const char **valid_methods, const char *conntype)
2856 for (p = valid_methods; *p; p++)
2858 if (strcmp(authmethod, *p) == 0)
2860 /* with space = param */
2861 if (strchr(authmethod, ' '))
2862 if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2866 fprintf(stderr, _("%s: invalid authentication method \"%s\" for \"%s\" connections\n"),
2867 progname, authmethod, conntype);
2872 check_need_password(const char *authmethodlocal, const char *authmethodhost)
2874 if ((strcmp(authmethodlocal, "md5") == 0 ||
2875 strcmp(authmethodlocal, "password") == 0) &&
2876 (strcmp(authmethodhost, "md5") == 0 ||
2877 strcmp(authmethodhost, "password") == 0) &&
2878 !(pwprompt || pwfilename))
2880 fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname,
2881 (strcmp(authmethodlocal, "md5") == 0 ||
2882 strcmp(authmethodlocal, "password") == 0)
2890 get_restricted_token(void)
2894 * Before we execute another program, make sure that we are running with a
2895 * restricted token. If not, re-execute ourselves with one.
2898 if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL
2899 || strcmp(restrict_env, "1") != 0)
2901 PROCESS_INFORMATION pi;
2904 ZeroMemory(&pi, sizeof(pi));
2906 cmdline = pg_strdup(GetCommandLine());
2908 putenv("PG_RESTRICT_EXEC=1");
2910 if (!CreateRestrictedProcess(cmdline, &pi))
2912 fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError());
2917 * Successfully re-execed. Now wait for child process to capture
2922 CloseHandle(pi.hThread);
2923 WaitForSingleObject(pi.hProcess, INFINITE);
2925 if (!GetExitCodeProcess(pi.hProcess, &x))
2927 fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError());
2939 char *pgdata_get_env,
2942 if (strlen(pg_data) == 0)
2944 pgdata_get_env = getenv("PGDATA");
2945 if (pgdata_get_env && strlen(pgdata_get_env))
2948 pg_data = pg_strdup(pgdata_get_env);
2953 _("%s: no data directory specified\n"
2954 "You must identify the directory where the data for this database system\n"
2955 "will reside. Do this with either the invocation option -D or the\n"
2956 "environment variable PGDATA.\n"),
2962 pgdata_native = pg_strdup(pg_data);
2963 canonicalize_path(pg_data);
2966 * we have to set PGDATA for postgres rather than pass it on the command
2967 * line to avoid dumb quoting problems on Windows, and we would especially
2968 * need quotes otherwise on Windows because paths there are most likely to
2969 * have embedded spaces.
2971 pgdata_set_env = psprintf("PGDATA=%s", pg_data);
2972 putenv(pgdata_set_env);
2977 setup_bin_paths(const char *argv0)
2981 if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2984 char full_path[MAXPGPATH];
2986 if (find_my_exec(argv0, full_path) < 0)
2987 strlcpy(full_path, progname, sizeof(full_path));
2991 _("The program \"postgres\" is needed by %s "
2992 "but was not found in the\n"
2993 "same directory as \"%s\".\n"
2994 "Check your installation.\n"),
2995 progname, full_path);
2998 _("The program \"postgres\" was found by \"%s\"\n"
2999 "but was not the same version as %s.\n"
3000 "Check your installation.\n"),
3001 full_path, progname);
3005 /* store binary directory */
3006 strcpy(bin_path, backend_exec);
3007 *last_dir_separator(bin_path) = '\0';
3008 canonicalize_path(bin_path);
3012 share_path = pg_malloc(MAXPGPATH);
3013 get_share_path(backend_exec, share_path);
3015 else if (!is_absolute_path(share_path))
3017 fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
3021 canonicalize_path(share_path);
3025 setup_locale_encoding(void)
3031 if (strcmp(lc_ctype, lc_collate) == 0 &&
3032 strcmp(lc_ctype, lc_time) == 0 &&
3033 strcmp(lc_ctype, lc_numeric) == 0 &&
3034 strcmp(lc_ctype, lc_monetary) == 0 &&
3035 strcmp(lc_ctype, lc_messages) == 0)
3036 printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
3039 printf(_("The database cluster will be initialized with locales\n"
3054 if (strlen(encoding) == 0)
3058 ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
3060 if (ctype_enc == -1)
3062 /* Couldn't recognize the locale's codeset */
3063 fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"),
3064 progname, lc_ctype);
3065 fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
3066 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3070 else if (!pg_valid_server_encoding_id(ctype_enc))
3073 * We recognized it, but it's not a legal server encoding. On
3074 * Windows, UTF-8 works with any locale, so we can fall back to
3078 printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
3079 "The default database encoding will be set to \"%s\" instead.\n"),
3080 pg_encoding_to_char(ctype_enc),
3081 pg_encoding_to_char(PG_UTF8));
3082 ctype_enc = PG_UTF8;
3083 encodingid = encodingid_to_string(ctype_enc);
3086 _("%s: locale \"%s\" requires unsupported encoding \"%s\"\n"),
3087 progname, lc_ctype, pg_encoding_to_char(ctype_enc));
3089 _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
3090 "Rerun %s with a different locale selection.\n"),
3091 pg_encoding_to_char(ctype_enc), progname);
3097 encodingid = encodingid_to_string(ctype_enc);
3098 printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
3099 pg_encoding_to_char(ctype_enc));
3103 encodingid = get_encoding_id(encoding);
3105 user_enc = atoi(encodingid);
3106 if (!check_locale_encoding(lc_ctype, user_enc) ||
3107 !check_locale_encoding(lc_collate, user_enc))
3108 exit(1); /* check_locale_encoding printed the error */
3114 setup_data_file_paths(void)
3116 set_input(&bki_file, "postgres.bki");
3117 set_input(&desc_file, "postgres.description");
3118 set_input(&shdesc_file, "postgres.shdescription");
3119 set_input(&hba_file, "pg_hba.conf.sample");
3120 set_input(&ident_file, "pg_ident.conf.sample");
3121 set_input(&conf_file, "postgresql.conf.sample");
3122 set_input(&conversion_file, "conversion_create.sql");
3123 set_input(&dictionary_file, "snowball_create.sql");
3124 set_input(&info_schema_file, "information_schema.sql");
3125 set_input(&features_file, "sql_features.txt");
3126 set_input(&system_views_file, "system_views.sql");
3128 if (show_setting || debug)
3132 "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
3133 "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
3134 "POSTGRES_DESCR=%s\nPOSTGRES_SHDESCR=%s\n"
3135 "POSTGRESQL_CONF_SAMPLE=%s\n"
3136 "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
3138 pg_data, share_path, bin_path,
3140 desc_file, shdesc_file,
3142 hba_file, ident_file);
3147 check_input(bki_file);
3148 check_input(desc_file);
3149 check_input(shdesc_file);
3150 check_input(hba_file);
3151 check_input(ident_file);
3152 check_input(conf_file);
3153 check_input(conversion_file);
3154 check_input(dictionary_file);
3155 check_input(info_schema_file);
3156 check_input(features_file);
3157 check_input(system_views_file);
3162 setup_text_search(void)
3164 if (strlen(default_text_search_config) == 0)
3166 default_text_search_config = find_matching_ts_config(lc_ctype);
3167 if (default_text_search_config == NULL)
3169 printf(_("%s: could not find suitable text search configuration for locale \"%s\"\n"),
3170 progname, lc_ctype);
3171 default_text_search_config = "simple";
3176 const char *checkmatch = find_matching_ts_config(lc_ctype);
3178 if (checkmatch == NULL)
3180 printf(_("%s: warning: suitable text search configuration for locale \"%s\" is unknown\n"),
3181 progname, lc_ctype);
3183 else if (strcmp(checkmatch, default_text_search_config) != 0)
3185 printf(_("%s: warning: specified text search configuration \"%s\" might not match locale \"%s\"\n"),
3186 progname, default_text_search_config, lc_ctype);
3190 printf(_("The default text search configuration will be set to \"%s\".\n"),
3191 default_text_search_config);
3199 /* some of these are not valid on Windows */
3201 pqsignal(SIGHUP, trapsig);
3204 pqsignal(SIGINT, trapsig);
3207 pqsignal(SIGQUIT, trapsig);
3210 pqsignal(SIGTERM, trapsig);
3213 /* Ignore SIGPIPE when writing to backend, so we can clean up */
3215 pqsignal(SIGPIPE, SIG_IGN);
3218 /* Prevent SIGSYS so we can probe for kernel calls that might not work */
3220 pqsignal(SIGSYS, SIG_IGN);
3226 create_data_directory(void)
3230 switch ((ret = pg_check_dir(pg_data)))
3233 /* PGDATA not there, must create it */
3234 printf(_("creating directory %s ... "),
3238 if (!mkdatadir(NULL))
3243 made_new_pgdata = true;
3247 /* Present but empty, fix permissions and use it */
3248 printf(_("fixing permissions on existing directory %s ... "),
3252 if (chmod(pg_data, S_IRWXU) != 0)
3254 fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
3255 progname, pg_data, strerror(errno));
3261 found_existing_pgdata = true;
3267 /* Present and not empty */
3269 _("%s: directory \"%s\" exists but is not empty\n"),
3272 warn_on_mount_point(ret);
3275 _("If you want to create a new database system, either remove or empty\n"
3276 "the directory \"%s\" or run %s\n"
3277 "with an argument other than \"%s\".\n"),
3278 pg_data, progname, pg_data);
3279 exit(1); /* no further message needed */
3282 /* Trouble accessing directory */
3283 fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3284 progname, pg_data, strerror(errno));
3291 create_xlog_symlink(void)
3293 /* Create transaction log symlink, if required */
3294 if (strcmp(xlog_dir, "") != 0)
3299 /* clean up xlog directory name, check it's absolute */
3300 canonicalize_path(xlog_dir);
3301 if (!is_absolute_path(xlog_dir))
3303 fprintf(stderr, _("%s: transaction log directory location must be an absolute path\n"), progname);
3307 /* check if the specified xlog directory exists/is empty */
3308 switch ((ret = pg_check_dir(xlog_dir)))
3311 /* xlog directory not there, must create it */
3312 printf(_("creating directory %s ... "),
3316 if (pg_mkdir_p(xlog_dir, S_IRWXU) != 0)
3318 fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3319 progname, xlog_dir, strerror(errno));
3325 made_new_xlogdir = true;
3329 /* Present but empty, fix permissions and use it */
3330 printf(_("fixing permissions on existing directory %s ... "),
3334 if (chmod(xlog_dir, S_IRWXU) != 0)
3336 fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
3337 progname, xlog_dir, strerror(errno));
3343 found_existing_xlogdir = true;
3349 /* Present and not empty */
3351 _("%s: directory \"%s\" exists but is not empty\n"),
3352 progname, xlog_dir);
3354 warn_on_mount_point(ret);
3357 _("If you want to store the transaction log there, either\n"
3358 "remove or empty the directory \"%s\".\n"),
3363 /* Trouble accessing directory */
3364 fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3365 progname, xlog_dir, strerror(errno));
3369 /* form name of the place where the symlink must go */
3370 linkloc = psprintf("%s/pg_xlog", pg_data);
3373 if (symlink(xlog_dir, linkloc) != 0)
3375 fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
3376 progname, linkloc, strerror(errno));
3380 fprintf(stderr, _("%s: symlinks are not supported on this platform"));
3389 warn_on_mount_point(int error)
3393 _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
3394 else if (error == 3)
3396 _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
3399 _("Using a mount point directly as the data directory is not recommended.\n"
3400 "Create a subdirectory under the mount point.\n"));
3405 initialize_data_directory(void)
3411 umask(S_IRWXG | S_IRWXO);
3413 create_data_directory();
3415 create_xlog_symlink();
3417 /* Create required subdirectories */
3418 printf(_("creating subdirectories ... "));
3421 for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
3423 if (!mkdatadir(subdirs[i]))
3429 /* Top level PG_VERSION is checked by bootstrapper, so make it first */
3430 write_version_file(NULL);
3432 /* Select suitable configuration settings */
3434 test_config_settings();
3436 /* Now create all the text config files */
3439 /* Bootstrap template1 */
3440 bootstrap_template1();
3443 * Make the per-database PG_VERSION for template1 only after init'ing it
3445 write_version_file("base/1");
3447 /* Create the stuff we don't need to use bootstrap mode for */
3450 if (pwprompt || pwfilename)
3457 setup_description();
3480 main(int argc, char *argv[])
3482 static struct option long_options[] = {
3483 {"pgdata", required_argument, NULL, 'D'},
3484 {"encoding", required_argument, NULL, 'E'},
3485 {"locale", required_argument, NULL, 1},
3486 {"lc-collate", required_argument, NULL, 2},
3487 {"lc-ctype", required_argument, NULL, 3},
3488 {"lc-monetary", required_argument, NULL, 4},
3489 {"lc-numeric", required_argument, NULL, 5},
3490 {"lc-time", required_argument, NULL, 6},
3491 {"lc-messages", required_argument, NULL, 7},
3492 {"no-locale", no_argument, NULL, 8},
3493 {"text-search-config", required_argument, NULL, 'T'},
3494 {"auth", required_argument, NULL, 'A'},
3495 {"auth-local", required_argument, NULL, 10},
3496 {"auth-host", required_argument, NULL, 11},
3497 {"pwprompt", no_argument, NULL, 'W'},
3498 {"pwfile", required_argument, NULL, 9},
3499 {"username", required_argument, NULL, 'U'},
3500 {"help", no_argument, NULL, '?'},
3501 {"version", no_argument, NULL, 'V'},
3502 {"debug", no_argument, NULL, 'd'},
3503 {"show", no_argument, NULL, 's'},
3504 {"noclean", no_argument, NULL, 'n'},
3505 {"nosync", no_argument, NULL, 'N'},
3506 {"sync-only", no_argument, NULL, 'S'},
3507 {"xlogdir", required_argument, NULL, 'X'},
3508 {"data-checksums", no_argument, NULL, 'k'},
3513 * options with no short version return a low integer, the rest return
3514 * their short version value
3518 char *effective_user;
3519 char bin_dir[MAXPGPATH];
3521 progname = get_progname(argv[0]);
3522 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
3526 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
3531 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
3533 puts("initdb (PostgreSQL) " PG_VERSION);
3538 /* process command-line options */
3540 while ((c = getopt_long(argc, argv, "dD:E:kL:nNU:WA:sST:X:", long_options, &option_index)) != -1)
3545 authmethodlocal = authmethodhost = pg_strdup(optarg);
3548 * When ident is specified, use peer for local connections.
3549 * Mirrored, when peer is specified, use ident for TCP/IP
3552 if (strcmp(authmethodhost, "ident") == 0)
3553 authmethodlocal = "peer";
3554 else if (strcmp(authmethodlocal, "peer") == 0)
3555 authmethodhost = "ident";
3558 authmethodlocal = pg_strdup(optarg);
3561 authmethodhost = pg_strdup(optarg);
3564 pg_data = pg_strdup(optarg);
3567 encoding = pg_strdup(optarg);
3573 username = pg_strdup(optarg);
3577 printf(_("Running in debug mode.\n"));
3581 printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
3590 data_checksums = true;
3593 share_path = pg_strdup(optarg);
3596 locale = pg_strdup(optarg);
3599 lc_collate = pg_strdup(optarg);
3602 lc_ctype = pg_strdup(optarg);
3605 lc_monetary = pg_strdup(optarg);
3608 lc_numeric = pg_strdup(optarg);
3611 lc_time = pg_strdup(optarg);
3614 lc_messages = pg_strdup(optarg);
3620 pwfilename = pg_strdup(optarg);
3623 show_setting = true;
3626 default_text_search_config = pg_strdup(optarg);
3629 xlog_dir = pg_strdup(optarg);
3632 /* getopt_long already emitted a complaint */
3633 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3641 * Non-option argument specifies data directory as long as it wasn't
3642 * already specified with -D / --pgdata
3644 if (optind < argc && strlen(pg_data) == 0)
3646 pg_data = pg_strdup(argv[optind]);
3652 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
3653 progname, argv[optind]);
3654 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3659 /* If we only need to fsync, just to it and exit */
3667 if (pwprompt && pwfilename)
3669 fprintf(stderr, _("%s: password prompt and password file cannot be specified together\n"), progname);
3673 check_authmethod_unspecified(&authmethodlocal);
3674 check_authmethod_unspecified(&authmethodhost);
3676 check_authmethod_valid(authmethodlocal, auth_methods_local, "local");
3677 check_authmethod_valid(authmethodhost, auth_methods_host, "host");
3679 check_need_password(authmethodlocal, authmethodhost);
3681 get_restricted_token();
3685 setup_bin_paths(argv[0]);
3687 effective_user = get_id();
3688 if (strlen(username) == 0)
3689 username = effective_user;
3691 printf(_("The files belonging to this database system will be owned "
3693 "This user must also own the server process.\n\n"),
3698 setup_data_file_paths();
3700 setup_locale_encoding();
3702 setup_text_search();
3707 printf(_("Data page checksums are enabled.\n"));
3709 printf(_("Data page checksums are disabled.\n"));
3713 initialize_data_directory();
3718 printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3720 if (authwarning != NULL)
3721 fprintf(stderr, "%s", authwarning);
3723 /* Get directory specification used to start this executable */
3724 strlcpy(bin_dir, argv[0], sizeof(bin_dir));
3725 get_parent_directory(bin_dir);
3727 printf(_("\nSuccess. You can now start the database server using:\n\n"
3728 " %s%s%spostgres%s -D %s%s%s\n"
3730 " %s%s%spg_ctl%s -D %s%s%s -l logfile start\n\n"),
3731 QUOTE_PATH, bin_dir, (strlen(bin_dir) > 0) ? DIR_SEP : "", QUOTE_PATH,
3732 QUOTE_PATH, pgdata_native, QUOTE_PATH,
3733 QUOTE_PATH, bin_dir, (strlen(bin_dir) > 0) ? DIR_SEP : "", QUOTE_PATH,
3734 QUOTE_PATH, pgdata_native, QUOTE_PATH);