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