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