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