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-2016, 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 #ifdef HAVE_LOCALE_T
1612 /*
1613  * "Normalize" a locale name, stripping off encoding tags such as
1614  * ".utf8" (e.g., "en_US.utf8" -> "en_US", but "br_FR.iso885915@euro"
1615  * -> "br_FR@euro"). Return true if a new, different name was
1616  * generated.
1617  */
1618 static bool
1619 normalize_locale_name(char *new, const char *old)
1620 {
1621  char *n = new;
1622  const char *o = old;
1623  bool changed = false;
1624 
1625  while (*o)
1626  {
1627  if (*o == '.')
1628  {
1629  /* skip over encoding tag such as ".utf8" or ".UTF-8" */
1630  o++;
1631  while ((*o >= 'A' && *o <= 'Z')
1632  || (*o >= 'a' && *o <= 'z')
1633  || (*o >= '0' && *o <= '9')
1634  || (*o == '-'))
1635  o++;
1636  changed = true;
1637  }
1638  else
1639  *n++ = *o++;
1640  }
1641  *n = '\0';
1642 
1643  return changed;
1644 }
1645 #endif /* HAVE_LOCALE_T */
1646 
1647 /*
1648  * populate pg_collation
1649  */
1650 static void
1651 setup_collation(FILE *cmdfd)
1652 {
1653 #if defined(HAVE_LOCALE_T) && !defined(WIN32)
1654  int i;
1655  FILE *locale_a_handle;
1656  char localebuf[NAMEDATALEN]; /* we assume ASCII so this is fine */
1657  int count = 0;
1658 
1659  locale_a_handle = popen_check("locale -a", "r");
1660  if (!locale_a_handle)
1661  return; /* complaint already printed */
1662 
1663  PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_collation ( "
1664  " collname name, "
1665  " locale name, "
1666  " encoding int) WITHOUT OIDS;\n\n");
1667 
1668  while (fgets(localebuf, sizeof(localebuf), locale_a_handle))
1669  {
1670  size_t len;
1671  int enc;
1672  bool skip;
1673  char *quoted_locale;
1674  char alias[NAMEDATALEN];
1675 
1676  len = strlen(localebuf);
1677 
1678  if (len == 0 || localebuf[len - 1] != '\n')
1679  {
1680  if (debug)
1681  fprintf(stderr, _("%s: locale name too long, skipped: \"%s\"\n"),
1682  progname, localebuf);
1683  continue;
1684  }
1685  localebuf[len - 1] = '\0';
1686 
1687  /*
1688  * Some systems have locale names that don't consist entirely of ASCII
1689  * letters (such as "bokm&aring;l" or "fran&ccedil;ais"). This is
1690  * pretty silly, since we need the locale itself to interpret the
1691  * non-ASCII characters. We can't do much with those, so we filter
1692  * them out.
1693  */
1694  skip = false;
1695  for (i = 0; i < len; i++)
1696  {
1697  if (IS_HIGHBIT_SET(localebuf[i]))
1698  {
1699  skip = true;
1700  break;
1701  }
1702  }
1703  if (skip)
1704  {
1705  if (debug)
1706  fprintf(stderr, _("%s: locale name has non-ASCII characters, skipped: \"%s\"\n"),
1707  progname, localebuf);
1708  continue;
1709  }
1710 
1711  enc = pg_get_encoding_from_locale(localebuf, debug);
1712  if (enc < 0)
1713  {
1714  /* error message printed by pg_get_encoding_from_locale() */
1715  continue;
1716  }
1717  if (!PG_VALID_BE_ENCODING(enc))
1718  continue; /* ignore locales for client-only encodings */
1719  if (enc == PG_SQL_ASCII)
1720  continue; /* C/POSIX are already in the catalog */
1721 
1722  count++;
1723 
1724  quoted_locale = escape_quotes(localebuf);
1725 
1726  PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n\n",
1727  quoted_locale, quoted_locale, enc);
1728 
1729  /*
1730  * Generate aliases such as "en_US" in addition to "en_US.utf8" for
1731  * ease of use. Note that collation names are unique per encoding
1732  * only, so this doesn't clash with "en_US" for LATIN1, say.
1733  */
1734  if (normalize_locale_name(alias, localebuf))
1735  {
1736  char *quoted_alias = escape_quotes(alias);
1737 
1738  PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n\n",
1739  quoted_alias, quoted_locale, enc);
1740  free(quoted_alias);
1741  }
1742  free(quoted_locale);
1743  }
1744 
1745  /* Add an SQL-standard name */
1746  PG_CMD_PRINTF1("INSERT INTO tmp_pg_collation VALUES ('ucs_basic', 'C', %d);\n\n", PG_UTF8);
1747 
1748  /*
1749  * When copying collations to the final location, eliminate aliases that
1750  * conflict with an existing locale name for the same encoding. For
1751  * example, "br_FR.iso88591" is normalized to "br_FR", both for encoding
1752  * LATIN1. But the unnormalized locale "br_FR" already exists for LATIN1.
1753  * Prefer the alias that matches the OS locale name, else the first locale
1754  * name by sort order (arbitrary choice to be deterministic).
1755  *
1756  * Also, eliminate any aliases that conflict with pg_collation's
1757  * hard-wired entries for "C" etc.
1758  */
1759  PG_CMD_PUTS("INSERT INTO pg_collation (collname, collnamespace, collowner, collencoding, collcollate, collctype) "
1760  " SELECT DISTINCT ON (collname, encoding)"
1761  " collname, "
1762  " (SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog') AS collnamespace, "
1763  " (SELECT relowner FROM pg_class WHERE relname = 'pg_collation') AS collowner, "
1764  " encoding, locale, locale "
1765  " FROM tmp_pg_collation"
1766  " WHERE NOT EXISTS (SELECT 1 FROM pg_collation WHERE collname = tmp_pg_collation.collname)"
1767  " ORDER BY collname, encoding, (collname = locale) DESC, locale;\n\n");
1768 
1769  /*
1770  * Even though the table is temp, drop it explicitly so it doesn't get
1771  * copied into template0/postgres databases.
1772  */
1773  PG_CMD_PUTS("DROP TABLE tmp_pg_collation;\n\n");
1774 
1775  pclose(locale_a_handle);
1776 
1777  if (count == 0 && !debug)
1778  {
1779  printf(_("No usable system locales were found.\n"));
1780  printf(_("Use the option \"--debug\" to see details.\n"));
1781  }
1782 #endif /* not HAVE_LOCALE_T && not WIN32 */
1783 }
1784 
1785 /*
1786  * load conversion functions
1787  */
1788 static void
1789 setup_conversion(FILE *cmdfd)
1790 {
1791  char **line;
1792  char **conv_lines;
1793 
1794  conv_lines = readfile(conversion_file);
1795  for (line = conv_lines; *line != NULL; line++)
1796  {
1797  if (strstr(*line, "DROP CONVERSION") != *line)
1798  PG_CMD_PUTS(*line);
1799  free(*line);
1800  }
1801 
1802  free(conv_lines);
1803 }
1804 
1805 /*
1806  * load extra dictionaries (Snowball stemmers)
1807  */
1808 static void
1809 setup_dictionary(FILE *cmdfd)
1810 {
1811  char **line;
1812  char **conv_lines;
1813 
1814  conv_lines = readfile(dictionary_file);
1815  for (line = conv_lines; *line != NULL; line++)
1816  {
1817  PG_CMD_PUTS(*line);
1818  free(*line);
1819  }
1820 
1821  free(conv_lines);
1822 }
1823 
1824 /*
1825  * Set up privileges
1826  *
1827  * We mark most system catalogs as world-readable. We don't currently have
1828  * to touch functions, languages, or databases, because their default
1829  * permissions are OK.
1830  *
1831  * Some objects may require different permissions by default, so we
1832  * make sure we don't overwrite privilege sets that have already been
1833  * set (NOT NULL).
1834  *
1835  * Also populate pg_init_privs to save what the privileges are at init
1836  * time. This is used by pg_dump to allow users to change privileges
1837  * on catalog objects and to have those privilege changes preserved
1838  * across dump/reload and pg_upgrade.
1839  *
1840  * Note that pg_init_privs is only for per-database objects and therefore
1841  * we don't include databases or tablespaces.
1842  */
1843 static void
1844 setup_privileges(FILE *cmdfd)
1845 {
1846  char **line;
1847  char **priv_lines;
1848  static char *privileges_setup[] = {
1849  "UPDATE pg_class "
1850  " SET relacl = (SELECT array_agg(a.acl) FROM "
1851  " (SELECT E'=r/\"$POSTGRES_SUPERUSERNAME\"' as acl "
1852  " UNION SELECT unnest(pg_catalog.acldefault("
1853  " CASE WHEN relkind = 'S' THEN 's' ELSE 'r' END::\"char\",10::oid))"
1854  " ) as a) "
1855  " WHERE relkind IN ('r', 'v', 'm', 'S') AND relacl IS NULL;\n\n",
1856  "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n\n",
1857  "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n\n",
1858  "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n",
1859  "INSERT INTO pg_init_privs "
1860  " (objoid, classoid, objsubid, initprivs, privtype)"
1861  " SELECT"
1862  " oid,"
1863  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1864  " 0,"
1865  " relacl,"
1866  " 'i'"
1867  " FROM"
1868  " pg_class"
1869  " WHERE"
1870  " relacl IS NOT NULL"
1871  " AND relkind IN ('r', 'v', 'm', 'S');",
1872  "INSERT INTO pg_init_privs "
1873  " (objoid, classoid, objsubid, initprivs, privtype)"
1874  " SELECT"
1875  " pg_class.oid,"
1876  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1877  " pg_attribute.attnum,"
1878  " pg_attribute.attacl,"
1879  " 'i'"
1880  " FROM"
1881  " pg_class"
1882  " JOIN pg_attribute ON (pg_class.oid = pg_attribute.attrelid)"
1883  " WHERE"
1884  " pg_attribute.attacl IS NOT NULL"
1885  " AND pg_class.relkind IN ('r', 'v', 'm', 'S');",
1886  "INSERT INTO pg_init_privs "
1887  " (objoid, classoid, objsubid, initprivs, privtype)"
1888  " SELECT"
1889  " oid,"
1890  " (SELECT oid FROM pg_class WHERE relname = 'pg_proc'),"
1891  " 0,"
1892  " proacl,"
1893  " 'i'"
1894  " FROM"
1895  " pg_proc"
1896  " WHERE"
1897  " proacl IS NOT NULL;",
1898  "INSERT INTO pg_init_privs "
1899  " (objoid, classoid, objsubid, initprivs, privtype)"
1900  " SELECT"
1901  " oid,"
1902  " (SELECT oid FROM pg_class WHERE relname = 'pg_type'),"
1903  " 0,"
1904  " typacl,"
1905  " 'i'"
1906  " FROM"
1907  " pg_type"
1908  " WHERE"
1909  " typacl IS NOT NULL;",
1910  "INSERT INTO pg_init_privs "
1911  " (objoid, classoid, objsubid, initprivs, privtype)"
1912  " SELECT"
1913  " oid,"
1914  " (SELECT oid FROM pg_class WHERE relname = 'pg_language'),"
1915  " 0,"
1916  " lanacl,"
1917  " 'i'"
1918  " FROM"
1919  " pg_language"
1920  " WHERE"
1921  " lanacl IS NOT NULL;",
1922  "INSERT INTO pg_init_privs "
1923  " (objoid, classoid, objsubid, initprivs, privtype)"
1924  " SELECT"
1925  " oid,"
1926  " (SELECT oid FROM pg_class WHERE "
1927  " relname = 'pg_largeobject_metadata'),"
1928  " 0,"
1929  " lomacl,"
1930  " 'i'"
1931  " FROM"
1932  " pg_largeobject_metadata"
1933  " WHERE"
1934  " lomacl IS NOT NULL;",
1935  "INSERT INTO pg_init_privs "
1936  " (objoid, classoid, objsubid, initprivs, privtype)"
1937  " SELECT"
1938  " oid,"
1939  " (SELECT oid FROM pg_class WHERE relname = 'pg_namespace'),"
1940  " 0,"
1941  " nspacl,"
1942  " 'i'"
1943  " FROM"
1944  " pg_namespace"
1945  " WHERE"
1946  " nspacl IS NOT NULL;",
1947  "INSERT INTO pg_init_privs "
1948  " (objoid, classoid, objsubid, initprivs, privtype)"
1949  " SELECT"
1950  " oid,"
1951  " (SELECT oid FROM pg_class WHERE "
1952  " relname = 'pg_foreign_data_wrapper'),"
1953  " 0,"
1954  " fdwacl,"
1955  " 'i'"
1956  " FROM"
1957  " pg_foreign_data_wrapper"
1958  " WHERE"
1959  " fdwacl IS NOT NULL;",
1960  "INSERT INTO pg_init_privs "
1961  " (objoid, classoid, objsubid, initprivs, privtype)"
1962  " SELECT"
1963  " oid,"
1964  " (SELECT oid FROM pg_class "
1965  " WHERE relname = 'pg_foreign_server'),"
1966  " 0,"
1967  " srvacl,"
1968  " 'i'"
1969  " FROM"
1970  " pg_foreign_server"
1971  " WHERE"
1972  " srvacl IS NOT NULL;",
1973  NULL
1974  };
1975 
1976  priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
1978  for (line = priv_lines; *line != NULL; line++)
1979  PG_CMD_PUTS(*line);
1980 }
1981 
1982 /*
1983  * extract the strange version of version required for information schema
1984  * (09.08.0007abc)
1985  */
1986 static void
1988 {
1989  char *letterversion;
1990  long major = 0,
1991  minor = 0,
1992  micro = 0;
1993  char *endptr;
1994  char *vstr = pg_strdup(PG_VERSION);
1995  char *ptr;
1996 
1997  ptr = vstr + (strlen(vstr) - 1);
1998  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1999  ptr--;
2000  letterversion = ptr + 1;
2001  major = strtol(vstr, &endptr, 10);
2002  if (*endptr)
2003  minor = strtol(endptr + 1, &endptr, 10);
2004  if (*endptr)
2005  micro = strtol(endptr + 1, &endptr, 10);
2006  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
2007  major, minor, micro, letterversion);
2008 }
2009 
2010 /*
2011  * load info schema and populate from features file
2012  */
2013 static void
2014 setup_schema(FILE *cmdfd)
2015 {
2016  char **line;
2017  char **lines;
2018 
2019  lines = readfile(info_schema_file);
2020 
2021  for (line = lines; *line != NULL; line++)
2022  {
2023  PG_CMD_PUTS(*line);
2024  free(*line);
2025  }
2026 
2027  free(lines);
2028 
2029  PG_CMD_PRINTF1("UPDATE information_schema.sql_implementation_info "
2030  " SET character_value = '%s' "
2031  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
2032  infoversion);
2033 
2034  PG_CMD_PRINTF1("COPY information_schema.sql_features "
2035  " (feature_id, feature_name, sub_feature_id, "
2036  " sub_feature_name, is_supported, comments) "
2037  " FROM E'%s';\n\n",
2039 }
2040 
2041 /*
2042  * load PL/pgsql server-side language
2043  */
2044 static void
2045 load_plpgsql(FILE *cmdfd)
2046 {
2047  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
2048 }
2049 
2050 /*
2051  * clean everything up in template1
2052  */
2053 static void
2054 vacuum_db(FILE *cmdfd)
2055 {
2056  /* Run analyze before VACUUM so the statistics are frozen. */
2057  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
2058 }
2059 
2060 /*
2061  * copy template1 to template0
2062  */
2063 static void
2064 make_template0(FILE *cmdfd)
2065 {
2066  const char *const * line;
2067  static const char *const template0_setup[] = {
2068  "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false;\n\n",
2069 
2070  /*
2071  * We use the OID of template0 to determine lastsysoid
2072  */
2073  "UPDATE pg_database SET datlastsysoid = "
2074  " (SELECT oid FROM pg_database "
2075  " WHERE datname = 'template0');\n\n",
2076 
2077  /*
2078  * Explicitly revoke public create-schema and create-temp-table
2079  * privileges in template1 and template0; else the latter would be on
2080  * by default
2081  */
2082  "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n",
2083  "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n",
2084 
2085  "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n",
2086 
2087  /*
2088  * Finally vacuum to clean up dead rows in pg_database
2089  */
2090  "VACUUM pg_database;\n\n",
2091  NULL
2092  };
2093 
2094  for (line = template0_setup; *line; line++)
2095  PG_CMD_PUTS(*line);
2096 }
2097 
2098 /*
2099  * copy template1 to postgres
2100  */
2101 static void
2102 make_postgres(FILE *cmdfd)
2103 {
2104  const char *const * line;
2105  static const char *const postgres_setup[] = {
2106  "CREATE DATABASE postgres;\n\n",
2107  "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",
2108  NULL
2109  };
2110 
2111  for (line = postgres_setup; *line; line++)
2112  PG_CMD_PUTS(*line);
2113 }
2114 
2115 /*
2116  * signal handler in case we are interrupted.
2117  *
2118  * The Windows runtime docs at
2119  * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
2120  * specifically forbid a number of things being done from a signal handler,
2121  * including IO, memory allocation and system calls, and only allow jmpbuf
2122  * if you are handling SIGFPE.
2123  *
2124  * I avoided doing the forbidden things by setting a flag instead of calling
2125  * exit_nicely() directly.
2126  *
2127  * Also note the behaviour of Windows with SIGINT, which says this:
2128  * Note SIGINT is not supported for any Win32 application, including
2129  * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
2130  * Win32 operating systems generate a new thread to specifically handle
2131  * that interrupt. This can cause a single-thread application such as UNIX,
2132  * to become multithreaded, resulting in unexpected behavior.
2133  *
2134  * I have no idea how to handle this. (Strange they call UNIX an application!)
2135  * So this will need some testing on Windows.
2136  */
2137 static void
2138 trapsig(int signum)
2139 {
2140  /* handle systems that reset the handler, like Windows (grr) */
2141  pqsignal(signum, trapsig);
2142  caught_signal = true;
2143 }
2144 
2145 /*
2146  * call exit_nicely() if we got a signal, or else output "ok".
2147  */
2148 static void
2150 {
2151  if (caught_signal)
2152  {
2153  printf(_("caught signal\n"));
2154  fflush(stdout);
2155  exit_nicely();
2156  }
2157  else if (output_failed)
2158  {
2159  printf(_("could not write to child process: %s\n"),
2161  fflush(stdout);
2162  exit_nicely();
2163  }
2164  else
2165  {
2166  /* all seems well */
2167  printf(_("ok\n"));
2168  fflush(stdout);
2169  }
2170 }
2171 
2172 /* Hack to suppress a warning about %x from some versions of gcc */
2173 static inline size_t
2174 my_strftime(char *s, size_t max, const char *fmt, const struct tm * tm)
2175 {
2176  return strftime(s, max, fmt, tm);
2177 }
2178 
2179 /*
2180  * Determine likely date order from locale
2181  */
2182 static int
2184 {
2185  struct tm testtime;
2186  char buf[128];
2187  char *posD;
2188  char *posM;
2189  char *posY;
2190  char *save;
2191  size_t res;
2192  int result;
2193 
2194  result = DATEORDER_MDY; /* default */
2195 
2196  save = setlocale(LC_TIME, NULL);
2197  if (!save)
2198  return result;
2199  save = pg_strdup(save);
2200 
2201  setlocale(LC_TIME, locale);
2202 
2203  memset(&testtime, 0, sizeof(testtime));
2204  testtime.tm_mday = 22;
2205  testtime.tm_mon = 10; /* November, should come out as "11" */
2206  testtime.tm_year = 133; /* 2033 */
2207 
2208  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
2209 
2210  setlocale(LC_TIME, save);
2211  free(save);
2212 
2213  if (res == 0)
2214  return result;
2215 
2216  posM = strstr(buf, "11");
2217  posD = strstr(buf, "22");
2218  posY = strstr(buf, "33");
2219 
2220  if (!posM || !posD || !posY)
2221  return result;
2222 
2223  if (posY < posM && posM < posD)
2224  result = DATEORDER_YMD;
2225  else if (posD < posM)
2226  result = DATEORDER_DMY;
2227  else
2228  result = DATEORDER_MDY;
2229 
2230  return result;
2231 }
2232 
2233 /*
2234  * Verify that locale name is valid for the locale category.
2235  *
2236  * If successful, and canonname isn't NULL, a malloc'd copy of the locale's
2237  * canonical name is stored there. This is especially useful for figuring out
2238  * what locale name "" means (ie, the environment value). (Actually,
2239  * it seems that on most implementations that's the only thing it's good for;
2240  * we could wish that setlocale gave back a canonically spelled version of
2241  * the locale name, but typically it doesn't.)
2242  *
2243  * this should match the backend's check_locale() function
2244  */
2245 static void
2246 check_locale_name(int category, const char *locale, char **canonname)
2247 {
2248  char *save;
2249  char *res;
2250 
2251  if (canonname)
2252  *canonname = NULL; /* in case of failure */
2253 
2254  save = setlocale(category, NULL);
2255  if (!save)
2256  {
2257  fprintf(stderr, _("%s: setlocale() failed\n"),
2258  progname);
2259  exit(1);
2260  }
2261 
2262  /* save may be pointing at a modifiable scratch variable, so copy it. */
2263  save = pg_strdup(save);
2264 
2265  /* set the locale with setlocale, to see if it accepts it. */
2266  res = setlocale(category, locale);
2267 
2268  /* save canonical name if requested. */
2269  if (res && canonname)
2270  *canonname = pg_strdup(res);
2271 
2272  /* restore old value. */
2273  if (!setlocale(category, save))
2274  {
2275  fprintf(stderr, _("%s: failed to restore old locale \"%s\"\n"),
2276  progname, save);
2277  exit(1);
2278  }
2279  free(save);
2280 
2281  /* complain if locale wasn't valid */
2282  if (res == NULL)
2283  {
2284  if (*locale)
2285  fprintf(stderr, _("%s: invalid locale name \"%s\"\n"),
2286  progname, locale);
2287  else
2288  {
2289  /*
2290  * If no relevant switch was given on command line, locale is an
2291  * empty string, which is not too helpful to report. Presumably
2292  * setlocale() found something it did not like in the environment.
2293  * Ideally we'd report the bad environment variable, but since
2294  * setlocale's behavior is implementation-specific, it's hard to
2295  * be sure what it didn't like. Print a safe generic message.
2296  */
2297  fprintf(stderr, _("%s: invalid locale settings; check LANG and LC_* environment variables\n"),
2298  progname);
2299  }
2300  exit(1);
2301  }
2302 }
2303 
2304 /*
2305  * check if the chosen encoding matches the encoding required by the locale
2306  *
2307  * this should match the similar check in the backend createdb() function
2308  */
2309 static bool
2310 check_locale_encoding(const char *locale, int user_enc)
2311 {
2312  int locale_enc;
2313 
2314  locale_enc = pg_get_encoding_from_locale(locale, true);
2315 
2316  /* See notes in createdb() to understand these tests */
2317  if (!(locale_enc == user_enc ||
2318  locale_enc == PG_SQL_ASCII ||
2319  locale_enc == -1 ||
2320 #ifdef WIN32
2321  user_enc == PG_UTF8 ||
2322 #endif
2323  user_enc == PG_SQL_ASCII))
2324  {
2325  fprintf(stderr, _("%s: encoding mismatch\n"), progname);
2326  fprintf(stderr,
2327  _("The encoding you selected (%s) and the encoding that the\n"
2328  "selected locale uses (%s) do not match. This would lead to\n"
2329  "misbehavior in various character string processing functions.\n"
2330  "Rerun %s and either do not specify an encoding explicitly,\n"
2331  "or choose a matching combination.\n"),
2332  pg_encoding_to_char(user_enc),
2333  pg_encoding_to_char(locale_enc),
2334  progname);
2335  return false;
2336  }
2337  return true;
2338 }
2339 
2340 /*
2341  * set up the locale variables
2342  *
2343  * assumes we have called setlocale(LC_ALL, "") -- see set_pglocale_pgservice
2344  */
2345 static void
2347 {
2348  char *canonname;
2349 
2350  /* set empty lc_* values to locale config if set */
2351 
2352  if (strlen(locale) > 0)
2353  {
2354  if (strlen(lc_ctype) == 0)
2355  lc_ctype = locale;
2356  if (strlen(lc_collate) == 0)
2357  lc_collate = locale;
2358  if (strlen(lc_numeric) == 0)
2359  lc_numeric = locale;
2360  if (strlen(lc_time) == 0)
2361  lc_time = locale;
2362  if (strlen(lc_monetary) == 0)
2363  lc_monetary = locale;
2364  if (strlen(lc_messages) == 0)
2365  lc_messages = locale;
2366  }
2367 
2368  /*
2369  * canonicalize locale names, and obtain any missing values from our
2370  * current environment
2371  */
2372 
2373  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2374  lc_ctype = canonname;
2375  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2376  lc_collate = canonname;
2377  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2378  lc_numeric = canonname;
2379  check_locale_name(LC_TIME, lc_time, &canonname);
2380  lc_time = canonname;
2381  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2382  lc_monetary = canonname;
2383 #if defined(LC_MESSAGES) && !defined(WIN32)
2384  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2385  lc_messages = canonname;
2386 #else
2387  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2388  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2389  lc_messages = canonname;
2390 #endif
2391 }
2392 
2393 /*
2394  * print help text
2395  */
2396 static void
2397 usage(const char *progname)
2398 {
2399  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2400  printf(_("Usage:\n"));
2401  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2402  printf(_("\nOptions:\n"));
2403  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2404  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2405  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2406  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2407  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2408  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2409  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2410  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2411  " set default locale in the respective category for\n"
2412  " new databases (default taken from environment)\n"));
2413  printf(_(" --no-locale equivalent to --locale=C\n"));
2414  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2415  printf(_(" -T, --text-search-config=CFG\n"
2416  " default text search configuration\n"));
2417  printf(_(" -U, --username=NAME database superuser name\n"));
2418  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2419  printf(_(" -X, --xlogdir=XLOGDIR location for the transaction log directory\n"));
2420  printf(_("\nLess commonly used options:\n"));
2421  printf(_(" -d, --debug generate lots of debugging output\n"));
2422  printf(_(" -k, --data-checksums use data page checksums\n"));
2423  printf(_(" -L DIRECTORY where to find the input files\n"));
2424  printf(_(" -n, --no-clean do not clean up after errors\n"));
2425  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
2426  printf(_(" -s, --show show internal settings\n"));
2427  printf(_(" -S, --sync-only only sync data directory\n"));
2428  printf(_("\nOther options:\n"));
2429  printf(_(" -V, --version output version information, then exit\n"));
2430  printf(_(" -?, --help show this help, then exit\n"));
2431  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2432  "is used.\n"));
2433  printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2434 }
2435 
2436 static void
2437 check_authmethod_unspecified(const char **authmethod)
2438 {
2439  if (*authmethod == NULL || strlen(*authmethod) == 0)
2440  {
2441  authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
2442  "You can change this by editing pg_hba.conf or using the option -A, or\n"
2443  "--auth-local and --auth-host, the next time you run initdb.\n");
2444  *authmethod = "trust";
2445  }
2446 }
2447 
2448 static void
2449 check_authmethod_valid(const char *authmethod, const char *const * valid_methods, const char *conntype)
2450 {
2451  const char *const * p;
2452 
2453  for (p = valid_methods; *p; p++)
2454  {
2455  if (strcmp(authmethod, *p) == 0)
2456  return;
2457  /* with space = param */
2458  if (strchr(authmethod, ' '))
2459  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2460  return;
2461  }
2462 
2463  fprintf(stderr, _("%s: invalid authentication method \"%s\" for \"%s\" connections\n"),
2464  progname, authmethod, conntype);
2465  exit(1);
2466 }
2467 
2468 static void
2470 {
2471  if ((strcmp(authmethodlocal, "md5") == 0 ||
2472  strcmp(authmethodlocal, "password") == 0) &&
2473  (strcmp(authmethodhost, "md5") == 0 ||
2474  strcmp(authmethodhost, "password") == 0) &&
2475  !(pwprompt || pwfilename))
2476  {
2477  fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname,
2478  (strcmp(authmethodlocal, "md5") == 0 ||
2479  strcmp(authmethodlocal, "password") == 0)
2480  ? authmethodlocal
2481  : authmethodhost);
2482  exit(1);
2483  }
2484 }
2485 
2486 
2487 void
2489 {
2490  char *pgdata_get_env,
2491  *pgdata_set_env;
2492 
2493  if (strlen(pg_data) == 0)
2494  {
2495  pgdata_get_env = getenv("PGDATA");
2496  if (pgdata_get_env && strlen(pgdata_get_env))
2497  {
2498  /* PGDATA found */
2499  pg_data = pg_strdup(pgdata_get_env);
2500  }
2501  else
2502  {
2503  fprintf(stderr,
2504  _("%s: no data directory specified\n"
2505  "You must identify the directory where the data for this database system\n"
2506  "will reside. Do this with either the invocation option -D or the\n"
2507  "environment variable PGDATA.\n"),
2508  progname);
2509  exit(1);
2510  }
2511  }
2512 
2515 
2516  /*
2517  * we have to set PGDATA for postgres rather than pass it on the command
2518  * line to avoid dumb quoting problems on Windows, and we would especially
2519  * need quotes otherwise on Windows because paths there are most likely to
2520  * have embedded spaces.
2521  */
2522  pgdata_set_env = psprintf("PGDATA=%s", pg_data);
2523  putenv(pgdata_set_env);
2524 }
2525 
2526 
2527 void
2529 {
2530  int ret;
2531 
2532  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2533  backend_exec)) < 0)
2534  {
2535  char full_path[MAXPGPATH];
2536 
2537  if (find_my_exec(argv0, full_path) < 0)
2538  strlcpy(full_path, progname, sizeof(full_path));
2539 
2540  if (ret == -1)
2541  fprintf(stderr,
2542  _("The program \"postgres\" is needed by %s "
2543  "but was not found in the\n"
2544  "same directory as \"%s\".\n"
2545  "Check your installation.\n"),
2546  progname, full_path);
2547  else
2548  fprintf(stderr,
2549  _("The program \"postgres\" was found by \"%s\"\n"
2550  "but was not the same version as %s.\n"
2551  "Check your installation.\n"),
2552  full_path, progname);
2553  exit(1);
2554  }
2555 
2556  /* store binary directory */
2557  strcpy(bin_path, backend_exec);
2558  *last_dir_separator(bin_path) = '\0';
2560 
2561  if (!share_path)
2562  {
2565  }
2566  else if (!is_absolute_path(share_path))
2567  {
2568  fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
2569  exit(1);
2570  }
2571 
2573 }
2574 
2575 void
2577 {
2578  int user_enc;
2579 
2580  setlocales();
2581 
2582  if (strcmp(lc_ctype, lc_collate) == 0 &&
2583  strcmp(lc_ctype, lc_time) == 0 &&
2584  strcmp(lc_ctype, lc_numeric) == 0 &&
2585  strcmp(lc_ctype, lc_monetary) == 0 &&
2586  strcmp(lc_ctype, lc_messages) == 0)
2587  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2588  else
2589  {
2590  printf(_("The database cluster will be initialized with locales\n"
2591  " COLLATE: %s\n"
2592  " CTYPE: %s\n"
2593  " MESSAGES: %s\n"
2594  " MONETARY: %s\n"
2595  " NUMERIC: %s\n"
2596  " TIME: %s\n"),
2597  lc_collate,
2598  lc_ctype,
2599  lc_messages,
2600  lc_monetary,
2601  lc_numeric,
2602  lc_time);
2603  }
2604 
2605  if (strlen(encoding) == 0)
2606  {
2607  int ctype_enc;
2608 
2609  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2610 
2611  if (ctype_enc == -1)
2612  {
2613  /* Couldn't recognize the locale's codeset */
2614  fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"),
2615  progname, lc_ctype);
2616  fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2617  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2618  progname);
2619  exit(1);
2620  }
2621  else if (!pg_valid_server_encoding_id(ctype_enc))
2622  {
2623  /*
2624  * We recognized it, but it's not a legal server encoding. On
2625  * Windows, UTF-8 works with any locale, so we can fall back to
2626  * UTF-8.
2627  */
2628 #ifdef WIN32
2629  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2630  "The default database encoding will be set to \"%s\" instead.\n"),
2631  pg_encoding_to_char(ctype_enc),
2633  ctype_enc = PG_UTF8;
2634  encodingid = encodingid_to_string(ctype_enc);
2635 #else
2636  fprintf(stderr,
2637  _("%s: locale \"%s\" requires unsupported encoding \"%s\"\n"),
2638  progname, lc_ctype, pg_encoding_to_char(ctype_enc));
2639  fprintf(stderr,
2640  _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
2641  "Rerun %s with a different locale selection.\n"),
2642  pg_encoding_to_char(ctype_enc), progname);
2643  exit(1);
2644 #endif
2645  }
2646  else
2647  {
2648  encodingid = encodingid_to_string(ctype_enc);
2649  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2650  pg_encoding_to_char(ctype_enc));
2651  }
2652  }
2653  else
2655 
2656  user_enc = atoi(encodingid);
2657  if (!check_locale_encoding(lc_ctype, user_enc) ||
2658  !check_locale_encoding(lc_collate, user_enc))
2659  exit(1); /* check_locale_encoding printed the error */
2660 
2661 }
2662 
2663 
2664 void
2666 {
2667  set_input(&bki_file, "postgres.bki");
2668  set_input(&desc_file, "postgres.description");
2669  set_input(&shdesc_file, "postgres.shdescription");
2670  set_input(&hba_file, "pg_hba.conf.sample");
2671  set_input(&ident_file, "pg_ident.conf.sample");
2672  set_input(&conf_file, "postgresql.conf.sample");
2673  set_input(&conversion_file, "conversion_create.sql");
2674  set_input(&dictionary_file, "snowball_create.sql");
2675  set_input(&info_schema_file, "information_schema.sql");
2676  set_input(&features_file, "sql_features.txt");
2677  set_input(&system_views_file, "system_views.sql");
2678 
2679  if (show_setting || debug)
2680  {
2681  fprintf(stderr,
2682  "VERSION=%s\n"
2683  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2684  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2685  "POSTGRES_DESCR=%s\nPOSTGRES_SHDESCR=%s\n"
2686  "POSTGRESQL_CONF_SAMPLE=%s\n"
2687  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2688  PG_VERSION,
2690  username, bki_file,
2692  conf_file,
2693  hba_file, ident_file);
2694  if (show_setting)
2695  exit(0);
2696  }
2697 
2709 }
2710 
2711 
2712 void
2714 {
2715  if (strlen(default_text_search_config) == 0)
2716  {
2719  {
2720  printf(_("%s: could not find suitable text search configuration for locale \"%s\"\n"),
2721  progname, lc_ctype);
2722  default_text_search_config = "simple";
2723  }
2724  }
2725  else
2726  {
2727  const char *checkmatch = find_matching_ts_config(lc_ctype);
2728 
2729  if (checkmatch == NULL)
2730  {
2731  printf(_("%s: warning: suitable text search configuration for locale \"%s\" is unknown\n"),
2732  progname, lc_ctype);
2733  }
2734  else if (strcmp(checkmatch, default_text_search_config) != 0)
2735  {
2736  printf(_("%s: warning: specified text search configuration \"%s\" might not match locale \"%s\"\n"),
2738  }
2739  }
2740 
2741  printf(_("The default text search configuration will be set to \"%s\".\n"),
2743 
2744 }
2745 
2746 
2747 void
2749 {
2750  /* some of these are not valid on Windows */
2751 #ifdef SIGHUP
2753 #endif
2754 #ifdef SIGINT
2755  pqsignal(SIGINT, trapsig);
2756 #endif
2757 #ifdef SIGQUIT
2759 #endif
2760 #ifdef SIGTERM
2761  pqsignal(SIGTERM, trapsig);
2762 #endif
2763 
2764  /* Ignore SIGPIPE when writing to backend, so we can clean up */
2765 #ifdef SIGPIPE
2767 #endif
2768 
2769  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
2770 #ifdef SIGSYS
2771  pqsignal(SIGSYS, SIG_IGN);
2772 #endif
2773 }
2774 
2775 
2776 void
2778 {
2779  int ret;
2780 
2781  switch ((ret = pg_check_dir(pg_data)))
2782  {
2783  case 0:
2784  /* PGDATA not there, must create it */
2785  printf(_("creating directory %s ... "),
2786  pg_data);
2787  fflush(stdout);
2788 
2789  if (pg_mkdir_p(pg_data, S_IRWXU) != 0)
2790  {
2791  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
2792  progname, pg_data, strerror(errno));
2793  exit_nicely();
2794  }
2795  else
2796  check_ok();
2797 
2798  made_new_pgdata = true;
2799  break;
2800 
2801  case 1:
2802  /* Present but empty, fix permissions and use it */
2803  printf(_("fixing permissions on existing directory %s ... "),
2804  pg_data);
2805  fflush(stdout);
2806 
2807  if (chmod(pg_data, S_IRWXU) != 0)
2808  {
2809  fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
2810  progname, pg_data, strerror(errno));
2811  exit_nicely();
2812  }
2813  else
2814  check_ok();
2815 
2816  found_existing_pgdata = true;
2817  break;
2818 
2819  case 2:
2820  case 3:
2821  case 4:
2822  /* Present and not empty */
2823  fprintf(stderr,
2824  _("%s: directory \"%s\" exists but is not empty\n"),
2825  progname, pg_data);
2826  if (ret != 4)
2827  warn_on_mount_point(ret);
2828  else
2829  fprintf(stderr,
2830  _("If you want to create a new database system, either remove or empty\n"
2831  "the directory \"%s\" or run %s\n"
2832  "with an argument other than \"%s\".\n"),
2834  exit(1); /* no further message needed */
2835 
2836  default:
2837  /* Trouble accessing directory */
2838  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
2839  progname, pg_data, strerror(errno));
2840  exit_nicely();
2841  }
2842 }
2843 
2844 
2845 /* Create transaction log directory, and symlink if required */
2846 void
2848 {
2849  char *subdirloc;
2850 
2851  /* form name of the place for the subdirectory or symlink */
2852  subdirloc = psprintf("%s/pg_wal", pg_data);
2853 
2854  if (strcmp(xlog_dir, "") != 0)
2855  {
2856  int ret;
2857 
2858  /* clean up xlog directory name, check it's absolute */
2860  if (!is_absolute_path(xlog_dir))
2861  {
2862  fprintf(stderr, _("%s: transaction log directory location must be an absolute path\n"), progname);
2863  exit_nicely();
2864  }
2865 
2866  /* check if the specified xlog directory exists/is empty */
2867  switch ((ret = pg_check_dir(xlog_dir)))
2868  {
2869  case 0:
2870  /* xlog directory not there, must create it */
2871  printf(_("creating directory %s ... "),
2872  xlog_dir);
2873  fflush(stdout);
2874 
2875  if (pg_mkdir_p(xlog_dir, S_IRWXU) != 0)
2876  {
2877  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
2878  progname, xlog_dir, strerror(errno));
2879  exit_nicely();
2880  }
2881  else
2882  check_ok();
2883 
2884  made_new_xlogdir = true;
2885  break;
2886 
2887  case 1:
2888  /* Present but empty, fix permissions and use it */
2889  printf(_("fixing permissions on existing directory %s ... "),
2890  xlog_dir);
2891  fflush(stdout);
2892 
2893  if (chmod(xlog_dir, S_IRWXU) != 0)
2894  {
2895  fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
2896  progname, xlog_dir, strerror(errno));
2897  exit_nicely();
2898  }
2899  else
2900  check_ok();
2901 
2902  found_existing_xlogdir = true;
2903  break;
2904 
2905  case 2:
2906  case 3:
2907  case 4:
2908  /* Present and not empty */
2909  fprintf(stderr,
2910  _("%s: directory \"%s\" exists but is not empty\n"),
2911  progname, xlog_dir);
2912  if (ret != 4)
2913  warn_on_mount_point(ret);
2914  else
2915  fprintf(stderr,
2916  _("If you want to store the transaction log there, either\n"
2917  "remove or empty the directory \"%s\".\n"),
2918  xlog_dir);
2919  exit_nicely();
2920 
2921  default:
2922  /* Trouble accessing directory */
2923  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
2924  progname, xlog_dir, strerror(errno));
2925  exit_nicely();
2926  }
2927 
2928 #ifdef HAVE_SYMLINK
2929  if (symlink(xlog_dir, subdirloc) != 0)
2930  {
2931  fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
2932  progname, subdirloc, strerror(errno));
2933  exit_nicely();
2934  }
2935 #else
2936  fprintf(stderr, _("%s: symlinks are not supported on this platform"));
2937  exit_nicely();
2938 #endif
2939  }
2940  else
2941  {
2942  /* Without -X option, just make the subdirectory normally */
2943  if (mkdir(subdirloc, S_IRWXU) < 0)
2944  {
2945  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
2946  progname, subdirloc, strerror(errno));
2947  exit_nicely();
2948  }
2949  }
2950 
2951  free(subdirloc);
2952 }
2953 
2954 
2955 void
2957 {
2958  if (error == 2)
2959  fprintf(stderr,
2960  _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
2961  else if (error == 3)
2962  fprintf(stderr,
2963  _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
2964 
2965  fprintf(stderr,
2966  _("Using a mount point directly as the data directory is not recommended.\n"
2967  "Create a subdirectory under the mount point.\n"));
2968 }
2969 
2970 
2971 void
2973 {
2974  PG_CMD_DECL;
2975  int i;
2976 
2977  setup_signals();
2978 
2979  umask(S_IRWXG | S_IRWXO);
2980 
2982 
2984 
2985  /* Create required subdirectories (other than pg_wal) */
2986  printf(_("creating subdirectories ... "));
2987  fflush(stdout);
2988 
2989  for (i = 0; i < lengthof(subdirs); i++)
2990  {
2991  char *path;
2992 
2993  path = psprintf("%s/%s", pg_data, subdirs[i]);
2994 
2995  /*
2996  * The parent directory already exists, so we only need mkdir() not
2997  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
2998  */
2999  if (mkdir(path, S_IRWXU) < 0)
3000  {
3001  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3002  progname, path, strerror(errno));
3003  exit_nicely();
3004  }
3005 
3006  free(path);
3007  }
3008 
3009  check_ok();
3010 
3011  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
3013 
3014  /* Select suitable configuration settings */
3015  set_null_conf();
3017 
3018  /* Now create all the text config files */
3019  setup_config();
3020 
3021  /* Bootstrap template1 */
3023 
3024  /*
3025  * Make the per-database PG_VERSION for template1 only after init'ing it
3026  */
3027  write_version_file("base/1");
3028 
3029  /*
3030  * Create the stuff we don't need to use bootstrap mode for, using a
3031  * backend running in simple standalone mode.
3032  */
3033  fputs(_("performing post-bootstrap initialization ... "), stdout);
3034  fflush(stdout);
3035 
3036  snprintf(cmd, sizeof(cmd),
3037  "\"%s\" %s template1 >%s",
3039  DEVNULL);
3040 
3041  PG_CMD_OPEN;
3042 
3043  setup_auth(cmdfd);
3044 
3045  setup_depend(cmdfd);
3046 
3047  setup_sysviews(cmdfd);
3048 
3049  setup_description(cmdfd);
3050 
3051  setup_collation(cmdfd);
3052 
3053  setup_conversion(cmdfd);
3054 
3055  setup_dictionary(cmdfd);
3056 
3057  setup_privileges(cmdfd);
3058 
3059  setup_schema(cmdfd);
3060 
3061  load_plpgsql(cmdfd);
3062 
3063  vacuum_db(cmdfd);
3064 
3065  make_template0(cmdfd);
3066 
3067  make_postgres(cmdfd);
3068 
3069  PG_CMD_CLOSE;
3070 
3071  check_ok();
3072 }
3073 
3074 
3075 int
3076 main(int argc, char *argv[])
3077 {
3078  static struct option long_options[] = {
3079  {"pgdata", required_argument, NULL, 'D'},
3080  {"encoding", required_argument, NULL, 'E'},
3081  {"locale", required_argument, NULL, 1},
3082  {"lc-collate", required_argument, NULL, 2},
3083  {"lc-ctype", required_argument, NULL, 3},
3084  {"lc-monetary", required_argument, NULL, 4},
3085  {"lc-numeric", required_argument, NULL, 5},
3086  {"lc-time", required_argument, NULL, 6},
3087  {"lc-messages", required_argument, NULL, 7},
3088  {"no-locale", no_argument, NULL, 8},
3089  {"text-search-config", required_argument, NULL, 'T'},
3090  {"auth", required_argument, NULL, 'A'},
3091  {"auth-local", required_argument, NULL, 10},
3092  {"auth-host", required_argument, NULL, 11},
3093  {"pwprompt", no_argument, NULL, 'W'},
3094  {"pwfile", required_argument, NULL, 9},
3095  {"username", required_argument, NULL, 'U'},
3096  {"help", no_argument, NULL, '?'},
3097  {"version", no_argument, NULL, 'V'},
3098  {"debug", no_argument, NULL, 'd'},
3099  {"show", no_argument, NULL, 's'},
3100  {"noclean", no_argument, NULL, 'n'}, /* for backwards compatibility */
3101  {"no-clean", no_argument, NULL, 'n'},
3102  {"nosync", no_argument, NULL, 'N'}, /* for backwards compatibility */
3103  {"no-sync", no_argument, NULL, 'N'},
3104  {"sync-only", no_argument, NULL, 'S'},
3105  {"xlogdir", required_argument, NULL, 'X'},
3106  {"data-checksums", no_argument, NULL, 'k'},
3107  {NULL, 0, NULL, 0}
3108  };
3109 
3110  /*
3111  * options with no short version return a low integer, the rest return
3112  * their short version value
3113  */
3114  int c;
3115  int option_index;
3116  char *effective_user;
3117  PQExpBuffer start_db_cmd;
3118  char pg_ctl_path[MAXPGPATH];
3119 
3120  /*
3121  * Ensure that buffering behavior of stdout and stderr matches what it is
3122  * in interactive usage (at least on most platforms). This prevents
3123  * unexpected output ordering when, eg, output is redirected to a file.
3124  * POSIX says we must do this before any other usage of these files.
3125  */
3126  setvbuf(stdout, NULL, PG_IOLBF, 0);
3127  setvbuf(stderr, NULL, _IONBF, 0);
3128 
3129  progname = get_progname(argv[0]);
3130  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
3131 
3132  if (argc > 1)
3133  {
3134  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
3135  {
3136  usage(progname);
3137  exit(0);
3138  }
3139  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
3140  {
3141  puts("initdb (PostgreSQL) " PG_VERSION);
3142  exit(0);
3143  }
3144  }
3145 
3146  /* process command-line options */
3147 
3148  while ((c = getopt_long(argc, argv, "dD:E:kL:nNU:WA:sST:X:", long_options, &option_index)) != -1)
3149  {
3150  switch (c)
3151  {
3152  case 'A':
3154 
3155  /*
3156  * When ident is specified, use peer for local connections.
3157  * Mirrored, when peer is specified, use ident for TCP/IP
3158  * connections.
3159  */
3160  if (strcmp(authmethodhost, "ident") == 0)
3161  authmethodlocal = "peer";
3162  else if (strcmp(authmethodlocal, "peer") == 0)
3163  authmethodhost = "ident";
3164  break;
3165  case 10:
3167  break;
3168  case 11:
3170  break;
3171  case 'D':
3173  break;
3174  case 'E':
3176  break;
3177  case 'W':
3178  pwprompt = true;
3179  break;
3180  case 'U':
3182  break;
3183  case 'd':
3184  debug = true;
3185  printf(_("Running in debug mode.\n"));
3186  break;
3187  case 'n':
3188  noclean = true;
3189  printf(_("Running in no-clean mode. Mistakes will not be cleaned up.\n"));
3190  break;
3191  case 'N':
3192  do_sync = false;
3193  break;
3194  case 'S':
3195  sync_only = true;
3196  break;
3197  case 'k':
3198  data_checksums = true;
3199  break;
3200  case 'L':
3202  break;
3203  case 1:
3204  locale = pg_strdup(optarg);
3205  break;
3206  case 2:
3208  break;
3209  case 3:
3211  break;
3212  case 4:
3214  break;
3215  case 5:
3217  break;
3218  case 6:
3220  break;
3221  case 7:
3223  break;
3224  case 8:
3225  locale = "C";
3226  break;
3227  case 9:
3229  break;
3230  case 's':
3231  show_setting = true;
3232  break;
3233  case 'T':
3235  break;
3236  case 'X':
3238  break;
3239  default:
3240  /* getopt_long already emitted a complaint */
3241  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3242  progname);
3243  exit(1);
3244  }
3245  }
3246 
3247 
3248  /*
3249  * Non-option argument specifies data directory as long as it wasn't
3250  * already specified with -D / --pgdata
3251  */
3252  if (optind < argc && strlen(pg_data) == 0)
3253  {
3254  pg_data = pg_strdup(argv[optind]);
3255  optind++;
3256  }
3257 
3258  if (optind < argc)
3259  {
3260  fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
3261  progname, argv[optind]);
3262  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3263  progname);
3264  exit(1);
3265  }
3266 
3267  /* If we only need to fsync, just do it and exit */
3268  if (sync_only)
3269  {
3270  setup_pgdata();
3271 
3272  /* must check that directory is readable */
3273  if (pg_check_dir(pg_data) <= 0)
3274  {
3275  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3276  progname, pg_data, strerror(errno));
3277  exit_nicely();
3278  }
3279 
3280  fputs(_("syncing data to disk ... "), stdout);
3281  fflush(stdout);
3282  fsync_pgdata(pg_data, progname, PG_VERSION_NUM);
3283  check_ok();
3284  return 0;
3285  }
3286 
3287  if (pwprompt && pwfilename)
3288  {
3289  fprintf(stderr, _("%s: password prompt and password file cannot be specified together\n"), progname);
3290  exit(1);
3291  }
3292 
3295 
3298 
3300 
3302 
3303  setup_pgdata();
3304 
3305  setup_bin_paths(argv[0]);
3306 
3307  effective_user = get_id();
3308  if (strlen(username) == 0)
3309  username = effective_user;
3310 
3311  if (strncmp(username, "pg_", 3) == 0)
3312  {
3313  fprintf(stderr, _("%s: superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"\n"), progname, username);
3314  exit(1);
3315  }
3316 
3317  printf(_("The files belonging to this database system will be owned "
3318  "by user \"%s\".\n"
3319  "This user must also own the server process.\n\n"),
3320  effective_user);
3321 
3322  set_info_version();
3323 
3325 
3327 
3329 
3330  printf("\n");
3331 
3332  if (data_checksums)
3333  printf(_("Data page checksums are enabled.\n"));
3334  else
3335  printf(_("Data page checksums are disabled.\n"));
3336 
3337  if (pwprompt || pwfilename)
3338  get_su_pwd();
3339 
3340  printf("\n");
3341 
3343 
3344  if (do_sync)
3345  {
3346  fputs(_("syncing data to disk ... "), stdout);
3347  fflush(stdout);
3348  fsync_pgdata(pg_data, progname, PG_VERSION_NUM);
3349  check_ok();
3350  }
3351  else
3352  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3353 
3354  if (authwarning != NULL)
3355  fprintf(stderr, "%s", authwarning);
3356 
3357  /*
3358  * Build up a shell command to tell the user how to start the server
3359  */
3360  start_db_cmd = createPQExpBuffer();
3361 
3362  /* Get directory specification used to start initdb ... */
3363  strlcpy(pg_ctl_path, argv[0], sizeof(pg_ctl_path));
3364  canonicalize_path(pg_ctl_path);
3365  get_parent_directory(pg_ctl_path);
3366  /* ... and tag on pg_ctl instead */
3367  join_path_components(pg_ctl_path, pg_ctl_path, "pg_ctl");
3368 
3369  /* path to pg_ctl, properly quoted */
3370  appendShellString(start_db_cmd, pg_ctl_path);
3371 
3372  /* add -D switch, with properly quoted data directory */
3373  appendPQExpBufferStr(start_db_cmd, " -D ");
3374  appendShellString(start_db_cmd, pgdata_native);
3375 
3376  /* add suggested -l switch and "start" command */
3377  appendPQExpBufferStr(start_db_cmd, " -l logfile start");
3378 
3379  printf(_("\nSuccess. You can now start the database server using:\n\n"
3380  " %s\n\n"),
3381  start_db_cmd->data);
3382 
3383  destroyPQExpBuffer(start_db_cmd);
3384 
3385  return 0;
3386 }
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
static void skip(struct vars *v)
Definition: regc_lex.c:1109
void setup_data_file_paths(void)
Definition: initdb.c:2665
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)
#define PG_CMD_PRINTF3(fmt, arg1, arg2, arg3)
Definition: initdb.c:316
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:343
static char * argv0
Definition: pg_ctl.c:93
static char * choose_dsm_implementation(void)
Definition: initdb.c:864
void setup_locale_encoding(void)
Definition: initdb.c:2576
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:2054
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:2956
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:1809
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:2847
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:2748
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:2437
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 IS_HIGHBIT_SET(ch)
Definition: c.h:965
#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:2310
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:2045
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:2972
#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:2149
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:2528
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:2777
#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:2174
static void make_template0(FILE *cmdfd)
Definition: initdb.c:2064
static int locale_date_order(const char *locale)
Definition: initdb.c:2183
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
static void setup_conversion(FILE *cmdfd)
Definition: initdb.c:1789
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:2713
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:293
#define NULL
Definition: c.h:226
static void setup_collation(FILE *cmdfd)
Definition: initdb.c:1651
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:2014
int main(int argc, char *argv[])
Definition: initdb.c:3076
static bool output_failed
Definition: initdb.c:164
static void setlocales(void)
Definition: initdb.c:2346
#define unsetenv(x)
Definition: win32.h:422
static void check_locale_name(int category, const char *locale, char **canonname)
Definition: initdb.c:2246
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:1844
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:2102
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:2397
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:2469
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:98
#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:2449
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:2488
#define _(x)
Definition: elog.c:84
const char * langname
Definition: initdb.c:659
static void trapsig(int signum)
Definition: initdb.c:2138
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:1987
#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