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