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