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