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