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