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