PostgreSQL Source Code  git master
initdb.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * initdb --- initialize a PostgreSQL installation
4  *
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.
8  *
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".
14  *
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.
19  *
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.
23  *
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.
30  *
31  *
32  * Note:
33  * The program has some memory leakage - it isn't worth cleaning it up.
34  *
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
38  *
39  * This code is released under the terms of the PostgreSQL License.
40  *
41  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
42  * Portions Copyright (c) 1994, Regents of the University of California
43  *
44  * src/bin/initdb/initdb.c
45  *
46  *-------------------------------------------------------------------------
47  */
48 
49 #include "postgres_fe.h"
50 
51 #include <dirent.h>
52 #include <fcntl.h>
53 #include <sys/stat.h>
54 #include <unistd.h>
55 #include <signal.h>
56 #include <time.h>
57 
58 #ifdef HAVE_SHM_OPEN
59 #include "sys/mman.h"
60 #endif
61 
62 #include "access/xlog_internal.h"
63 #include "catalog/pg_authid_d.h"
64 #include "catalog/pg_class_d.h" /* pgrminclude ignore */
65 #include "catalog/pg_collation_d.h"
66 #include "common/file_perm.h"
67 #include "common/file_utils.h"
68 #include "common/logging.h"
70 #include "common/string.h"
71 #include "common/username.h"
72 #include "fe_utils/string_utils.h"
73 #include "getaddrinfo.h"
74 #include "getopt_long.h"
75 #include "mb/pg_wchar.h"
76 #include "miscadmin.h"
77 
78 
79 /* Ideally this would be in a .h file, but it hardly seems worth the trouble */
80 extern const char *select_default_timezone(const char *share_path);
81 
82 static const char *const auth_methods_host[] = {
83  "trust", "reject", "scram-sha-256", "md5", "password", "ident", "radius",
84 #ifdef ENABLE_GSS
85  "gss",
86 #endif
87 #ifdef ENABLE_SSPI
88  "sspi",
89 #endif
90 #ifdef USE_PAM
91  "pam", "pam ",
92 #endif
93 #ifdef USE_BSD_AUTH
94  "bsd",
95 #endif
96 #ifdef USE_LDAP
97  "ldap",
98 #endif
99 #ifdef USE_SSL
100  "cert",
101 #endif
102  NULL
103 };
104 static const char *const auth_methods_local[] = {
105  "trust", "reject", "scram-sha-256", "md5", "password", "peer", "radius",
106 #ifdef USE_PAM
107  "pam", "pam ",
108 #endif
109 #ifdef USE_BSD_AUTH
110  "bsd",
111 #endif
112 #ifdef USE_LDAP
113  "ldap",
114 #endif
115  NULL
116 };
117 
118 /*
119  * these values are passed in by makefile defines
120  */
121 static char *share_path = NULL;
122 
123 /* values to be obtained from arguments */
124 static char *pg_data = NULL;
125 static char *encoding = NULL;
126 static char *locale = NULL;
127 static char *lc_collate = NULL;
128 static char *lc_ctype = NULL;
129 static char *lc_monetary = NULL;
130 static char *lc_numeric = NULL;
131 static char *lc_time = NULL;
132 static char *lc_messages = NULL;
133 static const char *default_text_search_config = NULL;
134 static char *username = NULL;
135 static bool pwprompt = false;
136 static char *pwfilename = NULL;
137 static char *superuser_password = NULL;
138 static const char *authmethodhost = NULL;
139 static const char *authmethodlocal = NULL;
140 static bool debug = false;
141 static bool noclean = false;
142 static bool do_sync = true;
143 static bool sync_only = false;
144 static bool show_setting = false;
145 static bool data_checksums = false;
146 static char *xlog_dir = NULL;
147 static char *str_wal_segment_size_mb = NULL;
149 
150 
151 /* internal vars */
152 static const char *progname;
153 static int encodingid;
154 static char *bki_file;
155 static char *hba_file;
156 static char *ident_file;
157 static char *conf_file;
158 static char *dictionary_file;
159 static char *info_schema_file;
160 static char *features_file;
161 static char *system_views_file;
162 static bool success = false;
163 static bool made_new_pgdata = false;
164 static bool found_existing_pgdata = false;
165 static bool made_new_xlogdir = false;
166 static bool found_existing_xlogdir = false;
167 static char infoversion[100];
168 static bool caught_signal = false;
169 static bool output_failed = false;
170 static int output_errno = 0;
171 static char *pgdata_native;
172 
173 /* defaults */
174 static int n_connections = 10;
175 static int n_buffers = 50;
176 static const char *dynamic_shared_memory_type = NULL;
177 static const char *default_timezone = NULL;
178 
179 /*
180  * Warning messages for authentication methods
181  */
182 #define AUTHTRUST_WARNING \
183 "# CAUTION: Configuring the system for local \"trust\" authentication\n" \
184 "# allows any local user to connect as any PostgreSQL user, including\n" \
185 "# the database superuser. If you do not trust all your local users,\n" \
186 "# use another authentication method.\n"
187 static bool authwarning = false;
188 
189 /*
190  * Centralized knowledge of switches to pass to backend
191  *
192  * Note: we run the backend with -F (fsync disabled) and then do a single
193  * pass of fsync'ing at the end. This is faster than fsync'ing each step.
194  *
195  * Note: in the shell-script version, we also passed PGDATA as a -D switch,
196  * but here it is more convenient to pass it as an environment variable
197  * (no quoting to worry about).
198  */
199 static const char *boot_options = "-F";
200 static const char *backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true";
201 
202 static const char *const subdirs[] = {
203  "global",
204  "pg_wal/archive_status",
205  "pg_commit_ts",
206  "pg_dynshmem",
207  "pg_notify",
208  "pg_serial",
209  "pg_snapshots",
210  "pg_subtrans",
211  "pg_twophase",
212  "pg_multixact",
213  "pg_multixact/members",
214  "pg_multixact/offsets",
215  "base",
216  "base/1",
217  "pg_replslot",
218  "pg_tblspc",
219  "pg_stat",
220  "pg_stat_tmp",
221  "pg_xact",
222  "pg_logical",
223  "pg_logical/snapshots",
224  "pg_logical/mappings"
225 };
226 
227 
228 /* path to 'initdb' binary directory */
229 static char bin_path[MAXPGPATH];
230 static char backend_exec[MAXPGPATH];
231 
232 static char **replace_token(char **lines,
233  const char *token, const char *replacement);
234 
235 #ifndef HAVE_UNIX_SOCKETS
236 static char **filter_lines_with_token(char **lines, const char *token);
237 #endif
238 static char **readfile(const char *path);
239 static void writefile(char *path, char **lines);
240 static FILE *popen_check(const char *command, const char *mode);
241 static char *get_id(void);
242 static int get_encoding_id(const char *encoding_name);
243 static void set_input(char **dest, const char *filename);
244 static void check_input(char *path);
245 static void write_version_file(const char *extrapath);
246 static void set_null_conf(void);
247 static void test_config_settings(void);
248 static void setup_config(void);
249 static void bootstrap_template1(void);
250 static void setup_auth(FILE *cmdfd);
251 static void get_su_pwd(void);
252 static void setup_depend(FILE *cmdfd);
253 static void setup_sysviews(FILE *cmdfd);
254 static void setup_description(FILE *cmdfd);
255 static void setup_collation(FILE *cmdfd);
256 static void setup_dictionary(FILE *cmdfd);
257 static void setup_privileges(FILE *cmdfd);
258 static void set_info_version(void);
259 static void setup_schema(FILE *cmdfd);
260 static void load_plpgsql(FILE *cmdfd);
261 static void vacuum_db(FILE *cmdfd);
262 static void make_template0(FILE *cmdfd);
263 static void make_postgres(FILE *cmdfd);
264 static void trapsig(int signum);
265 static void check_ok(void);
266 static char *escape_quotes(const char *src);
267 static char *escape_quotes_bki(const char *src);
268 static int locale_date_order(const char *locale);
269 static void check_locale_name(int category, const char *locale,
270  char **canonname);
271 static bool check_locale_encoding(const char *locale, int encoding);
272 static void setlocales(void);
273 static void usage(const char *progname);
274 void setup_pgdata(void);
275 void setup_bin_paths(const char *argv0);
276 void setup_data_file_paths(void);
277 void setup_locale_encoding(void);
278 void setup_signals(void);
279 void setup_text_search(void);
280 void create_data_directory(void);
281 void create_xlog_or_symlink(void);
282 void warn_on_mount_point(int error);
283 void initialize_data_directory(void);
284 
285 /*
286  * macros for running pipes to postgres
287  */
288 #define PG_CMD_DECL char cmd[MAXPGPATH]; FILE *cmdfd
289 
290 #define PG_CMD_OPEN \
291 do { \
292  cmdfd = popen_check(cmd, "w"); \
293  if (cmdfd == NULL) \
294  exit(1); /* message already printed by popen_check */ \
295 } while (0)
296 
297 #define PG_CMD_CLOSE \
298 do { \
299  if (pclose_check(cmdfd)) \
300  exit(1); /* message already printed by pclose_check */ \
301 } while (0)
302 
303 #define PG_CMD_PUTS(line) \
304 do { \
305  if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
306  output_failed = true, output_errno = errno; \
307 } while (0)
308 
309 #define PG_CMD_PRINTF(fmt, ...) \
310 do { \
311  if (fprintf(cmdfd, fmt, __VA_ARGS__) < 0 || fflush(cmdfd) < 0) \
312  output_failed = true, output_errno = errno; \
313 } while (0)
314 
315 /*
316  * Escape single quotes and backslashes, suitably for insertions into
317  * configuration files or SQL E'' strings.
318  */
319 static char *
320 escape_quotes(const char *src)
321 {
322  char *result = escape_single_quotes_ascii(src);
323 
324  if (!result)
325  {
326  pg_log_error("out of memory");
327  exit(1);
328  }
329  return result;
330 }
331 
332 /*
333  * Escape a field value to be inserted into the BKI data.
334  * Here, we first run the value through escape_quotes (which
335  * will be inverted by the backend's scanstr() function) and
336  * then overlay special processing of double quotes, which
337  * bootscanner.l will only accept as data if converted to octal
338  * representation ("\042"). We always wrap the value in double
339  * quotes, even if that isn't strictly necessary.
340  */
341 static char *
342 escape_quotes_bki(const char *src)
343 {
344  char *result;
345  char *data = escape_quotes(src);
346  char *resultp;
347  char *datap;
348  int nquotes = 0;
349 
350  /* count double quotes in data */
351  datap = data;
352  while ((datap = strchr(datap, '"')) != NULL)
353  {
354  nquotes++;
355  datap++;
356  }
357 
358  result = (char *) pg_malloc(strlen(data) + 3 + nquotes * 3);
359  resultp = result;
360  *resultp++ = '"';
361  for (datap = data; *datap; datap++)
362  {
363  if (*datap == '"')
364  {
365  strcpy(resultp, "\\042");
366  resultp += 4;
367  }
368  else
369  *resultp++ = *datap;
370  }
371  *resultp++ = '"';
372  *resultp = '\0';
373 
374  free(data);
375  return result;
376 }
377 
378 /*
379  * make a copy of the array of lines, with token replaced by replacement
380  * the first time it occurs on each line.
381  *
382  * This does most of what sed was used for in the shell script, but
383  * doesn't need any regexp stuff.
384  */
385 static char **
386 replace_token(char **lines, const char *token, const char *replacement)
387 {
388  int numlines = 1;
389  int i;
390  char **result;
391  int toklen,
392  replen,
393  diff;
394 
395  for (i = 0; lines[i]; i++)
396  numlines++;
397 
398  result = (char **) pg_malloc(numlines * sizeof(char *));
399 
400  toklen = strlen(token);
401  replen = strlen(replacement);
402  diff = replen - toklen;
403 
404  for (i = 0; i < numlines; i++)
405  {
406  char *where;
407  char *newline;
408  int pre;
409 
410  /* just copy pointer if NULL or no change needed */
411  if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
412  {
413  result[i] = lines[i];
414  continue;
415  }
416 
417  /* if we get here a change is needed - set up new line */
418 
419  newline = (char *) pg_malloc(strlen(lines[i]) + diff + 1);
420 
421  pre = where - lines[i];
422 
423  memcpy(newline, lines[i], pre);
424 
425  memcpy(newline + pre, replacement, replen);
426 
427  strcpy(newline + pre + replen, lines[i] + pre + toklen);
428 
429  result[i] = newline;
430  }
431 
432  return result;
433 }
434 
435 /*
436  * make a copy of lines without any that contain the token
437  *
438  * a sort of poor man's grep -v
439  */
440 #ifndef HAVE_UNIX_SOCKETS
441 static char **
442 filter_lines_with_token(char **lines, const char *token)
443 {
444  int numlines = 1;
445  int i,
446  src,
447  dst;
448  char **result;
449 
450  for (i = 0; lines[i]; i++)
451  numlines++;
452 
453  result = (char **) pg_malloc(numlines * sizeof(char *));
454 
455  for (src = 0, dst = 0; src < numlines; src++)
456  {
457  if (lines[src] == NULL || strstr(lines[src], token) == NULL)
458  result[dst++] = lines[src];
459  }
460 
461  return result;
462 }
463 #endif
464 
465 /*
466  * get the lines from a text file
467  */
468 static char **
469 readfile(const char *path)
470 {
471  char **result;
472  FILE *infile;
473  StringInfoData line;
474  int maxlines;
475  int n;
476 
477  if ((infile = fopen(path, "r")) == NULL)
478  {
479  pg_log_error("could not open file \"%s\" for reading: %m", path);
480  exit(1);
481  }
482 
483  initStringInfo(&line);
484 
485  maxlines = 1024;
486  result = (char **) pg_malloc(maxlines * sizeof(char *));
487 
488  n = 0;
489  while (pg_get_line_buf(infile, &line))
490  {
491  /* make sure there will be room for a trailing NULL pointer */
492  if (n >= maxlines - 1)
493  {
494  maxlines *= 2;
495  result = (char **) pg_realloc(result, maxlines * sizeof(char *));
496  }
497 
498  result[n++] = pg_strdup(line.data);
499  }
500  result[n] = NULL;
501 
502  pfree(line.data);
503 
504  fclose(infile);
505 
506  return result;
507 }
508 
509 /*
510  * write an array of lines to a file
511  *
512  * This is only used to write text files. Use fopen "w" not PG_BINARY_W
513  * so that the resulting configuration files are nicely editable on Windows.
514  */
515 static void
516 writefile(char *path, char **lines)
517 {
518  FILE *out_file;
519  char **line;
520 
521  if ((out_file = fopen(path, "w")) == NULL)
522  {
523  pg_log_error("could not open file \"%s\" for writing: %m", path);
524  exit(1);
525  }
526  for (line = lines; *line != NULL; line++)
527  {
528  if (fputs(*line, out_file) < 0)
529  {
530  pg_log_error("could not write file \"%s\": %m", path);
531  exit(1);
532  }
533  free(*line);
534  }
535  if (fclose(out_file))
536  {
537  pg_log_error("could not write file \"%s\": %m", path);
538  exit(1);
539  }
540 }
541 
542 /*
543  * Open a subcommand with suitable error messaging
544  */
545 static FILE *
546 popen_check(const char *command, const char *mode)
547 {
548  FILE *cmdfd;
549 
550  fflush(stdout);
551  fflush(stderr);
552  errno = 0;
553  cmdfd = popen(command, mode);
554  if (cmdfd == NULL)
555  pg_log_error("could not execute command \"%s\": %m", command);
556  return cmdfd;
557 }
558 
559 /*
560  * clean up any files we created on failure
561  * if we created the data directory remove it too
562  */
563 static void
565 {
566  if (success)
567  return;
568 
569  if (!noclean)
570  {
571  if (made_new_pgdata)
572  {
573  pg_log_info("removing data directory \"%s\"", pg_data);
574  if (!rmtree(pg_data, true))
575  pg_log_error("failed to remove data directory");
576  }
577  else if (found_existing_pgdata)
578  {
579  pg_log_info("removing contents of data directory \"%s\"",
580  pg_data);
581  if (!rmtree(pg_data, false))
582  pg_log_error("failed to remove contents of data directory");
583  }
584 
585  if (made_new_xlogdir)
586  {
587  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
588  if (!rmtree(xlog_dir, true))
589  pg_log_error("failed to remove WAL directory");
590  }
591  else if (found_existing_xlogdir)
592  {
593  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
594  if (!rmtree(xlog_dir, false))
595  pg_log_error("failed to remove contents of WAL directory");
596  }
597  /* otherwise died during startup, do nothing! */
598  }
599  else
600  {
602  pg_log_info("data directory \"%s\" not removed at user's request",
603  pg_data);
604 
606  pg_log_info("WAL directory \"%s\" not removed at user's request",
607  xlog_dir);
608  }
609 }
610 
611 /*
612  * find the current user
613  *
614  * on unix make sure it isn't root
615  */
616 static char *
617 get_id(void)
618 {
619  const char *username;
620 
621 #ifndef WIN32
622  if (geteuid() == 0) /* 0 is root's uid */
623  {
624  pg_log_error("cannot be run as root");
625  fprintf(stderr,
626  _("Please log in (using, e.g., \"su\") as the (unprivileged) user that will\n"
627  "own the server process.\n"));
628  exit(1);
629  }
630 #endif
631 
632  username = get_user_name_or_exit(progname);
633 
634  return pg_strdup(username);
635 }
636 
637 static char *
639 {
640  char result[20];
641 
642  sprintf(result, "%d", enc);
643  return pg_strdup(result);
644 }
645 
646 /*
647  * get the encoding id for a given encoding name
648  */
649 static int
650 get_encoding_id(const char *encoding_name)
651 {
652  int enc;
653 
654  if (encoding_name && *encoding_name)
655  {
656  if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
657  return enc;
658  }
659  pg_log_error("\"%s\" is not a valid server encoding name",
660  encoding_name ? encoding_name : "(null)");
661  exit(1);
662 }
663 
664 /*
665  * Support for determining the best default text search configuration.
666  * We key this off the first part of LC_CTYPE (ie, the language name).
667  */
669 {
670  const char *tsconfname;
671  const char *langname;
672 };
673 
675 {
676  {"arabic", "ar"},
677  {"arabic", "Arabic"},
678  {"basque", "eu"},
679  {"basque", "Basque"},
680  {"catalan", "ca"},
681  {"catalan", "Catalan"},
682  {"danish", "da"},
683  {"danish", "Danish"},
684  {"dutch", "nl"},
685  {"dutch", "Dutch"},
686  {"english", "C"},
687  {"english", "POSIX"},
688  {"english", "en"},
689  {"english", "English"},
690  {"finnish", "fi"},
691  {"finnish", "Finnish"},
692  {"french", "fr"},
693  {"french", "French"},
694  {"german", "de"},
695  {"german", "German"},
696  {"greek", "el"},
697  {"greek", "Greek"},
698  {"hindi", "hi"},
699  {"hindi", "Hindi"},
700  {"hungarian", "hu"},
701  {"hungarian", "Hungarian"},
702  {"indonesian", "id"},
703  {"indonesian", "Indonesian"},
704  {"irish", "ga"},
705  {"irish", "Irish"},
706  {"italian", "it"},
707  {"italian", "Italian"},
708  {"lithuanian", "lt"},
709  {"lithuanian", "Lithuanian"},
710  {"nepali", "ne"},
711  {"nepali", "Nepali"},
712  {"norwegian", "no"},
713  {"norwegian", "Norwegian"},
714  {"portuguese", "pt"},
715  {"portuguese", "Portuguese"},
716  {"romanian", "ro"},
717  {"russian", "ru"},
718  {"russian", "Russian"},
719  {"spanish", "es"},
720  {"spanish", "Spanish"},
721  {"swedish", "sv"},
722  {"swedish", "Swedish"},
723  {"tamil", "ta"},
724  {"tamil", "Tamil"},
725  {"turkish", "tr"},
726  {"turkish", "Turkish"},
727  {NULL, NULL} /* end marker */
728 };
729 
730 /*
731  * Look for a text search configuration matching lc_ctype, and return its
732  * name; return NULL if no match.
733  */
734 static const char *
735 find_matching_ts_config(const char *lc_type)
736 {
737  int i;
738  char *langname,
739  *ptr;
740 
741  /*
742  * Convert lc_ctype to a language name by stripping everything after an
743  * underscore (usual case) or a hyphen (Windows "locale name"; see
744  * comments at IsoLocaleName()).
745  *
746  * XXX Should ' ' be a stop character? This would select "norwegian" for
747  * the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
748  * should also accept the "nn" and "nb" Unix locales.
749  *
750  * Just for paranoia, we also stop at '.' or '@'.
751  */
752  if (lc_type == NULL)
753  langname = pg_strdup("");
754  else
755  {
756  ptr = langname = pg_strdup(lc_type);
757  while (*ptr &&
758  *ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
759  ptr++;
760  *ptr = '\0';
761  }
762 
763  for (i = 0; tsearch_config_languages[i].tsconfname; i++)
764  {
765  if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
766  {
767  free(langname);
768  return tsearch_config_languages[i].tsconfname;
769  }
770  }
771 
772  free(langname);
773  return NULL;
774 }
775 
776 
777 /*
778  * set name of given input file variable under data directory
779  */
780 static void
781 set_input(char **dest, const char *filename)
782 {
783  *dest = psprintf("%s/%s", share_path, filename);
784 }
785 
786 /*
787  * check that given input file exists
788  */
789 static void
790 check_input(char *path)
791 {
792  struct stat statbuf;
793 
794  if (stat(path, &statbuf) != 0)
795  {
796  if (errno == ENOENT)
797  {
798  pg_log_error("file \"%s\" does not exist", path);
799  fprintf(stderr,
800  _("This might mean you have a corrupted installation or identified\n"
801  "the wrong directory with the invocation option -L.\n"));
802  }
803  else
804  {
805  pg_log_error("could not access file \"%s\": %m", path);
806  fprintf(stderr,
807  _("This might mean you have a corrupted installation or identified\n"
808  "the wrong directory with the invocation option -L.\n"));
809  }
810  exit(1);
811  }
812  if (!S_ISREG(statbuf.st_mode))
813  {
814  pg_log_error("file \"%s\" is not a regular file", path);
815  fprintf(stderr,
816  _("This might mean you have a corrupted installation or identified\n"
817  "the wrong directory with the invocation option -L.\n"));
818  exit(1);
819  }
820 }
821 
822 /*
823  * write out the PG_VERSION file in the data dir, or its subdirectory
824  * if extrapath is not NULL
825  */
826 static void
827 write_version_file(const char *extrapath)
828 {
829  FILE *version_file;
830  char *path;
831 
832  if (extrapath == NULL)
833  path = psprintf("%s/PG_VERSION", pg_data);
834  else
835  path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
836 
837  if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
838  {
839  pg_log_error("could not open file \"%s\" for writing: %m", path);
840  exit(1);
841  }
842  if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
843  fclose(version_file))
844  {
845  pg_log_error("could not write file \"%s\": %m", path);
846  exit(1);
847  }
848  free(path);
849 }
850 
851 /*
852  * set up an empty config file so we can check config settings by launching
853  * a test backend
854  */
855 static void
857 {
858  FILE *conf_file;
859  char *path;
860 
861  path = psprintf("%s/postgresql.conf", pg_data);
862  conf_file = fopen(path, PG_BINARY_W);
863  if (conf_file == NULL)
864  {
865  pg_log_error("could not open file \"%s\" for writing: %m", path);
866  exit(1);
867  }
868  if (fclose(conf_file))
869  {
870  pg_log_error("could not write file \"%s\": %m", path);
871  exit(1);
872  }
873  free(path);
874 }
875 
876 /*
877  * Determine which dynamic shared memory implementation should be used on
878  * this platform. POSIX shared memory is preferable because the default
879  * allocation limits are much higher than the limits for System V on most
880  * systems that support both, but the fact that a platform has shm_open
881  * doesn't guarantee that that call will succeed when attempted. So, we
882  * attempt to reproduce what the postmaster will do when allocating a POSIX
883  * segment in dsm_impl.c; if it doesn't work, we assume it won't work for
884  * the postmaster either, and configure the cluster for System V shared
885  * memory instead.
886  */
887 static const char *
889 {
890 #ifdef HAVE_SHM_OPEN
891  int ntries = 10;
892 
893  /* Initialize random(); this function is its only user in this program. */
894  srandom((unsigned int) (getpid() ^ time(NULL)));
895 
896  while (ntries > 0)
897  {
898  uint32 handle;
899  char name[64];
900  int fd;
901 
902  handle = random();
903  snprintf(name, 64, "/PostgreSQL.%u", handle);
904  if ((fd = shm_open(name, O_CREAT | O_RDWR | O_EXCL, 0600)) != -1)
905  {
906  close(fd);
907  shm_unlink(name);
908  return "posix";
909  }
910  if (errno != EEXIST)
911  break;
912  --ntries;
913  }
914 #endif
915 
916 #ifdef WIN32
917  return "windows";
918 #else
919  return "sysv";
920 #endif
921 }
922 
923 /*
924  * Determine platform-specific config settings
925  *
926  * Use reasonable values if kernel will let us, else scale back.
927  */
928 static void
930 {
931  /*
932  * This macro defines the minimum shared_buffers we want for a given
933  * max_connections value. The arrays show the settings to try.
934  */
935 #define MIN_BUFS_FOR_CONNS(nconns) ((nconns) * 10)
936 
937  static const int trial_conns[] = {
938  100, 50, 40, 30, 20
939  };
940  static const int trial_bufs[] = {
941  16384, 8192, 4096, 3584, 3072, 2560, 2048, 1536,
942  1000, 900, 800, 700, 600, 500,
943  400, 300, 200, 100, 50
944  };
945 
946  char cmd[MAXPGPATH];
947  const int connslen = sizeof(trial_conns) / sizeof(int);
948  const int bufslen = sizeof(trial_bufs) / sizeof(int);
949  int i,
950  status,
951  test_conns,
952  test_buffs,
953  ok_buffers = 0;
954 
955  /*
956  * Need to determine working DSM implementation first so that subsequent
957  * tests don't fail because DSM setting doesn't work.
958  */
959  printf(_("selecting dynamic shared memory implementation ... "));
960  fflush(stdout);
963 
964  /*
965  * Probe for max_connections before shared_buffers, since it is subject to
966  * more constraints than shared_buffers.
967  */
968  printf(_("selecting default max_connections ... "));
969  fflush(stdout);
970 
971  for (i = 0; i < connslen; i++)
972  {
973  test_conns = trial_conns[i];
974  test_buffs = MIN_BUFS_FOR_CONNS(test_conns);
975 
976  snprintf(cmd, sizeof(cmd),
977  "\"%s\" --boot -x0 %s "
978  "-c max_connections=%d "
979  "-c shared_buffers=%d "
980  "-c dynamic_shared_memory_type=%s "
981  "< \"%s\" > \"%s\" 2>&1",
983  test_conns, test_buffs,
985  DEVNULL, DEVNULL);
986  status = system(cmd);
987  if (status == 0)
988  {
989  ok_buffers = test_buffs;
990  break;
991  }
992  }
993  if (i >= connslen)
994  i = connslen - 1;
995  n_connections = trial_conns[i];
996 
997  printf("%d\n", n_connections);
998 
999  printf(_("selecting default shared_buffers ... "));
1000  fflush(stdout);
1001 
1002  for (i = 0; i < bufslen; i++)
1003  {
1004  /* Use same amount of memory, independent of BLCKSZ */
1005  test_buffs = (trial_bufs[i] * 8192) / BLCKSZ;
1006  if (test_buffs <= ok_buffers)
1007  {
1008  test_buffs = ok_buffers;
1009  break;
1010  }
1011 
1012  snprintf(cmd, sizeof(cmd),
1013  "\"%s\" --boot -x0 %s "
1014  "-c max_connections=%d "
1015  "-c shared_buffers=%d "
1016  "-c dynamic_shared_memory_type=%s "
1017  "< \"%s\" > \"%s\" 2>&1",
1019  n_connections, test_buffs,
1021  DEVNULL, DEVNULL);
1022  status = system(cmd);
1023  if (status == 0)
1024  break;
1025  }
1026  n_buffers = test_buffs;
1027 
1028  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1029  printf("%dMB\n", (n_buffers * (BLCKSZ / 1024)) / 1024);
1030  else
1031  printf("%dkB\n", n_buffers * (BLCKSZ / 1024));
1032 
1033  printf(_("selecting default time zone ... "));
1034  fflush(stdout);
1036  printf("%s\n", default_timezone ? default_timezone : "GMT");
1037 }
1038 
1039 /*
1040  * Calculate the default wal_size with a "pretty" unit.
1041  */
1042 static char *
1043 pretty_wal_size(int segment_count)
1044 {
1045  int sz = wal_segment_size_mb * segment_count;
1046  char *result = pg_malloc(14);
1047 
1048  if ((sz % 1024) == 0)
1049  snprintf(result, 14, "%dGB", sz / 1024);
1050  else
1051  snprintf(result, 14, "%dMB", sz);
1052 
1053  return result;
1054 }
1055 
1056 /*
1057  * set up all the config files
1058  */
1059 static void
1061 {
1062  char **conflines;
1063  char repltok[MAXPGPATH];
1064  char path[MAXPGPATH];
1065  char *autoconflines[3];
1066 
1067  fputs(_("creating configuration files ... "), stdout);
1068  fflush(stdout);
1069 
1070  /* postgresql.conf */
1071 
1072  conflines = readfile(conf_file);
1073 
1074  snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1075  conflines = replace_token(conflines, "#max_connections = 100", repltok);
1076 
1077  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1078  snprintf(repltok, sizeof(repltok), "shared_buffers = %dMB",
1079  (n_buffers * (BLCKSZ / 1024)) / 1024);
1080  else
1081  snprintf(repltok, sizeof(repltok), "shared_buffers = %dkB",
1082  n_buffers * (BLCKSZ / 1024));
1083  conflines = replace_token(conflines, "#shared_buffers = 32MB", repltok);
1084 
1085 #ifdef HAVE_UNIX_SOCKETS
1086  snprintf(repltok, sizeof(repltok), "#unix_socket_directories = '%s'",
1088 #else
1089  snprintf(repltok, sizeof(repltok), "#unix_socket_directories = ''");
1090 #endif
1091  conflines = replace_token(conflines, "#unix_socket_directories = '/tmp'",
1092  repltok);
1093 
1094 #if DEF_PGPORT != 5432
1095  snprintf(repltok, sizeof(repltok), "#port = %d", DEF_PGPORT);
1096  conflines = replace_token(conflines, "#port = 5432", repltok);
1097 #endif
1098 
1099  /* set default max_wal_size and min_wal_size */
1100  snprintf(repltok, sizeof(repltok), "min_wal_size = %s",
1102  conflines = replace_token(conflines, "#min_wal_size = 80MB", repltok);
1103 
1104  snprintf(repltok, sizeof(repltok), "max_wal_size = %s",
1106  conflines = replace_token(conflines, "#max_wal_size = 1GB", repltok);
1107 
1108  snprintf(repltok, sizeof(repltok), "lc_messages = '%s'",
1110  conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1111 
1112  snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'",
1114  conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1115 
1116  snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'",
1118  conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1119 
1120  snprintf(repltok, sizeof(repltok), "lc_time = '%s'",
1122  conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1123 
1124  switch (locale_date_order(lc_time))
1125  {
1126  case DATEORDER_YMD:
1127  strcpy(repltok, "datestyle = 'iso, ymd'");
1128  break;
1129  case DATEORDER_DMY:
1130  strcpy(repltok, "datestyle = 'iso, dmy'");
1131  break;
1132  case DATEORDER_MDY:
1133  default:
1134  strcpy(repltok, "datestyle = 'iso, mdy'");
1135  break;
1136  }
1137  conflines = replace_token(conflines, "#datestyle = 'iso, mdy'", repltok);
1138 
1139  snprintf(repltok, sizeof(repltok),
1140  "default_text_search_config = 'pg_catalog.%s'",
1142  conflines = replace_token(conflines,
1143  "#default_text_search_config = 'pg_catalog.simple'",
1144  repltok);
1145 
1146  if (default_timezone)
1147  {
1148  snprintf(repltok, sizeof(repltok), "timezone = '%s'",
1150  conflines = replace_token(conflines, "#timezone = 'GMT'", repltok);
1151  snprintf(repltok, sizeof(repltok), "log_timezone = '%s'",
1153  conflines = replace_token(conflines, "#log_timezone = 'GMT'", repltok);
1154  }
1155 
1156  snprintf(repltok, sizeof(repltok), "dynamic_shared_memory_type = %s",
1158  conflines = replace_token(conflines, "#dynamic_shared_memory_type = posix",
1159  repltok);
1160 
1161 #if DEFAULT_BACKEND_FLUSH_AFTER > 0
1162  snprintf(repltok, sizeof(repltok), "#backend_flush_after = %dkB",
1163  DEFAULT_BACKEND_FLUSH_AFTER * (BLCKSZ / 1024));
1164  conflines = replace_token(conflines, "#backend_flush_after = 0",
1165  repltok);
1166 #endif
1167 
1168 #if DEFAULT_BGWRITER_FLUSH_AFTER > 0
1169  snprintf(repltok, sizeof(repltok), "#bgwriter_flush_after = %dkB",
1170  DEFAULT_BGWRITER_FLUSH_AFTER * (BLCKSZ / 1024));
1171  conflines = replace_token(conflines, "#bgwriter_flush_after = 0",
1172  repltok);
1173 #endif
1174 
1175 #if DEFAULT_CHECKPOINT_FLUSH_AFTER > 0
1176  snprintf(repltok, sizeof(repltok), "#checkpoint_flush_after = %dkB",
1177  DEFAULT_CHECKPOINT_FLUSH_AFTER * (BLCKSZ / 1024));
1178  conflines = replace_token(conflines, "#checkpoint_flush_after = 0",
1179  repltok);
1180 #endif
1181 
1182 #ifndef USE_PREFETCH
1183  conflines = replace_token(conflines,
1184  "#effective_io_concurrency = 1",
1185  "#effective_io_concurrency = 0");
1186 #endif
1187 
1188 #ifdef WIN32
1189  conflines = replace_token(conflines,
1190  "#update_process_title = on",
1191  "#update_process_title = off");
1192 #endif
1193 
1194  /*
1195  * Change password_encryption setting to md5 if md5 was chosen as an
1196  * authentication method, unless scram-sha-256 was also chosen.
1197  */
1198  if ((strcmp(authmethodlocal, "md5") == 0 &&
1199  strcmp(authmethodhost, "scram-sha-256") != 0) ||
1200  (strcmp(authmethodhost, "md5") == 0 &&
1201  strcmp(authmethodlocal, "scram-sha-256") != 0))
1202  {
1203  conflines = replace_token(conflines,
1204  "#password_encryption = scram-sha-256",
1205  "password_encryption = md5");
1206  }
1207 
1208  /*
1209  * If group access has been enabled for the cluster then it makes sense to
1210  * ensure that the log files also allow group access. Otherwise a backup
1211  * from a user in the group would fail if the log files were not
1212  * relocated.
1213  */
1215  {
1216  conflines = replace_token(conflines,
1217  "#log_file_mode = 0600",
1218  "log_file_mode = 0640");
1219  }
1220 
1221  snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1222 
1223  writefile(path, conflines);
1224  if (chmod(path, pg_file_create_mode) != 0)
1225  {
1226  pg_log_error("could not change permissions of \"%s\": %m", path);
1227  exit(1);
1228  }
1229 
1230  /*
1231  * create the automatic configuration file to store the configuration
1232  * parameters set by ALTER SYSTEM command. The parameters present in this
1233  * file will override the value of parameters that exists before parse of
1234  * this file.
1235  */
1236  autoconflines[0] = pg_strdup("# Do not edit this file manually!\n");
1237  autoconflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
1238  autoconflines[2] = NULL;
1239 
1240  sprintf(path, "%s/postgresql.auto.conf", pg_data);
1241 
1242  writefile(path, autoconflines);
1243  if (chmod(path, pg_file_create_mode) != 0)
1244  {
1245  pg_log_error("could not change permissions of \"%s\": %m", path);
1246  exit(1);
1247  }
1248 
1249  free(conflines);
1250 
1251 
1252  /* pg_hba.conf */
1253 
1254  conflines = readfile(hba_file);
1255 
1256 #ifndef HAVE_UNIX_SOCKETS
1257  conflines = filter_lines_with_token(conflines, "@remove-line-for-nolocal@");
1258 #else
1259  conflines = replace_token(conflines, "@remove-line-for-nolocal@", "");
1260 #endif
1261 
1262 #ifdef HAVE_IPV6
1263 
1264  /*
1265  * Probe to see if there is really any platform support for IPv6, and
1266  * comment out the relevant pg_hba line if not. This avoids runtime
1267  * warnings if getaddrinfo doesn't actually cope with IPv6. Particularly
1268  * useful on Windows, where executables built on a machine with IPv6 may
1269  * have to run on a machine without.
1270  */
1271  {
1272  struct addrinfo *gai_result;
1273  struct addrinfo hints;
1274  int err = 0;
1275 
1276 #ifdef WIN32
1277  /* need to call WSAStartup before calling getaddrinfo */
1278  WSADATA wsaData;
1279 
1280  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
1281 #endif
1282 
1283  /* for best results, this code should match parse_hba_line() */
1284  hints.ai_flags = AI_NUMERICHOST;
1285  hints.ai_family = AF_UNSPEC;
1286  hints.ai_socktype = 0;
1287  hints.ai_protocol = 0;
1288  hints.ai_addrlen = 0;
1289  hints.ai_canonname = NULL;
1290  hints.ai_addr = NULL;
1291  hints.ai_next = NULL;
1292 
1293  if (err != 0 ||
1294  getaddrinfo("::1", NULL, &hints, &gai_result) != 0)
1295  {
1296  conflines = replace_token(conflines,
1297  "host all all ::1",
1298  "#host all all ::1");
1299  conflines = replace_token(conflines,
1300  "host replication all ::1",
1301  "#host replication all ::1");
1302  }
1303  }
1304 #else /* !HAVE_IPV6 */
1305  /* If we didn't compile IPV6 support at all, always comment it out */
1306  conflines = replace_token(conflines,
1307  "host all all ::1",
1308  "#host all all ::1");
1309  conflines = replace_token(conflines,
1310  "host replication all ::1",
1311  "#host replication all ::1");
1312 #endif /* HAVE_IPV6 */
1313 
1314  /* Replace default authentication methods */
1315  conflines = replace_token(conflines,
1316  "@authmethodhost@",
1317  authmethodhost);
1318  conflines = replace_token(conflines,
1319  "@authmethodlocal@",
1320  authmethodlocal);
1321 
1322  conflines = replace_token(conflines,
1323  "@authcomment@",
1324  (strcmp(authmethodlocal, "trust") == 0 || strcmp(authmethodhost, "trust") == 0) ? AUTHTRUST_WARNING : "");
1325 
1326  snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1327 
1328  writefile(path, conflines);
1329  if (chmod(path, pg_file_create_mode) != 0)
1330  {
1331  pg_log_error("could not change permissions of \"%s\": %m", path);
1332  exit(1);
1333  }
1334 
1335  free(conflines);
1336 
1337  /* pg_ident.conf */
1338 
1339  conflines = readfile(ident_file);
1340 
1341  snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1342 
1343  writefile(path, conflines);
1344  if (chmod(path, pg_file_create_mode) != 0)
1345  {
1346  pg_log_error("could not change permissions of \"%s\": %m", path);
1347  exit(1);
1348  }
1349 
1350  free(conflines);
1351 
1352  check_ok();
1353 }
1354 
1355 
1356 /*
1357  * run the BKI script in bootstrap mode to create template1
1358  */
1359 static void
1361 {
1362  PG_CMD_DECL;
1363  char **line;
1364  char **bki_lines;
1365  char headerline[MAXPGPATH];
1366  char buf[64];
1367 
1368  printf(_("running bootstrap script ... "));
1369  fflush(stdout);
1370 
1371  bki_lines = readfile(bki_file);
1372 
1373  /* Check that bki file appears to be of the right version */
1374 
1375  snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1376  PG_MAJORVERSION);
1377 
1378  if (strcmp(headerline, *bki_lines) != 0)
1379  {
1380  pg_log_error("input file \"%s\" does not belong to PostgreSQL %s",
1381  bki_file, PG_VERSION);
1382  fprintf(stderr,
1383  _("Check your installation or specify the correct path "
1384  "using the option -L.\n"));
1385  exit(1);
1386  }
1387 
1388  /* Substitute for various symbols used in the BKI file */
1389 
1390  sprintf(buf, "%d", NAMEDATALEN);
1391  bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
1392 
1393  sprintf(buf, "%d", (int) sizeof(Pointer));
1394  bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
1395 
1396  bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
1397  (sizeof(Pointer) == 4) ? "i" : "d");
1398 
1399  bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
1400  FLOAT8PASSBYVAL ? "true" : "false");
1401 
1402  bki_lines = replace_token(bki_lines, "POSTGRES",
1404 
1405  bki_lines = replace_token(bki_lines, "ENCODING",
1407 
1408  bki_lines = replace_token(bki_lines, "LC_COLLATE",
1410 
1411  bki_lines = replace_token(bki_lines, "LC_CTYPE",
1413 
1414  /* Also ensure backend isn't confused by this environment var: */
1415  unsetenv("PGCLIENTENCODING");
1416 
1417  snprintf(cmd, sizeof(cmd),
1418  "\"%s\" --boot -x1 -X %u %s %s %s",
1419  backend_exec,
1420  wal_segment_size_mb * (1024 * 1024),
1421  data_checksums ? "-k" : "",
1422  boot_options,
1423  debug ? "-d 5" : "");
1424 
1425 
1426  PG_CMD_OPEN;
1427 
1428  for (line = bki_lines; *line != NULL; line++)
1429  {
1430  PG_CMD_PUTS(*line);
1431  free(*line);
1432  }
1433 
1434  PG_CMD_CLOSE;
1435 
1436  free(bki_lines);
1437 
1438  check_ok();
1439 }
1440 
1441 /*
1442  * set up the shadow password table
1443  */
1444 static void
1445 setup_auth(FILE *cmdfd)
1446 {
1447  const char *const *line;
1448  static const char *const pg_authid_setup[] = {
1449  /*
1450  * The authid table shouldn't be readable except through views, to
1451  * ensure passwords are not publicly visible.
1452  */
1453  "REVOKE ALL on pg_authid FROM public;\n\n",
1454  NULL
1455  };
1456 
1457  for (line = pg_authid_setup; *line != NULL; line++)
1458  PG_CMD_PUTS(*line);
1459 
1460  if (superuser_password)
1461  PG_CMD_PRINTF("ALTER USER \"%s\" WITH PASSWORD E'%s';\n\n",
1463 }
1464 
1465 /*
1466  * get the superuser password if required
1467  */
1468 static void
1470 {
1471  char *pwd1;
1472 
1473  if (pwprompt)
1474  {
1475  /*
1476  * Read password from terminal
1477  */
1478  char *pwd2;
1479 
1480  printf("\n");
1481  fflush(stdout);
1482  pwd1 = simple_prompt("Enter new superuser password: ", false);
1483  pwd2 = simple_prompt("Enter it again: ", false);
1484  if (strcmp(pwd1, pwd2) != 0)
1485  {
1486  fprintf(stderr, _("Passwords didn't match.\n"));
1487  exit(1);
1488  }
1489  free(pwd2);
1490  }
1491  else
1492  {
1493  /*
1494  * Read password from file
1495  *
1496  * Ideally this should insist that the file not be world-readable.
1497  * However, this option is mainly intended for use on Windows where
1498  * file permissions may not exist at all, so we'll skip the paranoia
1499  * for now.
1500  */
1501  FILE *pwf = fopen(pwfilename, "r");
1502 
1503  if (!pwf)
1504  {
1505  pg_log_error("could not open file \"%s\" for reading: %m",
1506  pwfilename);
1507  exit(1);
1508  }
1509  pwd1 = pg_get_line(pwf);
1510  if (!pwd1)
1511  {
1512  if (ferror(pwf))
1513  pg_log_error("could not read password from file \"%s\": %m",
1514  pwfilename);
1515  else
1516  pg_log_error("password file \"%s\" is empty",
1517  pwfilename);
1518  exit(1);
1519  }
1520  fclose(pwf);
1521 
1522  (void) pg_strip_crlf(pwd1);
1523  }
1524 
1525  superuser_password = pwd1;
1526 }
1527 
1528 /*
1529  * set up pg_depend
1530  */
1531 static void
1532 setup_depend(FILE *cmdfd)
1533 {
1534  const char *const *line;
1535  static const char *const pg_depend_setup[] = {
1536  /*
1537  * Make PIN entries in pg_depend for all objects made so far in the
1538  * tables that the dependency code handles. This is overkill (the
1539  * system doesn't really depend on having every last weird datatype,
1540  * for instance) but generating only the minimum required set of
1541  * dependencies seems hard.
1542  *
1543  * Catalogs that are intentionally not scanned here are:
1544  *
1545  * pg_database: it's a feature, not a bug, that template1 is not
1546  * pinned.
1547  *
1548  * pg_extension: a pinned extension isn't really an extension, hmm?
1549  *
1550  * pg_tablespace: tablespaces don't participate in the dependency
1551  * code, and DropTableSpace() explicitly protects the built-in
1552  * tablespaces.
1553  *
1554  * First delete any already-made entries; PINs override all else, and
1555  * must be the only entries for their objects.
1556  */
1557  "DELETE FROM pg_depend;\n\n",
1558  "VACUUM pg_depend;\n\n",
1559  "DELETE FROM pg_shdepend;\n\n",
1560  "VACUUM pg_shdepend;\n\n",
1561 
1562  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1563  " FROM pg_class;\n\n",
1564  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1565  " FROM pg_proc;\n\n",
1566  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1567  " FROM pg_type;\n\n",
1568  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1569  " FROM pg_cast;\n\n",
1570  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1571  " FROM pg_constraint;\n\n",
1572  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1573  " FROM pg_conversion;\n\n",
1574  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1575  " FROM pg_attrdef;\n\n",
1576  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1577  " FROM pg_language;\n\n",
1578  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1579  " FROM pg_operator;\n\n",
1580  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1581  " FROM pg_opclass;\n\n",
1582  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1583  " FROM pg_opfamily;\n\n",
1584  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1585  " FROM pg_am;\n\n",
1586  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1587  " FROM pg_amop;\n\n",
1588  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1589  " FROM pg_amproc;\n\n",
1590  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1591  " FROM pg_rewrite;\n\n",
1592  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1593  " FROM pg_trigger;\n\n",
1594 
1595  /*
1596  * restriction here to avoid pinning the public namespace
1597  */
1598  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1599  " FROM pg_namespace "
1600  " WHERE nspname LIKE 'pg%';\n\n",
1601 
1602  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1603  " FROM pg_ts_parser;\n\n",
1604  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1605  " FROM pg_ts_dict;\n\n",
1606  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1607  " FROM pg_ts_template;\n\n",
1608  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1609  " FROM pg_ts_config;\n\n",
1610  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1611  " FROM pg_collation;\n\n",
1612  "INSERT INTO pg_shdepend SELECT 0,0,0,0, tableoid,oid, 'p' "
1613  " FROM pg_authid;\n\n",
1614  NULL
1615  };
1616 
1617  for (line = pg_depend_setup; *line != NULL; line++)
1618  PG_CMD_PUTS(*line);
1619 }
1620 
1621 /*
1622  * set up system views
1623  */
1624 static void
1625 setup_sysviews(FILE *cmdfd)
1626 {
1627  char **line;
1628  char **sysviews_setup;
1629 
1630  sysviews_setup = readfile(system_views_file);
1631 
1632  for (line = sysviews_setup; *line != NULL; line++)
1633  {
1634  PG_CMD_PUTS(*line);
1635  free(*line);
1636  }
1637 
1638  PG_CMD_PUTS("\n\n");
1639 
1640  free(sysviews_setup);
1641 }
1642 
1643 /*
1644  * fill in extra description data
1645  */
1646 static void
1647 setup_description(FILE *cmdfd)
1648 {
1649  /* Create default descriptions for operator implementation functions */
1650  PG_CMD_PUTS("WITH funcdescs AS ( "
1651  "SELECT p.oid as p_oid, o.oid as o_oid, oprname "
1652  "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
1653  "INSERT INTO pg_description "
1654  " SELECT p_oid, 'pg_proc'::regclass, 0, "
1655  " 'implementation of ' || oprname || ' operator' "
1656  " FROM funcdescs "
1657  " WHERE NOT EXISTS (SELECT 1 FROM pg_description "
1658  " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass) "
1659  " AND NOT EXISTS (SELECT 1 FROM pg_description "
1660  " WHERE objoid = o_oid AND classoid = 'pg_operator'::regclass"
1661  " AND description LIKE 'deprecated%');\n\n");
1662 }
1663 
1664 /*
1665  * populate pg_collation
1666  */
1667 static void
1668 setup_collation(FILE *cmdfd)
1669 {
1670  /*
1671  * Add an SQL-standard name. We don't want to pin this, so it doesn't go
1672  * in pg_collation.h. But add it before reading system collations, so
1673  * that it wins if libc defines a locale named ucs_basic.
1674  */
1675  PG_CMD_PRINTF("INSERT INTO pg_collation (oid, collname, collnamespace, collowner, collprovider, collisdeterministic, collencoding, collcollate, collctype)"
1676  "VALUES (pg_nextoid('pg_catalog.pg_collation', 'oid', 'pg_catalog.pg_collation_oid_index'), 'ucs_basic', 'pg_catalog'::regnamespace, %u, '%c', true, %d, 'C', 'C');\n\n",
1677  BOOTSTRAP_SUPERUSERID, COLLPROVIDER_LIBC, PG_UTF8);
1678 
1679  /* Now import all collations we can find in the operating system */
1680  PG_CMD_PUTS("SELECT pg_import_system_collations('pg_catalog');\n\n");
1681 }
1682 
1683 /*
1684  * load extra dictionaries (Snowball stemmers)
1685  */
1686 static void
1687 setup_dictionary(FILE *cmdfd)
1688 {
1689  char **line;
1690  char **conv_lines;
1691 
1692  conv_lines = readfile(dictionary_file);
1693  for (line = conv_lines; *line != NULL; line++)
1694  {
1695  PG_CMD_PUTS(*line);
1696  free(*line);
1697  }
1698 
1699  PG_CMD_PUTS("\n\n");
1700 
1701  free(conv_lines);
1702 }
1703 
1704 /*
1705  * Set up privileges
1706  *
1707  * We mark most system catalogs as world-readable. We don't currently have
1708  * to touch functions, languages, or databases, because their default
1709  * permissions are OK.
1710  *
1711  * Some objects may require different permissions by default, so we
1712  * make sure we don't overwrite privilege sets that have already been
1713  * set (NOT NULL).
1714  *
1715  * Also populate pg_init_privs to save what the privileges are at init
1716  * time. This is used by pg_dump to allow users to change privileges
1717  * on catalog objects and to have those privilege changes preserved
1718  * across dump/reload and pg_upgrade.
1719  *
1720  * Note that pg_init_privs is only for per-database objects and therefore
1721  * we don't include databases or tablespaces.
1722  */
1723 static void
1724 setup_privileges(FILE *cmdfd)
1725 {
1726  char **line;
1727  char **priv_lines;
1728  static char *privileges_setup[] = {
1729  "UPDATE pg_class "
1730  " SET relacl = (SELECT array_agg(a.acl) FROM "
1731  " (SELECT E'=r/\"$POSTGRES_SUPERUSERNAME\"' as acl "
1732  " UNION SELECT unnest(pg_catalog.acldefault("
1733  " CASE WHEN relkind = " CppAsString2(RELKIND_SEQUENCE) " THEN 's' "
1734  " ELSE 'r' END::\"char\"," CppAsString2(BOOTSTRAP_SUPERUSERID) "::oid))"
1735  " ) as a) "
1736  " WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1737  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1738  CppAsString2(RELKIND_SEQUENCE) ")"
1739  " AND relacl IS NULL;\n\n",
1740  "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n\n",
1741  "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n\n",
1742  "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n",
1743  "INSERT INTO pg_init_privs "
1744  " (objoid, classoid, objsubid, initprivs, privtype)"
1745  " SELECT"
1746  " oid,"
1747  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1748  " 0,"
1749  " relacl,"
1750  " 'i'"
1751  " FROM"
1752  " pg_class"
1753  " WHERE"
1754  " relacl IS NOT NULL"
1755  " AND relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1756  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1757  CppAsString2(RELKIND_SEQUENCE) ");\n\n",
1758  "INSERT INTO pg_init_privs "
1759  " (objoid, classoid, objsubid, initprivs, privtype)"
1760  " SELECT"
1761  " pg_class.oid,"
1762  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1763  " pg_attribute.attnum,"
1764  " pg_attribute.attacl,"
1765  " 'i'"
1766  " FROM"
1767  " pg_class"
1768  " JOIN pg_attribute ON (pg_class.oid = pg_attribute.attrelid)"
1769  " WHERE"
1770  " pg_attribute.attacl IS NOT NULL"
1771  " AND pg_class.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1772  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1773  CppAsString2(RELKIND_SEQUENCE) ");\n\n",
1774  "INSERT INTO pg_init_privs "
1775  " (objoid, classoid, objsubid, initprivs, privtype)"
1776  " SELECT"
1777  " oid,"
1778  " (SELECT oid FROM pg_class WHERE relname = 'pg_proc'),"
1779  " 0,"
1780  " proacl,"
1781  " 'i'"
1782  " FROM"
1783  " pg_proc"
1784  " WHERE"
1785  " proacl IS NOT NULL;\n\n",
1786  "INSERT INTO pg_init_privs "
1787  " (objoid, classoid, objsubid, initprivs, privtype)"
1788  " SELECT"
1789  " oid,"
1790  " (SELECT oid FROM pg_class WHERE relname = 'pg_type'),"
1791  " 0,"
1792  " typacl,"
1793  " 'i'"
1794  " FROM"
1795  " pg_type"
1796  " WHERE"
1797  " typacl IS NOT NULL;\n\n",
1798  "INSERT INTO pg_init_privs "
1799  " (objoid, classoid, objsubid, initprivs, privtype)"
1800  " SELECT"
1801  " oid,"
1802  " (SELECT oid FROM pg_class WHERE relname = 'pg_language'),"
1803  " 0,"
1804  " lanacl,"
1805  " 'i'"
1806  " FROM"
1807  " pg_language"
1808  " WHERE"
1809  " lanacl IS NOT NULL;\n\n",
1810  "INSERT INTO pg_init_privs "
1811  " (objoid, classoid, objsubid, initprivs, privtype)"
1812  " SELECT"
1813  " oid,"
1814  " (SELECT oid FROM pg_class WHERE "
1815  " relname = 'pg_largeobject_metadata'),"
1816  " 0,"
1817  " lomacl,"
1818  " 'i'"
1819  " FROM"
1820  " pg_largeobject_metadata"
1821  " WHERE"
1822  " lomacl IS NOT NULL;\n\n",
1823  "INSERT INTO pg_init_privs "
1824  " (objoid, classoid, objsubid, initprivs, privtype)"
1825  " SELECT"
1826  " oid,"
1827  " (SELECT oid FROM pg_class WHERE relname = 'pg_namespace'),"
1828  " 0,"
1829  " nspacl,"
1830  " 'i'"
1831  " FROM"
1832  " pg_namespace"
1833  " WHERE"
1834  " nspacl IS NOT NULL;\n\n",
1835  "INSERT INTO pg_init_privs "
1836  " (objoid, classoid, objsubid, initprivs, privtype)"
1837  " SELECT"
1838  " oid,"
1839  " (SELECT oid FROM pg_class WHERE "
1840  " relname = 'pg_foreign_data_wrapper'),"
1841  " 0,"
1842  " fdwacl,"
1843  " 'i'"
1844  " FROM"
1845  " pg_foreign_data_wrapper"
1846  " WHERE"
1847  " fdwacl IS NOT NULL;\n\n",
1848  "INSERT INTO pg_init_privs "
1849  " (objoid, classoid, objsubid, initprivs, privtype)"
1850  " SELECT"
1851  " oid,"
1852  " (SELECT oid FROM pg_class "
1853  " WHERE relname = 'pg_foreign_server'),"
1854  " 0,"
1855  " srvacl,"
1856  " 'i'"
1857  " FROM"
1858  " pg_foreign_server"
1859  " WHERE"
1860  " srvacl IS NOT NULL;\n\n",
1861  NULL
1862  };
1863 
1864  priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
1866  for (line = priv_lines; *line != NULL; line++)
1867  PG_CMD_PUTS(*line);
1868 }
1869 
1870 /*
1871  * extract the strange version of version required for information schema
1872  * (09.08.0007abc)
1873  */
1874 static void
1876 {
1877  char *letterversion;
1878  long major = 0,
1879  minor = 0,
1880  micro = 0;
1881  char *endptr;
1882  char *vstr = pg_strdup(PG_VERSION);
1883  char *ptr;
1884 
1885  ptr = vstr + (strlen(vstr) - 1);
1886  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1887  ptr--;
1888  letterversion = ptr + 1;
1889  major = strtol(vstr, &endptr, 10);
1890  if (*endptr)
1891  minor = strtol(endptr + 1, &endptr, 10);
1892  if (*endptr)
1893  micro = strtol(endptr + 1, &endptr, 10);
1894  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1895  major, minor, micro, letterversion);
1896 }
1897 
1898 /*
1899  * load info schema and populate from features file
1900  */
1901 static void
1902 setup_schema(FILE *cmdfd)
1903 {
1904  char **line;
1905  char **lines;
1906 
1907  lines = readfile(info_schema_file);
1908 
1909  for (line = lines; *line != NULL; line++)
1910  {
1911  PG_CMD_PUTS(*line);
1912  free(*line);
1913  }
1914 
1915  PG_CMD_PUTS("\n\n");
1916 
1917  free(lines);
1918 
1919  PG_CMD_PRINTF("UPDATE information_schema.sql_implementation_info "
1920  " SET character_value = '%s' "
1921  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
1922  infoversion);
1923 
1924  PG_CMD_PRINTF("COPY information_schema.sql_features "
1925  " (feature_id, feature_name, sub_feature_id, "
1926  " sub_feature_name, is_supported, comments) "
1927  " FROM E'%s';\n\n",
1929 }
1930 
1931 /*
1932  * load PL/pgSQL server-side language
1933  */
1934 static void
1935 load_plpgsql(FILE *cmdfd)
1936 {
1937  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
1938 }
1939 
1940 /*
1941  * clean everything up in template1
1942  */
1943 static void
1944 vacuum_db(FILE *cmdfd)
1945 {
1946  /* Run analyze before VACUUM so the statistics are frozen. */
1947  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
1948 }
1949 
1950 /*
1951  * copy template1 to template0
1952  */
1953 static void
1954 make_template0(FILE *cmdfd)
1955 {
1956  const char *const *line;
1957  static const char *const template0_setup[] = {
1958  "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false;\n\n",
1959 
1960  /*
1961  * We use the OID of template0 to determine datlastsysoid
1962  */
1963  "UPDATE pg_database SET datlastsysoid = "
1964  " (SELECT oid FROM pg_database "
1965  " WHERE datname = 'template0');\n\n",
1966 
1967  /*
1968  * Explicitly revoke public create-schema and create-temp-table
1969  * privileges in template1 and template0; else the latter would be on
1970  * by default
1971  */
1972  "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n",
1973  "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n",
1974 
1975  "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n",
1976 
1977  /*
1978  * Finally vacuum to clean up dead rows in pg_database
1979  */
1980  "VACUUM pg_database;\n\n",
1981  NULL
1982  };
1983 
1984  for (line = template0_setup; *line; line++)
1985  PG_CMD_PUTS(*line);
1986 }
1987 
1988 /*
1989  * copy template1 to postgres
1990  */
1991 static void
1992 make_postgres(FILE *cmdfd)
1993 {
1994  const char *const *line;
1995  static const char *const postgres_setup[] = {
1996  "CREATE DATABASE postgres;\n\n",
1997  "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",
1998  NULL
1999  };
2000 
2001  for (line = postgres_setup; *line; line++)
2002  PG_CMD_PUTS(*line);
2003 }
2004 
2005 /*
2006  * signal handler in case we are interrupted.
2007  *
2008  * The Windows runtime docs at
2009  * https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/signal
2010  * specifically forbid a number of things being done from a signal handler,
2011  * including IO, memory allocation and system calls, and only allow jmpbuf
2012  * if you are handling SIGFPE.
2013  *
2014  * I avoided doing the forbidden things by setting a flag instead of calling
2015  * exit() directly.
2016  *
2017  * Also note the behaviour of Windows with SIGINT, which says this:
2018  * SIGINT is not supported for any Win32 application. When a CTRL+C interrupt
2019  * occurs, Win32 operating systems generate a new thread to specifically
2020  * handle that interrupt. This can cause a single-thread application, such as
2021  * one in UNIX, to become multithreaded and cause unexpected behavior.
2022  *
2023  * I have no idea how to handle this. (Strange they call UNIX an application!)
2024  * So this will need some testing on Windows.
2025  */
2026 static void
2027 trapsig(int signum)
2028 {
2029  /* handle systems that reset the handler, like Windows (grr) */
2030  pqsignal(signum, trapsig);
2031  caught_signal = true;
2032 }
2033 
2034 /*
2035  * call exit() if we got a signal, or else output "ok".
2036  */
2037 static void
2039 {
2040  if (caught_signal)
2041  {
2042  printf(_("caught signal\n"));
2043  fflush(stdout);
2044  exit(1);
2045  }
2046  else if (output_failed)
2047  {
2048  printf(_("could not write to child process: %s\n"),
2050  fflush(stdout);
2051  exit(1);
2052  }
2053  else
2054  {
2055  /* all seems well */
2056  printf(_("ok\n"));
2057  fflush(stdout);
2058  }
2059 }
2060 
2061 /* Hack to suppress a warning about %x from some versions of gcc */
2062 static inline size_t
2063 my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
2064 {
2065  return strftime(s, max, fmt, tm);
2066 }
2067 
2068 /*
2069  * Determine likely date order from locale
2070  */
2071 static int
2073 {
2074  struct tm testtime;
2075  char buf[128];
2076  char *posD;
2077  char *posM;
2078  char *posY;
2079  char *save;
2080  size_t res;
2081  int result;
2082 
2083  result = DATEORDER_MDY; /* default */
2084 
2085  save = setlocale(LC_TIME, NULL);
2086  if (!save)
2087  return result;
2088  save = pg_strdup(save);
2089 
2090  setlocale(LC_TIME, locale);
2091 
2092  memset(&testtime, 0, sizeof(testtime));
2093  testtime.tm_mday = 22;
2094  testtime.tm_mon = 10; /* November, should come out as "11" */
2095  testtime.tm_year = 133; /* 2033 */
2096 
2097  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
2098 
2099  setlocale(LC_TIME, save);
2100  free(save);
2101 
2102  if (res == 0)
2103  return result;
2104 
2105  posM = strstr(buf, "11");
2106  posD = strstr(buf, "22");
2107  posY = strstr(buf, "33");
2108 
2109  if (!posM || !posD || !posY)
2110  return result;
2111 
2112  if (posY < posM && posM < posD)
2113  result = DATEORDER_YMD;
2114  else if (posD < posM)
2115  result = DATEORDER_DMY;
2116  else
2117  result = DATEORDER_MDY;
2118 
2119  return result;
2120 }
2121 
2122 /*
2123  * Verify that locale name is valid for the locale category.
2124  *
2125  * If successful, and canonname isn't NULL, a malloc'd copy of the locale's
2126  * canonical name is stored there. This is especially useful for figuring out
2127  * what locale name "" means (ie, the environment value). (Actually,
2128  * it seems that on most implementations that's the only thing it's good for;
2129  * we could wish that setlocale gave back a canonically spelled version of
2130  * the locale name, but typically it doesn't.)
2131  *
2132  * this should match the backend's check_locale() function
2133  */
2134 static void
2135 check_locale_name(int category, const char *locale, char **canonname)
2136 {
2137  char *save;
2138  char *res;
2139 
2140  if (canonname)
2141  *canonname = NULL; /* in case of failure */
2142 
2143  save = setlocale(category, NULL);
2144  if (!save)
2145  {
2146  pg_log_error("setlocale() failed");
2147  exit(1);
2148  }
2149 
2150  /* save may be pointing at a modifiable scratch variable, so copy it. */
2151  save = pg_strdup(save);
2152 
2153  /* for setlocale() call */
2154  if (!locale)
2155  locale = "";
2156 
2157  /* set the locale with setlocale, to see if it accepts it. */
2158  res = setlocale(category, locale);
2159 
2160  /* save canonical name if requested. */
2161  if (res && canonname)
2162  *canonname = pg_strdup(res);
2163 
2164  /* restore old value. */
2165  if (!setlocale(category, save))
2166  {
2167  pg_log_error("failed to restore old locale \"%s\"", save);
2168  exit(1);
2169  }
2170  free(save);
2171 
2172  /* complain if locale wasn't valid */
2173  if (res == NULL)
2174  {
2175  if (*locale)
2176  pg_log_error("invalid locale name \"%s\"", locale);
2177  else
2178  {
2179  /*
2180  * If no relevant switch was given on command line, locale is an
2181  * empty string, which is not too helpful to report. Presumably
2182  * setlocale() found something it did not like in the environment.
2183  * Ideally we'd report the bad environment variable, but since
2184  * setlocale's behavior is implementation-specific, it's hard to
2185  * be sure what it didn't like. Print a safe generic message.
2186  */
2187  pg_log_error("invalid locale settings; check LANG and LC_* environment variables");
2188  }
2189  exit(1);
2190  }
2191 }
2192 
2193 /*
2194  * check if the chosen encoding matches the encoding required by the locale
2195  *
2196  * this should match the similar check in the backend createdb() function
2197  */
2198 static bool
2199 check_locale_encoding(const char *locale, int user_enc)
2200 {
2201  int locale_enc;
2202 
2203  locale_enc = pg_get_encoding_from_locale(locale, true);
2204 
2205  /* See notes in createdb() to understand these tests */
2206  if (!(locale_enc == user_enc ||
2207  locale_enc == PG_SQL_ASCII ||
2208  locale_enc == -1 ||
2209 #ifdef WIN32
2210  user_enc == PG_UTF8 ||
2211 #endif
2212  user_enc == PG_SQL_ASCII))
2213  {
2214  pg_log_error("encoding mismatch");
2215  fprintf(stderr,
2216  _("The encoding you selected (%s) and the encoding that the\n"
2217  "selected locale uses (%s) do not match. This would lead to\n"
2218  "misbehavior in various character string processing functions.\n"
2219  "Rerun %s and either do not specify an encoding explicitly,\n"
2220  "or choose a matching combination.\n"),
2221  pg_encoding_to_char(user_enc),
2222  pg_encoding_to_char(locale_enc),
2223  progname);
2224  return false;
2225  }
2226  return true;
2227 }
2228 
2229 /*
2230  * set up the locale variables
2231  *
2232  * assumes we have called setlocale(LC_ALL, "") -- see set_pglocale_pgservice
2233  */
2234 static void
2236 {
2237  char *canonname;
2238 
2239  /* set empty lc_* values to locale config if set */
2240 
2241  if (locale)
2242  {
2243  if (!lc_ctype)
2244  lc_ctype = locale;
2245  if (!lc_collate)
2246  lc_collate = locale;
2247  if (!lc_numeric)
2248  lc_numeric = locale;
2249  if (!lc_time)
2250  lc_time = locale;
2251  if (!lc_monetary)
2252  lc_monetary = locale;
2253  if (!lc_messages)
2254  lc_messages = locale;
2255  }
2256 
2257  /*
2258  * canonicalize locale names, and obtain any missing values from our
2259  * current environment
2260  */
2261 
2262  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2263  lc_ctype = canonname;
2264  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2265  lc_collate = canonname;
2266  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2267  lc_numeric = canonname;
2268  check_locale_name(LC_TIME, lc_time, &canonname);
2269  lc_time = canonname;
2270  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2271  lc_monetary = canonname;
2272 #if defined(LC_MESSAGES) && !defined(WIN32)
2273  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2274  lc_messages = canonname;
2275 #else
2276  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2277  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2278  lc_messages = canonname;
2279 #endif
2280 }
2281 
2282 /*
2283  * print help text
2284  */
2285 static void
2286 usage(const char *progname)
2287 {
2288  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2289  printf(_("Usage:\n"));
2290  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2291  printf(_("\nOptions:\n"));
2292  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2293  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2294  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2295  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2296  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2297  printf(_(" -g, --allow-group-access allow group read/execute on data directory\n"));
2298  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2299  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2300  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2301  " set default locale in the respective category for\n"
2302  " new databases (default taken from environment)\n"));
2303  printf(_(" --no-locale equivalent to --locale=C\n"));
2304  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2305  printf(_(" -T, --text-search-config=CFG\n"
2306  " default text search configuration\n"));
2307  printf(_(" -U, --username=NAME database superuser name\n"));
2308  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2309  printf(_(" -X, --waldir=WALDIR location for the write-ahead log directory\n"));
2310  printf(_(" --wal-segsize=SIZE size of WAL segments, in megabytes\n"));
2311  printf(_("\nLess commonly used options:\n"));
2312  printf(_(" -d, --debug generate lots of debugging output\n"));
2313  printf(_(" -k, --data-checksums use data page checksums\n"));
2314  printf(_(" -L DIRECTORY where to find the input files\n"));
2315  printf(_(" -n, --no-clean do not clean up after errors\n"));
2316  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
2317  printf(_(" -s, --show show internal settings\n"));
2318  printf(_(" -S, --sync-only only sync data directory\n"));
2319  printf(_("\nOther options:\n"));
2320  printf(_(" -V, --version output version information, then exit\n"));
2321  printf(_(" -?, --help show this help, then exit\n"));
2322  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2323  "is used.\n"));
2324  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2325  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2326 }
2327 
2328 static void
2329 check_authmethod_unspecified(const char **authmethod)
2330 {
2331  if (*authmethod == NULL)
2332  {
2333  authwarning = true;
2334  *authmethod = "trust";
2335  }
2336 }
2337 
2338 static void
2339 check_authmethod_valid(const char *authmethod, const char *const *valid_methods, const char *conntype)
2340 {
2341  const char *const *p;
2342 
2343  for (p = valid_methods; *p; p++)
2344  {
2345  if (strcmp(authmethod, *p) == 0)
2346  return;
2347  /* with space = param */
2348  if (strchr(authmethod, ' '))
2349  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2350  return;
2351  }
2352 
2353  pg_log_error("invalid authentication method \"%s\" for \"%s\" connections",
2354  authmethod, conntype);
2355  exit(1);
2356 }
2357 
2358 static void
2360 {
2361  if ((strcmp(authmethodlocal, "md5") == 0 ||
2362  strcmp(authmethodlocal, "password") == 0 ||
2363  strcmp(authmethodlocal, "scram-sha-256") == 0) &&
2364  (strcmp(authmethodhost, "md5") == 0 ||
2365  strcmp(authmethodhost, "password") == 0 ||
2366  strcmp(authmethodhost, "scram-sha-256") == 0) &&
2367  !(pwprompt || pwfilename))
2368  {
2369  pg_log_error("must specify a password for the superuser to enable password authentication");
2370  exit(1);
2371  }
2372 }
2373 
2374 
2375 void
2377 {
2378  char *pgdata_get_env,
2379  *pgdata_set_env;
2380 
2381  if (!pg_data)
2382  {
2383  pgdata_get_env = getenv("PGDATA");
2384  if (pgdata_get_env && strlen(pgdata_get_env))
2385  {
2386  /* PGDATA found */
2387  pg_data = pg_strdup(pgdata_get_env);
2388  }
2389  else
2390  {
2391  pg_log_error("no data directory specified");
2392  fprintf(stderr,
2393  _("You must identify the directory where the data for this database system\n"
2394  "will reside. Do this with either the invocation option -D or the\n"
2395  "environment variable PGDATA.\n"));
2396  exit(1);
2397  }
2398  }
2399 
2402 
2403  /*
2404  * we have to set PGDATA for postgres rather than pass it on the command
2405  * line to avoid dumb quoting problems on Windows, and we would especially
2406  * need quotes otherwise on Windows because paths there are most likely to
2407  * have embedded spaces.
2408  */
2409  pgdata_set_env = psprintf("PGDATA=%s", pg_data);
2410  putenv(pgdata_set_env);
2411 }
2412 
2413 
2414 void
2416 {
2417  int ret;
2418 
2419  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2420  backend_exec)) < 0)
2421  {
2422  char full_path[MAXPGPATH];
2423 
2424  if (find_my_exec(argv0, full_path) < 0)
2425  strlcpy(full_path, progname, sizeof(full_path));
2426 
2427  if (ret == -1)
2428  pg_log_error("The program \"%s\" is needed by %s but was not found in the\n"
2429  "same directory as \"%s\".\n"
2430  "Check your installation.",
2431  "postgres", progname, full_path);
2432  else
2433  pg_log_error("The program \"%s\" was found by \"%s\"\n"
2434  "but was not the same version as %s.\n"
2435  "Check your installation.",
2436  "postgres", full_path, progname);
2437  exit(1);
2438  }
2439 
2440  /* store binary directory */
2441  strcpy(bin_path, backend_exec);
2442  *last_dir_separator(bin_path) = '\0';
2444 
2445  if (!share_path)
2446  {
2449  }
2450  else if (!is_absolute_path(share_path))
2451  {
2452  pg_log_error("input file location must be an absolute path");
2453  exit(1);
2454  }
2455 
2457 }
2458 
2459 void
2461 {
2462  setlocales();
2463 
2464  if (strcmp(lc_ctype, lc_collate) == 0 &&
2465  strcmp(lc_ctype, lc_time) == 0 &&
2466  strcmp(lc_ctype, lc_numeric) == 0 &&
2467  strcmp(lc_ctype, lc_monetary) == 0 &&
2468  strcmp(lc_ctype, lc_messages) == 0)
2469  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2470  else
2471  {
2472  printf(_("The database cluster will be initialized with locales\n"
2473  " COLLATE: %s\n"
2474  " CTYPE: %s\n"
2475  " MESSAGES: %s\n"
2476  " MONETARY: %s\n"
2477  " NUMERIC: %s\n"
2478  " TIME: %s\n"),
2479  lc_collate,
2480  lc_ctype,
2481  lc_messages,
2482  lc_monetary,
2483  lc_numeric,
2484  lc_time);
2485  }
2486 
2487  if (!encoding)
2488  {
2489  int ctype_enc;
2490 
2491  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2492 
2493  if (ctype_enc == -1)
2494  {
2495  /* Couldn't recognize the locale's codeset */
2496  pg_log_error("could not find suitable encoding for locale \"%s\"",
2497  lc_ctype);
2498  fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2499  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2500  progname);
2501  exit(1);
2502  }
2503  else if (!pg_valid_server_encoding_id(ctype_enc))
2504  {
2505  /*
2506  * We recognized it, but it's not a legal server encoding. On
2507  * Windows, UTF-8 works with any locale, so we can fall back to
2508  * UTF-8.
2509  */
2510 #ifdef WIN32
2511  encodingid = PG_UTF8;
2512  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2513  "The default database encoding will be set to \"%s\" instead.\n"),
2514  pg_encoding_to_char(ctype_enc),
2516 #else
2517  pg_log_error("locale \"%s\" requires unsupported encoding \"%s\"",
2518  lc_ctype, pg_encoding_to_char(ctype_enc));
2519  fprintf(stderr,
2520  _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
2521  "Rerun %s with a different locale selection.\n"),
2522  pg_encoding_to_char(ctype_enc), progname);
2523  exit(1);
2524 #endif
2525  }
2526  else
2527  {
2528  encodingid = ctype_enc;
2529  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2531  }
2532  }
2533  else
2535 
2538  exit(1); /* check_locale_encoding printed the error */
2539 
2540 }
2541 
2542 
2543 void
2545 {
2546  set_input(&bki_file, "postgres.bki");
2547  set_input(&hba_file, "pg_hba.conf.sample");
2548  set_input(&ident_file, "pg_ident.conf.sample");
2549  set_input(&conf_file, "postgresql.conf.sample");
2550  set_input(&dictionary_file, "snowball_create.sql");
2551  set_input(&info_schema_file, "information_schema.sql");
2552  set_input(&features_file, "sql_features.txt");
2553  set_input(&system_views_file, "system_views.sql");
2554 
2555  if (show_setting || debug)
2556  {
2557  fprintf(stderr,
2558  "VERSION=%s\n"
2559  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2560  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2561  "POSTGRESQL_CONF_SAMPLE=%s\n"
2562  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2563  PG_VERSION,
2565  username, bki_file,
2566  conf_file,
2567  hba_file, ident_file);
2568  if (show_setting)
2569  exit(0);
2570  }
2571 
2580 }
2581 
2582 
2583 void
2585 {
2587  {
2590  {
2591  pg_log_info("could not find suitable text search configuration for locale \"%s\"",
2592  lc_ctype);
2593  default_text_search_config = "simple";
2594  }
2595  }
2596  else
2597  {
2598  const char *checkmatch = find_matching_ts_config(lc_ctype);
2599 
2600  if (checkmatch == NULL)
2601  {
2602  pg_log_warning("suitable text search configuration for locale \"%s\" is unknown",
2603  lc_ctype);
2604  }
2605  else if (strcmp(checkmatch, default_text_search_config) != 0)
2606  {
2607  pg_log_warning("specified text search configuration \"%s\" might not match locale \"%s\"",
2609  }
2610  }
2611 
2612  printf(_("The default text search configuration will be set to \"%s\".\n"),
2614 
2615 }
2616 
2617 
2618 void
2620 {
2621  /* some of these are not valid on Windows */
2622 #ifdef SIGHUP
2624 #endif
2625 #ifdef SIGINT
2626  pqsignal(SIGINT, trapsig);
2627 #endif
2628 #ifdef SIGQUIT
2630 #endif
2631 #ifdef SIGTERM
2632  pqsignal(SIGTERM, trapsig);
2633 #endif
2634 
2635  /* Ignore SIGPIPE when writing to backend, so we can clean up */
2636 #ifdef SIGPIPE
2638 #endif
2639 
2640  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
2641 #ifdef SIGSYS
2642  pqsignal(SIGSYS, SIG_IGN);
2643 #endif
2644 }
2645 
2646 
2647 void
2649 {
2650  int ret;
2651 
2652  switch ((ret = pg_check_dir(pg_data)))
2653  {
2654  case 0:
2655  /* PGDATA not there, must create it */
2656  printf(_("creating directory %s ... "),
2657  pg_data);
2658  fflush(stdout);
2659 
2661  {
2662  pg_log_error("could not create directory \"%s\": %m", pg_data);
2663  exit(1);
2664  }
2665  else
2666  check_ok();
2667 
2668  made_new_pgdata = true;
2669  break;
2670 
2671  case 1:
2672  /* Present but empty, fix permissions and use it */
2673  printf(_("fixing permissions on existing directory %s ... "),
2674  pg_data);
2675  fflush(stdout);
2676 
2677  if (chmod(pg_data, pg_dir_create_mode) != 0)
2678  {
2679  pg_log_error("could not change permissions of directory \"%s\": %m",
2680  pg_data);
2681  exit(1);
2682  }
2683  else
2684  check_ok();
2685 
2686  found_existing_pgdata = true;
2687  break;
2688 
2689  case 2:
2690  case 3:
2691  case 4:
2692  /* Present and not empty */
2693  pg_log_error("directory \"%s\" exists but is not empty", pg_data);
2694  if (ret != 4)
2695  warn_on_mount_point(ret);
2696  else
2697  fprintf(stderr,
2698  _("If you want to create a new database system, either remove or empty\n"
2699  "the directory \"%s\" or run %s\n"
2700  "with an argument other than \"%s\".\n"),
2702  exit(1); /* no further message needed */
2703 
2704  default:
2705  /* Trouble accessing directory */
2706  pg_log_error("could not access directory \"%s\": %m", pg_data);
2707  exit(1);
2708  }
2709 }
2710 
2711 
2712 /* Create WAL directory, and symlink if required */
2713 void
2715 {
2716  char *subdirloc;
2717 
2718  /* form name of the place for the subdirectory or symlink */
2719  subdirloc = psprintf("%s/pg_wal", pg_data);
2720 
2721  if (xlog_dir)
2722  {
2723  int ret;
2724 
2725  /* clean up xlog directory name, check it's absolute */
2727  if (!is_absolute_path(xlog_dir))
2728  {
2729  pg_log_error("WAL directory location must be an absolute path");
2730  exit(1);
2731  }
2732 
2733  /* check if the specified xlog directory exists/is empty */
2734  switch ((ret = pg_check_dir(xlog_dir)))
2735  {
2736  case 0:
2737  /* xlog directory not there, must create it */
2738  printf(_("creating directory %s ... "),
2739  xlog_dir);
2740  fflush(stdout);
2741 
2743  {
2744  pg_log_error("could not create directory \"%s\": %m",
2745  xlog_dir);
2746  exit(1);
2747  }
2748  else
2749  check_ok();
2750 
2751  made_new_xlogdir = true;
2752  break;
2753 
2754  case 1:
2755  /* Present but empty, fix permissions and use it */
2756  printf(_("fixing permissions on existing directory %s ... "),
2757  xlog_dir);
2758  fflush(stdout);
2759 
2760  if (chmod(xlog_dir, pg_dir_create_mode) != 0)
2761  {
2762  pg_log_error("could not change permissions of directory \"%s\": %m",
2763  xlog_dir);
2764  exit(1);
2765  }
2766  else
2767  check_ok();
2768 
2769  found_existing_xlogdir = true;
2770  break;
2771 
2772  case 2:
2773  case 3:
2774  case 4:
2775  /* Present and not empty */
2776  pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
2777  if (ret != 4)
2778  warn_on_mount_point(ret);
2779  else
2780  fprintf(stderr,
2781  _("If you want to store the WAL there, either remove or empty the directory\n"
2782  "\"%s\".\n"),
2783  xlog_dir);
2784  exit(1);
2785 
2786  default:
2787  /* Trouble accessing directory */
2788  pg_log_error("could not access directory \"%s\": %m", xlog_dir);
2789  exit(1);
2790  }
2791 
2792 #ifdef HAVE_SYMLINK
2793  if (symlink(xlog_dir, subdirloc) != 0)
2794  {
2795  pg_log_error("could not create symbolic link \"%s\": %m",
2796  subdirloc);
2797  exit(1);
2798  }
2799 #else
2800  pg_log_error("symlinks are not supported on this platform");
2801  exit(1);
2802 #endif
2803  }
2804  else
2805  {
2806  /* Without -X option, just make the subdirectory normally */
2807  if (mkdir(subdirloc, pg_dir_create_mode) < 0)
2808  {
2809  pg_log_error("could not create directory \"%s\": %m",
2810  subdirloc);
2811  exit(1);
2812  }
2813  }
2814 
2815  free(subdirloc);
2816 }
2817 
2818 
2819 void
2821 {
2822  if (error == 2)
2823  fprintf(stderr,
2824  _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
2825  else if (error == 3)
2826  fprintf(stderr,
2827  _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
2828 
2829  fprintf(stderr,
2830  _("Using a mount point directly as the data directory is not recommended.\n"
2831  "Create a subdirectory under the mount point.\n"));
2832 }
2833 
2834 
2835 void
2837 {
2838  PG_CMD_DECL;
2839  int i;
2840 
2841  setup_signals();
2842 
2843  /*
2844  * Set mask based on requested PGDATA permissions. pg_mode_mask, and
2845  * friends like pg_dir_create_mode, are set to owner-only by default and
2846  * then updated if -g is passed in by calling SetDataDirectoryCreatePerm()
2847  * when parsing our options (see above).
2848  */
2849  umask(pg_mode_mask);
2850 
2852 
2854 
2855  /* Create required subdirectories (other than pg_wal) */
2856  printf(_("creating subdirectories ... "));
2857  fflush(stdout);
2858 
2859  for (i = 0; i < lengthof(subdirs); i++)
2860  {
2861  char *path;
2862 
2863  path = psprintf("%s/%s", pg_data, subdirs[i]);
2864 
2865  /*
2866  * The parent directory already exists, so we only need mkdir() not
2867  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
2868  */
2869  if (mkdir(path, pg_dir_create_mode) < 0)
2870  {
2871  pg_log_error("could not create directory \"%s\": %m", path);
2872  exit(1);
2873  }
2874 
2875  free(path);
2876  }
2877 
2878  check_ok();
2879 
2880  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2881  write_version_file(NULL);
2882 
2883  /* Select suitable configuration settings */
2884  set_null_conf();
2886 
2887  /* Now create all the text config files */
2888  setup_config();
2889 
2890  /* Bootstrap template1 */
2892 
2893  /*
2894  * Make the per-database PG_VERSION for template1 only after init'ing it
2895  */
2896  write_version_file("base/1");
2897 
2898  /*
2899  * Create the stuff we don't need to use bootstrap mode for, using a
2900  * backend running in simple standalone mode.
2901  */
2902  fputs(_("performing post-bootstrap initialization ... "), stdout);
2903  fflush(stdout);
2904 
2905  snprintf(cmd, sizeof(cmd),
2906  "\"%s\" %s template1 >%s",
2908  DEVNULL);
2909 
2910  PG_CMD_OPEN;
2911 
2912  setup_auth(cmdfd);
2913 
2914  setup_depend(cmdfd);
2915 
2916  /*
2917  * Note that no objects created after setup_depend() will be "pinned".
2918  * They are all droppable at the whim of the DBA.
2919  */
2920 
2921  setup_sysviews(cmdfd);
2922 
2923  setup_description(cmdfd);
2924 
2925  setup_collation(cmdfd);
2926 
2927  setup_dictionary(cmdfd);
2928 
2929  setup_privileges(cmdfd);
2930 
2931  setup_schema(cmdfd);
2932 
2933  load_plpgsql(cmdfd);
2934 
2935  vacuum_db(cmdfd);
2936 
2937  make_template0(cmdfd);
2938 
2939  make_postgres(cmdfd);
2940 
2941  PG_CMD_CLOSE;
2942 
2943  check_ok();
2944 }
2945 
2946 
2947 int
2948 main(int argc, char *argv[])
2949 {
2950  static struct option long_options[] = {
2951  {"pgdata", required_argument, NULL, 'D'},
2952  {"encoding", required_argument, NULL, 'E'},
2953  {"locale", required_argument, NULL, 1},
2954  {"lc-collate", required_argument, NULL, 2},
2955  {"lc-ctype", required_argument, NULL, 3},
2956  {"lc-monetary", required_argument, NULL, 4},
2957  {"lc-numeric", required_argument, NULL, 5},
2958  {"lc-time", required_argument, NULL, 6},
2959  {"lc-messages", required_argument, NULL, 7},
2960  {"no-locale", no_argument, NULL, 8},
2961  {"text-search-config", required_argument, NULL, 'T'},
2962  {"auth", required_argument, NULL, 'A'},
2963  {"auth-local", required_argument, NULL, 10},
2964  {"auth-host", required_argument, NULL, 11},
2965  {"pwprompt", no_argument, NULL, 'W'},
2966  {"pwfile", required_argument, NULL, 9},
2967  {"username", required_argument, NULL, 'U'},
2968  {"help", no_argument, NULL, '?'},
2969  {"version", no_argument, NULL, 'V'},
2970  {"debug", no_argument, NULL, 'd'},
2971  {"show", no_argument, NULL, 's'},
2972  {"noclean", no_argument, NULL, 'n'}, /* for backwards compatibility */
2973  {"no-clean", no_argument, NULL, 'n'},
2974  {"nosync", no_argument, NULL, 'N'}, /* for backwards compatibility */
2975  {"no-sync", no_argument, NULL, 'N'},
2976  {"sync-only", no_argument, NULL, 'S'},
2977  {"waldir", required_argument, NULL, 'X'},
2978  {"wal-segsize", required_argument, NULL, 12},
2979  {"data-checksums", no_argument, NULL, 'k'},
2980  {"allow-group-access", no_argument, NULL, 'g'},
2981  {NULL, 0, NULL, 0}
2982  };
2983 
2984  /*
2985  * options with no short version return a low integer, the rest return
2986  * their short version value
2987  */
2988  int c;
2989  int option_index;
2990  char *effective_user;
2991  PQExpBuffer start_db_cmd;
2992  char pg_ctl_path[MAXPGPATH];
2993 
2994  /*
2995  * Ensure that buffering behavior of stdout matches what it is in
2996  * interactive usage (at least on most platforms). This prevents
2997  * unexpected output ordering when, eg, output is redirected to a file.
2998  * POSIX says we must do this before any other usage of these files.
2999  */
3000  setvbuf(stdout, NULL, PG_IOLBF, 0);
3001 
3002  pg_logging_init(argv[0]);
3003  progname = get_progname(argv[0]);
3004  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
3005 
3006  if (argc > 1)
3007  {
3008  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
3009  {
3010  usage(progname);
3011  exit(0);
3012  }
3013  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
3014  {
3015  puts("initdb (PostgreSQL) " PG_VERSION);
3016  exit(0);
3017  }
3018  }
3019 
3020  /* process command-line options */
3021 
3022  while ((c = getopt_long(argc, argv, "dD:E:kL:nNU:WA:sST:X:g", long_options, &option_index)) != -1)
3023  {
3024  switch (c)
3025  {
3026  case 'A':
3028 
3029  /*
3030  * When ident is specified, use peer for local connections.
3031  * Mirrored, when peer is specified, use ident for TCP/IP
3032  * connections.
3033  */
3034  if (strcmp(authmethodhost, "ident") == 0)
3035  authmethodlocal = "peer";
3036  else if (strcmp(authmethodlocal, "peer") == 0)
3037  authmethodhost = "ident";
3038  break;
3039  case 10:
3041  break;
3042  case 11:
3044  break;
3045  case 'D':
3047  break;
3048  case 'E':
3050  break;
3051  case 'W':
3052  pwprompt = true;
3053  break;
3054  case 'U':
3056  break;
3057  case 'd':
3058  debug = true;
3059  printf(_("Running in debug mode.\n"));
3060  break;
3061  case 'n':
3062  noclean = true;
3063  printf(_("Running in no-clean mode. Mistakes will not be cleaned up.\n"));
3064  break;
3065  case 'N':
3066  do_sync = false;
3067  break;
3068  case 'S':
3069  sync_only = true;
3070  break;
3071  case 'k':
3072  data_checksums = true;
3073  break;
3074  case 'L':
3076  break;
3077  case 1:
3078  locale = pg_strdup(optarg);
3079  break;
3080  case 2:
3082  break;
3083  case 3:
3085  break;
3086  case 4:
3088  break;
3089  case 5:
3091  break;
3092  case 6:
3094  break;
3095  case 7:
3097  break;
3098  case 8:
3099  locale = "C";
3100  break;
3101  case 9:
3103  break;
3104  case 's':
3105  show_setting = true;
3106  break;
3107  case 'T':
3109  break;
3110  case 'X':
3112  break;
3113  case 12:
3115  break;
3116  case 'g':
3118  break;
3119  default:
3120  /* getopt_long already emitted a complaint */
3121  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3122  progname);
3123  exit(1);
3124  }
3125  }
3126 
3127 
3128  /*
3129  * Non-option argument specifies data directory as long as it wasn't
3130  * already specified with -D / --pgdata
3131  */
3132  if (optind < argc && !pg_data)
3133  {
3134  pg_data = pg_strdup(argv[optind]);
3135  optind++;
3136  }
3137 
3138  if (optind < argc)
3139  {
3140  pg_log_error("too many command-line arguments (first is \"%s\")",
3141  argv[optind]);
3142  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3143  progname);
3144  exit(1);
3145  }
3146 
3148 
3149  /* If we only need to fsync, just do it and exit */
3150  if (sync_only)
3151  {
3152  setup_pgdata();
3153 
3154  /* must check that directory is readable */
3155  if (pg_check_dir(pg_data) <= 0)
3156  {
3157  pg_log_error("could not access directory \"%s\": %m", pg_data);
3158  exit(1);
3159  }
3160 
3161  fputs(_("syncing data to disk ... "), stdout);
3162  fflush(stdout);
3163  fsync_pgdata(pg_data, PG_VERSION_NUM);
3164  check_ok();
3165  return 0;
3166  }
3167 
3168  if (pwprompt && pwfilename)
3169  {
3170  pg_log_error("password prompt and password file cannot be specified together");
3171  exit(1);
3172  }
3173 
3176 
3179 
3181 
3182  /* set wal segment size */
3183  if (str_wal_segment_size_mb == NULL)
3184  wal_segment_size_mb = (DEFAULT_XLOG_SEG_SIZE) / (1024 * 1024);
3185  else
3186  {
3187  char *endptr;
3188 
3189  /* check that the argument is a number */
3190  wal_segment_size_mb = strtol(str_wal_segment_size_mb, &endptr, 10);
3191 
3192  /* verify that wal segment size is valid */
3193  if (endptr == str_wal_segment_size_mb || *endptr != '\0')
3194  {
3195  pg_log_error("argument of --wal-segsize must be a number");
3196  exit(1);
3197  }
3198  if (!IsValidWalSegSize(wal_segment_size_mb * 1024 * 1024))
3199  {
3200  pg_log_error("argument of --wal-segsize must be a power of 2 between 1 and 1024");
3201  exit(1);
3202  }
3203  }
3204 
3206 
3207  setup_pgdata();
3208 
3209  setup_bin_paths(argv[0]);
3210 
3211  effective_user = get_id();
3212  if (!username)
3213  username = effective_user;
3214 
3215  if (strncmp(username, "pg_", 3) == 0)
3216  {
3217  pg_log_error("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
3218  exit(1);
3219  }
3220 
3221  printf(_("The files belonging to this database system will be owned "
3222  "by user \"%s\".\n"
3223  "This user must also own the server process.\n\n"),
3224  effective_user);
3225 
3226  set_info_version();
3227 
3229 
3231 
3233 
3234  printf("\n");
3235 
3236  if (data_checksums)
3237  printf(_("Data page checksums are enabled.\n"));
3238  else
3239  printf(_("Data page checksums are disabled.\n"));
3240 
3241  if (pwprompt || pwfilename)
3242  get_su_pwd();
3243 
3244  printf("\n");
3245 
3247 
3248  if (do_sync)
3249  {
3250  fputs(_("syncing data to disk ... "), stdout);
3251  fflush(stdout);
3252  fsync_pgdata(pg_data, PG_VERSION_NUM);
3253  check_ok();
3254  }
3255  else
3256  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3257 
3258  if (authwarning)
3259  {
3260  printf("\n");
3261  pg_log_warning("enabling \"trust\" authentication for local connections");
3262  fprintf(stderr, _("You can change this by editing pg_hba.conf or using the option -A, or\n"
3263  "--auth-local and --auth-host, the next time you run initdb.\n"));
3264  }
3265 
3266  /*
3267  * Build up a shell command to tell the user how to start the server
3268  */
3269  start_db_cmd = createPQExpBuffer();
3270 
3271  /* Get directory specification used to start initdb ... */
3272  strlcpy(pg_ctl_path, argv[0], sizeof(pg_ctl_path));
3273  canonicalize_path(pg_ctl_path);
3274  get_parent_directory(pg_ctl_path);
3275  /* ... and tag on pg_ctl instead */
3276  join_path_components(pg_ctl_path, pg_ctl_path, "pg_ctl");
3277 
3278  /* path to pg_ctl, properly quoted */
3279  appendShellString(start_db_cmd, pg_ctl_path);
3280 
3281  /* add -D switch, with properly quoted data directory */
3282  appendPQExpBufferStr(start_db_cmd, " -D ");
3283  appendShellString(start_db_cmd, pgdata_native);
3284 
3285  /* add suggested -l switch and "start" command */
3286  /* translator: This is a placeholder in a shell command. */
3287  appendPQExpBuffer(start_db_cmd, " -l %s start", _("logfile"));
3288 
3289  printf(_("\nSuccess. You can now start the database server using:\n\n"
3290  " %s\n\n"),
3291  start_db_cmd->data);
3292 
3293  destroyPQExpBuffer(start_db_cmd);
3294 
3295  success = true;
3296  return 0;
3297 }
static int encodingid
Definition: initdb.c:153
static const char * default_timezone
Definition: initdb.c:177
static char * lc_monetary
Definition: initdb.c:129
bool pg_get_line_buf(FILE *stream, StringInfo buf)
Definition: pg_get_line.c:88
#define IsValidWalSegSize(size)
Definition: xlog_internal.h:94
static const char * find_matching_ts_config(const char *lc_type)
Definition: initdb.c:735
#define getaddrinfo
Definition: getaddrinfo.h:136
static void cleanup_directories_atexit(void)
Definition: initdb.c:564
static PgChecksumMode mode
Definition: pg_checksums.c:61
void setup_data_file_paths(void)
Definition: initdb.c:2544
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:323
#define SIGQUIT
Definition: win32_port.h:154
static void setup_depend(FILE *cmdfd)
Definition: initdb.c:1532
#define MIN_BUFS_FOR_CONNS(nconns)
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:386
int pg_file_create_mode
Definition: file_perm.c:19
static char * argv0
Definition: pg_ctl.c:97
void setup_locale_encoding(void)
Definition: initdb.c:2460
static FILE * popen_check(const char *command, const char *mode)
Definition: initdb.c:546
static char infoversion[100]
Definition: initdb.c:167
#define DEFAULT_CHECKPOINT_FLUSH_AFTER
static bool debug
Definition: initdb.c:140
static void vacuum_db(FILE *cmdfd)
Definition: initdb.c:1944
static char * system_views_file
Definition: initdb.c:161
int pg_strip_crlf(char *str)
Definition: string.c:105
static void error(void)
Definition: sql-dyntest.c:147
#define setlocale(a, b)
Definition: win32_port.h:408
static char * lc_collate
Definition: initdb.c:127
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
static char * encodingid_to_string(int enc)
Definition: initdb.c:638
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
void warn_on_mount_point(int error)
Definition: initdb.c:2820
static char * conf_file
Definition: initdb.c:157
const char * get_progname(const char *argv0)
Definition: path.c:453
static const char * backend_options
Definition: initdb.c:200
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
#define pg_log_error(...)
Definition: logging.h:80
#define DEFAULT_BGWRITER_FLUSH_AFTER
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
long random(void)
Definition: random.c:22
static char * features_file
Definition: initdb.c:160
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void get_restricted_token(void)
void pg_logging_init(const char *argv0)
Definition: logging.c:81
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void setup_auth(FILE *cmdfd)
Definition: initdb.c:1445
static void setup_dictionary(FILE *cmdfd)
Definition: initdb.c:1687
static bool made_new_xlogdir
Definition: initdb.c:165
#define DEFAULT_XLOG_SEG_SIZE
#define AUTHTRUST_WARNING
Definition: initdb.c:182
void canonicalize_path(char *path)
Definition: path.c:254
static bool caught_signal
Definition: initdb.c:168
int pg_valid_server_encoding_id(int encoding)
Definition: encnames.c:514
void create_xlog_or_symlink(void)
Definition: initdb.c:2714
static void bootstrap_template1(void)
Definition: initdb.c:1360
#define PG_BINARY_W
Definition: c.h:1214
#define PG_CMD_PRINTF(fmt,...)
Definition: initdb.c:309
#define printf(...)
Definition: port.h:199
void setup_signals(void)
Definition: initdb.c:2619
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static const struct tsearch_config_match tsearch_config_languages[]
Definition: initdb.c:674
static const char * choose_dsm_implementation(void)
Definition: initdb.c:888
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define lengthof(array)
Definition: c.h:675
#define SIGPIPE
Definition: win32_port.h:158
static bool pwprompt
Definition: initdb.c:135
static char * pgdata_native
Definition: initdb.c:171
#define PG_CMD_PUTS(line)
Definition: initdb.c:303
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
static chr newline(void)
Definition: regc_lex.c:1138
static void get_su_pwd(void)
Definition: initdb.c:1469
#define fprintf
Definition: port.h:197
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static char * get_id(void)
Definition: initdb.c:617
static char * share_path
Definition: initdb.c:121
static struct pg_tm tm
Definition: localtime.c:102
static void set_null_conf(void)
Definition: initdb.c:856
static const char * authmethodlocal
Definition: initdb.c:139
static int get_encoding_id(const char *encoding_name)
Definition: initdb.c:650
#define NAMEDATALEN
static char * lc_time
Definition: initdb.c:131
#define sprintf
Definition: port.h:195
static void check_input(char *path)
Definition: initdb.c:790
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
static int n_connections
Definition: initdb.c:174
static void check_authmethod_unspecified(const char **authmethod)
Definition: initdb.c:2329
char * escape_single_quotes_ascii(const char *src)
Definition: quotes.c:33
#define required_argument
Definition: getopt_long.h:25
void pfree(void *pointer)
Definition: mcxt.c:1057
char * Pointer
Definition: c.h:351
int optind
Definition: getopt.c:50
#define PG_CMD_DECL
Definition: initdb.c:288
struct pg_encoding enc
Definition: encode.c:562
static bool authwarning
Definition: initdb.c:187
static const char *const subdirs[]
Definition: initdb.c:202
static char * lc_messages
Definition: initdb.c:132
#define MAXPGPATH
static bool check_locale_encoding(const char *locale, int encoding)
Definition: initdb.c:2199
static const char * default_text_search_config
Definition: initdb.c:133
static char * lc_ctype
Definition: initdb.c:128
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
#define PG_CMD_OPEN
Definition: initdb.c:290
const char * tsconfname
Definition: initdb.c:670
static void setup_config(void)
Definition: initdb.c:1060
static char * lc_numeric
Definition: initdb.c:130
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
static bool found_existing_pgdata
Definition: initdb.c:164
char * ai_canonname
Definition: getaddrinfo.h:106
char * c
static char * buf
Definition: pg_test_fsync.c:68
#define symlink(oldpath, newpath)
Definition: win32_port.h:221
static void load_plpgsql(FILE *cmdfd)
Definition: initdb.c:1935
void initialize_data_directory(void)
Definition: initdb.c:2836
static int wal_segment_size_mb
Definition: initdb.c:148
#define SIGHUP
Definition: win32_port.h:153
#define is_absolute_path(filename)
Definition: port.h:86
void get_parent_directory(char *path)
Definition: path.c:854
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static void write_version_file(const char *extrapath)
Definition: initdb.c:827
unsigned int uint32
Definition: c.h:374
static void setup_description(FILE *cmdfd)
Definition: initdb.c:1647
static char * pg_data
Definition: initdb.c:124
#define DEVNULL
Definition: port.h:124
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
static char * pwfilename
Definition: initdb.c:136
static void check_ok(void)
Definition: initdb.c:2038
#define DEFAULT_MAX_WAL_SEGS
Definition: xlog_internal.h:90
static bool found_existing_xlogdir
Definition: initdb.c:166
static bool made_new_pgdata
Definition: initdb.c:163
static char * dictionary_file
Definition: initdb.c:158
#define S_ISREG(m)
Definition: win32_port.h:299
#define DATEORDER_YMD
Definition: miscadmin.h:220
static void test_config_settings(void)
Definition: initdb.c:929
#define SIG_IGN
Definition: win32_port.h:150
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
const char * select_default_timezone(const char *share_path)
void setup_bin_paths(const char *argv0)
Definition: initdb.c:2415
#define stat(a, b)
Definition: win32_port.h:255
static const char * progname
Definition: initdb.c:152
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
void create_data_directory(void)
Definition: initdb.c:2648
int pg_dir_create_mode
Definition: file_perm.c:18
#define PG_CMD_CLOSE
Definition: initdb.c:297
#define CppAsString2(x)
Definition: c.h:222
#define no_argument
Definition: getopt_long.h:24
static const char * boot_options
Definition: initdb.c:199
static char * xlog_dir
Definition: initdb.c:146
#define PG_DIR_MODE_GROUP
Definition: file_perm.h:35
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1155
static bool data_checksums
Definition: initdb.c:145
static char * info_schema_file
Definition: initdb.c:159
static size_t my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
Definition: initdb.c:2063
static void make_template0(FILE *cmdfd)
Definition: initdb.c:1954
static int locale_date_order(const char *locale)
Definition: initdb.c:2072
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define PG_IOLBF
Definition: port.h:321
#define DATEORDER_DMY
Definition: miscadmin.h:221
static char * username
Definition: initdb.c:134
static char * pretty_wal_size(int segment_count)
Definition: initdb.c:1043
#define PG_BACKEND_VERSIONSTR
Definition: port.h:112
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:452
#define DATEORDER_MDY
Definition: miscadmin.h:222
static void infile(const char *filename)
Definition: zic.c:1245
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:429
static char * encoding
Definition: initdb.c:125
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define free(a)
Definition: header.h:65
int ai_protocol
Definition: getaddrinfo.h:103
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
void setup_text_search(void)
Definition: initdb.c:2584
#define FLOAT8PASSBYVAL
Definition: c.h:503
static void setup_collation(FILE *cmdfd)
Definition: initdb.c:1668
static char * str_wal_segment_size_mb
Definition: initdb.c:147
static char ** filter_lines_with_token(char **lines, const char *token)
Definition: initdb.c:442
static bool do_sync
Definition: initdb.c:142
int ai_socktype
Definition: getaddrinfo.h:102
#define strerror
Definition: port.h:206
static void setup_schema(FILE *cmdfd)
Definition: initdb.c:1902
int main(int argc, char *argv[])
Definition: initdb.c:2948
static bool output_failed
Definition: initdb.c:169
static void setlocales(void)
Definition: initdb.c:2235
static void check_locale_name(int category, const char *locale, char **canonname)
Definition: initdb.c:2135
#define putenv(x)
Definition: win32_port.h:474
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
static char * superuser_password
Definition: initdb.c:137
const char * name
Definition: encode.c:561
static int n_buffers
Definition: initdb.c:175
static const char *const auth_methods_host[]
Definition: initdb.c:82
static char * escape_quotes(const char *src)
Definition: initdb.c:320
static const char * dynamic_shared_memory_type
Definition: initdb.c:176
static int output_errno
Definition: initdb.c:170
static char * filename
Definition: pg_dumpall.c:91
struct addrinfo * ai_next
Definition: getaddrinfo.h:107
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:434
static void writefile(char *path, char **lines)
Definition: initdb.c:516
char * optarg
Definition: getopt.c:52
static void setup_privileges(FILE *cmdfd)
Definition: initdb.c:1724
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:1992
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:31
static char bin_path[MAXPGPATH]
Definition: initdb.c:229
static void usage(const char *progname)
Definition: initdb.c:2286
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
int i
static void check_need_password(const char *authmethodlocal, const char *authmethodhost)
Definition: initdb.c:2359
static char backend_exec[MAXPGPATH]
Definition: initdb.c:230
static char * ident_file
Definition: initdb.c:156
static char * locale
Definition: initdb.c:126
static char ** readfile(const char *path)
Definition: initdb.c:469
void srandom(unsigned int seed)
Definition: srandom.c:22
char * pg_get_line(FILE *stream)
Definition: pg_get_line.c:52
static char * bki_file
Definition: initdb.c:154
static const char * authmethodhost
Definition: initdb.c:138
size_t ai_addrlen
Definition: getaddrinfo.h:104
static bool sync_only
Definition: initdb.c:143
#define mkdir(a, b)
Definition: win32_port.h:57
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:102
#define close(a)
Definition: win32.h:12
#define pg_log_warning(...)
Definition: pgfnames.c:24
int ai_flags
Definition: getaddrinfo.h:100
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
static const char *const auth_methods_local[]
Definition: initdb.c:104
static bool success
Definition: initdb.c:162
static void check_authmethod_valid(const char *authmethod, const char *const *valid_methods, const char *conntype)
Definition: initdb.c:2339
static void setup_sysviews(FILE *cmdfd)
Definition: initdb.c:1625
void get_share_path(const char *my_exec_path, char *ret_path)
Definition: path.c:704
#define snprintf
Definition: port.h:193
void setup_pgdata(void)
Definition: initdb.c:2376
#define _(x)
Definition: elog.c:88
int pg_mode_mask
Definition: file_perm.c:25
const char * langname
Definition: initdb.c:671
#define DEFAULT_MIN_WAL_SEGS
Definition: xlog_internal.h:89
static void trapsig(int signum)
Definition: initdb.c:2027
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
static char * escape_quotes_bki(const char *src)
Definition: initdb.c:342
static char * hba_file
Definition: initdb.c:155
#define DEFAULT_BACKEND_FLUSH_AFTER
#define pg_log_info(...)
Definition: logging.h:88
#define unsetenv(x)
Definition: win32_port.h:475
static void set_info_version(void)
Definition: initdb.c:1875
#define DEFAULT_PGSOCKET_DIR
static bool show_setting
Definition: initdb.c:144
static void set_input(char **dest, const char *filename)
Definition: initdb.c:781
static bool noclean
Definition: initdb.c:141
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:74
int ai_family
Definition: getaddrinfo.h:101