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