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