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