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