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 static void
2007 setup_privileges(FILE *cmdfd)
2008 {
2009  char **line;
2010  char **priv_lines;
2011  static char *privileges_setup[] = {
2012  "UPDATE pg_class "
2013  " SET relacl = (SELECT array_agg(a.acl) FROM "
2014  " (SELECT E'=r/\"$POSTGRES_SUPERUSERNAME\"' as acl "
2015  " UNION SELECT unnest(pg_catalog.acldefault("
2016  " CASE WHEN relkind = 'S' THEN 's' ELSE 'r' END::\"char\",10::oid))"
2017  " ) as a) "
2018  " WHERE relkind IN ('r', 'v', 'm', 'S') AND relacl IS NULL;\n\n",
2019  "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n\n",
2020  "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n\n",
2021  "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n",
2022  "INSERT INTO pg_init_privs "
2023  " (objoid, classoid, objsubid, initprivs, privtype)"
2024  " SELECT"
2025  " oid,"
2026  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
2027  " 0,"
2028  " relacl,"
2029  " 'i'"
2030  " FROM"
2031  " pg_class"
2032  " WHERE"
2033  " relacl IS NOT NULL"
2034  " AND relkind IN ('r', 'v', 'm', 'S');",
2035  "INSERT INTO pg_init_privs "
2036  " (objoid, classoid, objsubid, initprivs, privtype)"
2037  " SELECT"
2038  " pg_class.oid,"
2039  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
2040  " pg_attribute.attnum,"
2041  " pg_attribute.attacl,"
2042  " 'i'"
2043  " FROM"
2044  " pg_class"
2045  " JOIN pg_attribute ON (pg_class.oid = pg_attribute.attrelid)"
2046  " WHERE"
2047  " pg_attribute.attacl IS NOT NULL"
2048  " AND pg_class.relkind IN ('r', 'v', 'm', 'S');",
2049  "INSERT INTO pg_init_privs "
2050  " (objoid, classoid, objsubid, initprivs, privtype)"
2051  " SELECT"
2052  " oid,"
2053  " (SELECT oid FROM pg_class WHERE relname = 'pg_proc'),"
2054  " 0,"
2055  " proacl,"
2056  " 'i'"
2057  " FROM"
2058  " pg_proc"
2059  " WHERE"
2060  " proacl IS NOT NULL;",
2061  "INSERT INTO pg_init_privs "
2062  " (objoid, classoid, objsubid, initprivs, privtype)"
2063  " SELECT"
2064  " oid,"
2065  " (SELECT oid FROM pg_class WHERE relname = 'pg_type'),"
2066  " 0,"
2067  " typacl,"
2068  " 'i'"
2069  " FROM"
2070  " pg_type"
2071  " WHERE"
2072  " typacl IS NOT NULL;",
2073  "INSERT INTO pg_init_privs "
2074  " (objoid, classoid, objsubid, initprivs, privtype)"
2075  " SELECT"
2076  " oid,"
2077  " (SELECT oid FROM pg_class WHERE relname = 'pg_language'),"
2078  " 0,"
2079  " lanacl,"
2080  " 'i'"
2081  " FROM"
2082  " pg_language"
2083  " WHERE"
2084  " lanacl IS NOT NULL;",
2085  "INSERT INTO pg_init_privs "
2086  " (objoid, classoid, objsubid, initprivs, privtype)"
2087  " SELECT"
2088  " oid,"
2089  " (SELECT oid FROM pg_class WHERE "
2090  " relname = 'pg_largeobject_metadata'),"
2091  " 0,"
2092  " lomacl,"
2093  " 'i'"
2094  " FROM"
2095  " pg_largeobject_metadata"
2096  " WHERE"
2097  " lomacl IS NOT NULL;",
2098  "INSERT INTO pg_init_privs "
2099  " (objoid, classoid, objsubid, initprivs, privtype)"
2100  " SELECT"
2101  " oid,"
2102  " (SELECT oid FROM pg_class WHERE relname = 'pg_namespace'),"
2103  " 0,"
2104  " nspacl,"
2105  " 'i'"
2106  " FROM"
2107  " pg_namespace"
2108  " WHERE"
2109  " nspacl IS NOT NULL;",
2110  "INSERT INTO pg_init_privs "
2111  " (objoid, classoid, objsubid, initprivs, privtype)"
2112  " SELECT"
2113  " oid,"
2114  " (SELECT oid FROM pg_class WHERE relname = 'pg_database'),"
2115  " 0,"
2116  " datacl,"
2117  " 'i'"
2118  " FROM"
2119  " pg_database"
2120  " WHERE"
2121  " datacl IS NOT NULL;",
2122  "INSERT INTO pg_init_privs "
2123  " (objoid, classoid, objsubid, initprivs, privtype)"
2124  " SELECT"
2125  " oid,"
2126  " (SELECT oid FROM pg_class WHERE relname = 'pg_tablespace'),"
2127  " 0,"
2128  " spcacl,"
2129  " 'i'"
2130  " FROM"
2131  " pg_tablespace"
2132  " WHERE"
2133  " spcacl IS NOT NULL;",
2134  "INSERT INTO pg_init_privs "
2135  " (objoid, classoid, objsubid, initprivs, privtype)"
2136  " SELECT"
2137  " oid,"
2138  " (SELECT oid FROM pg_class WHERE "
2139  " relname = 'pg_foreign_data_wrapper'),"
2140  " 0,"
2141  " fdwacl,"
2142  " 'i'"
2143  " FROM"
2144  " pg_foreign_data_wrapper"
2145  " WHERE"
2146  " fdwacl IS NOT NULL;",
2147  "INSERT INTO pg_init_privs "
2148  " (objoid, classoid, objsubid, initprivs, privtype)"
2149  " SELECT"
2150  " oid,"
2151  " (SELECT oid FROM pg_class "
2152  " WHERE relname = 'pg_foreign_server'),"
2153  " 0,"
2154  " srvacl,"
2155  " 'i'"
2156  " FROM"
2157  " pg_foreign_server"
2158  " WHERE"
2159  " srvacl IS NOT NULL;",
2160  NULL
2161  };
2162 
2163  priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
2165  for (line = priv_lines; *line != NULL; line++)
2166  PG_CMD_PUTS(*line);
2167 }
2168 
2169 /*
2170  * extract the strange version of version required for information schema
2171  * (09.08.0007abc)
2172  */
2173 static void
2175 {
2176  char *letterversion;
2177  long major = 0,
2178  minor = 0,
2179  micro = 0;
2180  char *endptr;
2181  char *vstr = pg_strdup(PG_VERSION);
2182  char *ptr;
2183 
2184  ptr = vstr + (strlen(vstr) - 1);
2185  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
2186  ptr--;
2187  letterversion = ptr + 1;
2188  major = strtol(vstr, &endptr, 10);
2189  if (*endptr)
2190  minor = strtol(endptr + 1, &endptr, 10);
2191  if (*endptr)
2192  micro = strtol(endptr + 1, &endptr, 10);
2193  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
2194  major, minor, micro, letterversion);
2195 }
2196 
2197 /*
2198  * load info schema and populate from features file
2199  */
2200 static void
2201 setup_schema(FILE *cmdfd)
2202 {
2203  char **line;
2204  char **lines;
2205 
2206  lines = readfile(info_schema_file);
2207 
2208  for (line = lines; *line != NULL; line++)
2209  {
2210  PG_CMD_PUTS(*line);
2211  free(*line);
2212  }
2213 
2214  free(lines);
2215 
2216  PG_CMD_PRINTF1("UPDATE information_schema.sql_implementation_info "
2217  " SET character_value = '%s' "
2218  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
2219  infoversion);
2220 
2221  PG_CMD_PRINTF1("COPY information_schema.sql_features "
2222  " (feature_id, feature_name, sub_feature_id, "
2223  " sub_feature_name, is_supported, comments) "
2224  " FROM E'%s';\n\n",
2226 }
2227 
2228 /*
2229  * load PL/pgsql server-side language
2230  */
2231 static void
2232 load_plpgsql(FILE *cmdfd)
2233 {
2234  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
2235 }
2236 
2237 /*
2238  * clean everything up in template1
2239  */
2240 static void
2241 vacuum_db(FILE *cmdfd)
2242 {
2243  /* Run analyze before VACUUM so the statistics are frozen. */
2244  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
2245 }
2246 
2247 /*
2248  * copy template1 to template0
2249  */
2250 static void
2251 make_template0(FILE *cmdfd)
2252 {
2253  const char *const * line;
2254  static const char *const template0_setup[] = {
2255  "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false;\n\n",
2256 
2257  /*
2258  * We use the OID of template0 to determine lastsysoid
2259  */
2260  "UPDATE pg_database SET datlastsysoid = "
2261  " (SELECT oid FROM pg_database "
2262  " WHERE datname = 'template0');\n\n",
2263 
2264  /*
2265  * Explicitly revoke public create-schema and create-temp-table
2266  * privileges in template1 and template0; else the latter would be on
2267  * by default
2268  */
2269  "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n",
2270  "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n",
2271 
2272  "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n",
2273 
2274  /*
2275  * Finally vacuum to clean up dead rows in pg_database
2276  */
2277  "VACUUM pg_database;\n\n",
2278  NULL
2279  };
2280 
2281  for (line = template0_setup; *line; line++)
2282  PG_CMD_PUTS(*line);
2283 }
2284 
2285 /*
2286  * copy template1 to postgres
2287  */
2288 static void
2289 make_postgres(FILE *cmdfd)
2290 {
2291  const char *const * line;
2292  static const char *const postgres_setup[] = {
2293  "CREATE DATABASE postgres;\n\n",
2294  "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",
2295  NULL
2296  };
2297 
2298  for (line = postgres_setup; *line; line++)
2299  PG_CMD_PUTS(*line);
2300 }
2301 
2302 /*
2303  * Issue fsync recursively on PGDATA and all its contents.
2304  *
2305  * We fsync regular files and directories wherever they are, but we
2306  * follow symlinks only for pg_xlog and immediately under pg_tblspc.
2307  * Other symlinks are presumed to point at files we're not responsible
2308  * for fsyncing, and might not have privileges to write at all.
2309  *
2310  * Errors are reported but not considered fatal.
2311  */
2312 static void
2314 {
2315  bool xlog_is_symlink;
2316  char pg_xlog[MAXPGPATH];
2317  char pg_tblspc[MAXPGPATH];
2318 
2319  fputs(_("syncing data to disk ... "), stdout);
2320  fflush(stdout);
2321 
2322  snprintf(pg_xlog, MAXPGPATH, "%s/pg_xlog", pg_data);
2323  snprintf(pg_tblspc, MAXPGPATH, "%s/pg_tblspc", pg_data);
2324 
2325  /*
2326  * If pg_xlog is a symlink, we'll need to recurse into it separately,
2327  * because the first walkdir below will ignore it.
2328  */
2329  xlog_is_symlink = false;
2330 
2331 #ifndef WIN32
2332  {
2333  struct stat st;
2334 
2335  if (lstat(pg_xlog, &st) < 0)
2336  fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
2337  progname, pg_xlog, strerror(errno));
2338  else if (S_ISLNK(st.st_mode))
2339  xlog_is_symlink = true;
2340  }
2341 #else
2342  if (pgwin32_is_junction(pg_xlog))
2343  xlog_is_symlink = true;
2344 #endif
2345 
2346  /*
2347  * If possible, hint to the kernel that we're soon going to fsync the data
2348  * directory and its contents.
2349  */
2350 #ifdef PG_FLUSH_DATA_WORKS
2351  walkdir(pg_data, pre_sync_fname, false);
2352  if (xlog_is_symlink)
2353  walkdir(pg_xlog, pre_sync_fname, false);
2354  walkdir(pg_tblspc, pre_sync_fname, true);
2355 #endif
2356 
2357  /*
2358  * Now we do the fsync()s in the same order.
2359  *
2360  * The main call ignores symlinks, so in addition to specially processing
2361  * pg_xlog if it's a symlink, pg_tblspc has to be visited separately with
2362  * process_symlinks = true. Note that if there are any plain directories
2363  * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
2364  * so we don't worry about optimizing it.
2365  */
2366  walkdir(pg_data, fsync_fname_ext, false);
2367  if (xlog_is_symlink)
2368  walkdir(pg_xlog, fsync_fname_ext, false);
2369  walkdir(pg_tblspc, fsync_fname_ext, true);
2370 
2371  check_ok();
2372 }
2373 
2374 
2375 /*
2376  * signal handler in case we are interrupted.
2377  *
2378  * The Windows runtime docs at
2379  * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
2380  * specifically forbid a number of things being done from a signal handler,
2381  * including IO, memory allocation and system calls, and only allow jmpbuf
2382  * if you are handling SIGFPE.
2383  *
2384  * I avoided doing the forbidden things by setting a flag instead of calling
2385  * exit_nicely() directly.
2386  *
2387  * Also note the behaviour of Windows with SIGINT, which says this:
2388  * Note SIGINT is not supported for any Win32 application, including
2389  * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
2390  * Win32 operating systems generate a new thread to specifically handle
2391  * that interrupt. This can cause a single-thread application such as UNIX,
2392  * to become multithreaded, resulting in unexpected behavior.
2393  *
2394  * I have no idea how to handle this. (Strange they call UNIX an application!)
2395  * So this will need some testing on Windows.
2396  */
2397 static void
2398 trapsig(int signum)
2399 {
2400  /* handle systems that reset the handler, like Windows (grr) */
2401  pqsignal(signum, trapsig);
2402  caught_signal = true;
2403 }
2404 
2405 /*
2406  * call exit_nicely() if we got a signal, or else output "ok".
2407  */
2408 static void
2410 {
2411  if (caught_signal)
2412  {
2413  printf(_("caught signal\n"));
2414  fflush(stdout);
2415  exit_nicely();
2416  }
2417  else if (output_failed)
2418  {
2419  printf(_("could not write to child process: %s\n"),
2421  fflush(stdout);
2422  exit_nicely();
2423  }
2424  else
2425  {
2426  /* all seems well */
2427  printf(_("ok\n"));
2428  fflush(stdout);
2429  }
2430 }
2431 
2432 /* Hack to suppress a warning about %x from some versions of gcc */
2433 static inline size_t
2434 my_strftime(char *s, size_t max, const char *fmt, const struct tm * tm)
2435 {
2436  return strftime(s, max, fmt, tm);
2437 }
2438 
2439 /*
2440  * Determine likely date order from locale
2441  */
2442 static int
2444 {
2445  struct tm testtime;
2446  char buf[128];
2447  char *posD;
2448  char *posM;
2449  char *posY;
2450  char *save;
2451  size_t res;
2452  int result;
2453 
2454  result = DATEORDER_MDY; /* default */
2455 
2456  save = setlocale(LC_TIME, NULL);
2457  if (!save)
2458  return result;
2459  save = pg_strdup(save);
2460 
2461  setlocale(LC_TIME, locale);
2462 
2463  memset(&testtime, 0, sizeof(testtime));
2464  testtime.tm_mday = 22;
2465  testtime.tm_mon = 10; /* November, should come out as "11" */
2466  testtime.tm_year = 133; /* 2033 */
2467 
2468  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
2469 
2470  setlocale(LC_TIME, save);
2471  free(save);
2472 
2473  if (res == 0)
2474  return result;
2475 
2476  posM = strstr(buf, "11");
2477  posD = strstr(buf, "22");
2478  posY = strstr(buf, "33");
2479 
2480  if (!posM || !posD || !posY)
2481  return result;
2482 
2483  if (posY < posM && posM < posD)
2484  result = DATEORDER_YMD;
2485  else if (posD < posM)
2486  result = DATEORDER_DMY;
2487  else
2488  result = DATEORDER_MDY;
2489 
2490  return result;
2491 }
2492 
2493 /*
2494  * Verify that locale name is valid for the locale category.
2495  *
2496  * If successful, and canonname isn't NULL, a malloc'd copy of the locale's
2497  * canonical name is stored there. This is especially useful for figuring out
2498  * what locale name "" means (ie, the environment value). (Actually,
2499  * it seems that on most implementations that's the only thing it's good for;
2500  * we could wish that setlocale gave back a canonically spelled version of
2501  * the locale name, but typically it doesn't.)
2502  *
2503  * this should match the backend's check_locale() function
2504  */
2505 static void
2506 check_locale_name(int category, const char *locale, char **canonname)
2507 {
2508  char *save;
2509  char *res;
2510 
2511  if (canonname)
2512  *canonname = NULL; /* in case of failure */
2513 
2514  save = setlocale(category, NULL);
2515  if (!save)
2516  {
2517  fprintf(stderr, _("%s: setlocale() failed\n"),
2518  progname);
2519  exit(1);
2520  }
2521 
2522  /* save may be pointing at a modifiable scratch variable, so copy it. */
2523  save = pg_strdup(save);
2524 
2525  /* set the locale with setlocale, to see if it accepts it. */
2526  res = setlocale(category, locale);
2527 
2528  /* save canonical name if requested. */
2529  if (res && canonname)
2530  *canonname = pg_strdup(res);
2531 
2532  /* restore old value. */
2533  if (!setlocale(category, save))
2534  {
2535  fprintf(stderr, _("%s: failed to restore old locale \"%s\"\n"),
2536  progname, save);
2537  exit(1);
2538  }
2539  free(save);
2540 
2541  /* complain if locale wasn't valid */
2542  if (res == NULL)
2543  {
2544  if (*locale)
2545  fprintf(stderr, _("%s: invalid locale name \"%s\"\n"),
2546  progname, locale);
2547  else
2548  {
2549  /*
2550  * If no relevant switch was given on command line, locale is an
2551  * empty string, which is not too helpful to report. Presumably
2552  * setlocale() found something it did not like in the environment.
2553  * Ideally we'd report the bad environment variable, but since
2554  * setlocale's behavior is implementation-specific, it's hard to
2555  * be sure what it didn't like. Print a safe generic message.
2556  */
2557  fprintf(stderr, _("%s: invalid locale settings; check LANG and LC_* environment variables\n"),
2558  progname);
2559  }
2560  exit(1);
2561  }
2562 }
2563 
2564 /*
2565  * check if the chosen encoding matches the encoding required by the locale
2566  *
2567  * this should match the similar check in the backend createdb() function
2568  */
2569 static bool
2570 check_locale_encoding(const char *locale, int user_enc)
2571 {
2572  int locale_enc;
2573 
2574  locale_enc = pg_get_encoding_from_locale(locale, true);
2575 
2576  /* See notes in createdb() to understand these tests */
2577  if (!(locale_enc == user_enc ||
2578  locale_enc == PG_SQL_ASCII ||
2579  locale_enc == -1 ||
2580 #ifdef WIN32
2581  user_enc == PG_UTF8 ||
2582 #endif
2583  user_enc == PG_SQL_ASCII))
2584  {
2585  fprintf(stderr, _("%s: encoding mismatch\n"), progname);
2586  fprintf(stderr,
2587  _("The encoding you selected (%s) and the encoding that the\n"
2588  "selected locale uses (%s) do not match. This would lead to\n"
2589  "misbehavior in various character string processing functions.\n"
2590  "Rerun %s and either do not specify an encoding explicitly,\n"
2591  "or choose a matching combination.\n"),
2592  pg_encoding_to_char(user_enc),
2593  pg_encoding_to_char(locale_enc),
2594  progname);
2595  return false;
2596  }
2597  return true;
2598 }
2599 
2600 /*
2601  * set up the locale variables
2602  *
2603  * assumes we have called setlocale(LC_ALL, "") -- see set_pglocale_pgservice
2604  */
2605 static void
2607 {
2608  char *canonname;
2609 
2610  /* set empty lc_* values to locale config if set */
2611 
2612  if (strlen(locale) > 0)
2613  {
2614  if (strlen(lc_ctype) == 0)
2615  lc_ctype = locale;
2616  if (strlen(lc_collate) == 0)
2617  lc_collate = locale;
2618  if (strlen(lc_numeric) == 0)
2619  lc_numeric = locale;
2620  if (strlen(lc_time) == 0)
2621  lc_time = locale;
2622  if (strlen(lc_monetary) == 0)
2623  lc_monetary = locale;
2624  if (strlen(lc_messages) == 0)
2625  lc_messages = locale;
2626  }
2627 
2628  /*
2629  * canonicalize locale names, and obtain any missing values from our
2630  * current environment
2631  */
2632 
2633  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2634  lc_ctype = canonname;
2635  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2636  lc_collate = canonname;
2637  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2638  lc_numeric = canonname;
2639  check_locale_name(LC_TIME, lc_time, &canonname);
2640  lc_time = canonname;
2641  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2642  lc_monetary = canonname;
2643 #if defined(LC_MESSAGES) && !defined(WIN32)
2644  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2645  lc_messages = canonname;
2646 #else
2647  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2648  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2649  lc_messages = canonname;
2650 #endif
2651 }
2652 
2653 /*
2654  * print help text
2655  */
2656 static void
2657 usage(const char *progname)
2658 {
2659  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2660  printf(_("Usage:\n"));
2661  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2662  printf(_("\nOptions:\n"));
2663  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2664  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2665  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2666  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2667  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2668  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2669  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2670  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2671  " set default locale in the respective category for\n"
2672  " new databases (default taken from environment)\n"));
2673  printf(_(" --no-locale equivalent to --locale=C\n"));
2674  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2675  printf(_(" -T, --text-search-config=CFG\n"
2676  " default text search configuration\n"));
2677  printf(_(" -U, --username=NAME database superuser name\n"));
2678  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2679  printf(_(" -X, --xlogdir=XLOGDIR location for the transaction log directory\n"));
2680  printf(_("\nLess commonly used options:\n"));
2681  printf(_(" -d, --debug generate lots of debugging output\n"));
2682  printf(_(" -k, --data-checksums use data page checksums\n"));
2683  printf(_(" -L DIRECTORY where to find the input files\n"));
2684  printf(_(" -n, --noclean do not clean up after errors\n"));
2685  printf(_(" -N, --nosync do not wait for changes to be written safely to disk\n"));
2686  printf(_(" -s, --show show internal settings\n"));
2687  printf(_(" -S, --sync-only only sync data directory\n"));
2688  printf(_("\nOther options:\n"));
2689  printf(_(" -V, --version output version information, then exit\n"));
2690  printf(_(" -?, --help show this help, then exit\n"));
2691  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2692  "is used.\n"));
2693  printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2694 }
2695 
2696 static void
2697 check_authmethod_unspecified(const char **authmethod)
2698 {
2699  if (*authmethod == NULL || strlen(*authmethod) == 0)
2700  {
2701  authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
2702  "You can change this by editing pg_hba.conf or using the option -A, or\n"
2703  "--auth-local and --auth-host, the next time you run initdb.\n");
2704  *authmethod = "trust";
2705  }
2706 }
2707 
2708 static void
2709 check_authmethod_valid(const char *authmethod, const char *const * valid_methods, const char *conntype)
2710 {
2711  const char *const * p;
2712 
2713  for (p = valid_methods; *p; p++)
2714  {
2715  if (strcmp(authmethod, *p) == 0)
2716  return;
2717  /* with space = param */
2718  if (strchr(authmethod, ' '))
2719  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2720  return;
2721  }
2722 
2723  fprintf(stderr, _("%s: invalid authentication method \"%s\" for \"%s\" connections\n"),
2724  progname, authmethod, conntype);
2725  exit(1);
2726 }
2727 
2728 static void
2730 {
2731  if ((strcmp(authmethodlocal, "md5") == 0 ||
2732  strcmp(authmethodlocal, "password") == 0) &&
2733  (strcmp(authmethodhost, "md5") == 0 ||
2734  strcmp(authmethodhost, "password") == 0) &&
2735  !(pwprompt || pwfilename))
2736  {
2737  fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname,
2738  (strcmp(authmethodlocal, "md5") == 0 ||
2739  strcmp(authmethodlocal, "password") == 0)
2740  ? authmethodlocal
2741  : authmethodhost);
2742  exit(1);
2743  }
2744 }
2745 
2746 
2747 void
2749 {
2750  char *pgdata_get_env,
2751  *pgdata_set_env;
2752 
2753  if (strlen(pg_data) == 0)
2754  {
2755  pgdata_get_env = getenv("PGDATA");
2756  if (pgdata_get_env && strlen(pgdata_get_env))
2757  {
2758  /* PGDATA found */
2759  pg_data = pg_strdup(pgdata_get_env);
2760  }
2761  else
2762  {
2763  fprintf(stderr,
2764  _("%s: no data directory specified\n"
2765  "You must identify the directory where the data for this database system\n"
2766  "will reside. Do this with either the invocation option -D or the\n"
2767  "environment variable PGDATA.\n"),
2768  progname);
2769  exit(1);
2770  }
2771  }
2772 
2775 
2776  /*
2777  * we have to set PGDATA for postgres rather than pass it on the command
2778  * line to avoid dumb quoting problems on Windows, and we would especially
2779  * need quotes otherwise on Windows because paths there are most likely to
2780  * have embedded spaces.
2781  */
2782  pgdata_set_env = psprintf("PGDATA=%s", pg_data);
2783  putenv(pgdata_set_env);
2784 }
2785 
2786 
2787 void
2789 {
2790  int ret;
2791 
2792  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2793  backend_exec)) < 0)
2794  {
2795  char full_path[MAXPGPATH];
2796 
2797  if (find_my_exec(argv0, full_path) < 0)
2798  strlcpy(full_path, progname, sizeof(full_path));
2799 
2800  if (ret == -1)
2801  fprintf(stderr,
2802  _("The program \"postgres\" is needed by %s "
2803  "but was not found in the\n"
2804  "same directory as \"%s\".\n"
2805  "Check your installation.\n"),
2806  progname, full_path);
2807  else
2808  fprintf(stderr,
2809  _("The program \"postgres\" was found by \"%s\"\n"
2810  "but was not the same version as %s.\n"
2811  "Check your installation.\n"),
2812  full_path, progname);
2813  exit(1);
2814  }
2815 
2816  /* store binary directory */
2817  strcpy(bin_path, backend_exec);
2818  *last_dir_separator(bin_path) = '\0';
2820 
2821  if (!share_path)
2822  {
2825  }
2826  else if (!is_absolute_path(share_path))
2827  {
2828  fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
2829  exit(1);
2830  }
2831 
2833 }
2834 
2835 void
2837 {
2838  int user_enc;
2839 
2840  setlocales();
2841 
2842  if (strcmp(lc_ctype, lc_collate) == 0 &&
2843  strcmp(lc_ctype, lc_time) == 0 &&
2844  strcmp(lc_ctype, lc_numeric) == 0 &&
2845  strcmp(lc_ctype, lc_monetary) == 0 &&
2846  strcmp(lc_ctype, lc_messages) == 0)
2847  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2848  else
2849  {
2850  printf(_("The database cluster will be initialized with locales\n"
2851  " COLLATE: %s\n"
2852  " CTYPE: %s\n"
2853  " MESSAGES: %s\n"
2854  " MONETARY: %s\n"
2855  " NUMERIC: %s\n"
2856  " TIME: %s\n"),
2857  lc_collate,
2858  lc_ctype,
2859  lc_messages,
2860  lc_monetary,
2861  lc_numeric,
2862  lc_time);
2863  }
2864 
2865  if (strlen(encoding) == 0)
2866  {
2867  int ctype_enc;
2868 
2869  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2870 
2871  if (ctype_enc == -1)
2872  {
2873  /* Couldn't recognize the locale's codeset */
2874  fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"),
2875  progname, lc_ctype);
2876  fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2877  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2878  progname);
2879  exit(1);
2880  }
2881  else if (!pg_valid_server_encoding_id(ctype_enc))
2882  {
2883  /*
2884  * We recognized it, but it's not a legal server encoding. On
2885  * Windows, UTF-8 works with any locale, so we can fall back to
2886  * UTF-8.
2887  */
2888 #ifdef WIN32
2889  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2890  "The default database encoding will be set to \"%s\" instead.\n"),
2891  pg_encoding_to_char(ctype_enc),
2893  ctype_enc = PG_UTF8;
2894  encodingid = encodingid_to_string(ctype_enc);
2895 #else
2896  fprintf(stderr,
2897  _("%s: locale \"%s\" requires unsupported encoding \"%s\"\n"),
2898  progname, lc_ctype, pg_encoding_to_char(ctype_enc));
2899  fprintf(stderr,
2900  _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
2901  "Rerun %s with a different locale selection.\n"),
2902  pg_encoding_to_char(ctype_enc), progname);
2903  exit(1);
2904 #endif
2905  }
2906  else
2907  {
2908  encodingid = encodingid_to_string(ctype_enc);
2909  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2910  pg_encoding_to_char(ctype_enc));
2911  }
2912  }
2913  else
2915 
2916  user_enc = atoi(encodingid);
2917  if (!check_locale_encoding(lc_ctype, user_enc) ||
2918  !check_locale_encoding(lc_collate, user_enc))
2919  exit(1); /* check_locale_encoding printed the error */
2920 
2921 }
2922 
2923 
2924 void
2926 {
2927  set_input(&bki_file, "postgres.bki");
2928  set_input(&desc_file, "postgres.description");
2929  set_input(&shdesc_file, "postgres.shdescription");
2930  set_input(&hba_file, "pg_hba.conf.sample");
2931  set_input(&ident_file, "pg_ident.conf.sample");
2932  set_input(&conf_file, "postgresql.conf.sample");
2933  set_input(&conversion_file, "conversion_create.sql");
2934  set_input(&dictionary_file, "snowball_create.sql");
2935  set_input(&info_schema_file, "information_schema.sql");
2936  set_input(&features_file, "sql_features.txt");
2937  set_input(&system_views_file, "system_views.sql");
2938 
2939  if (show_setting || debug)
2940  {
2941  fprintf(stderr,
2942  "VERSION=%s\n"
2943  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2944  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2945  "POSTGRES_DESCR=%s\nPOSTGRES_SHDESCR=%s\n"
2946  "POSTGRESQL_CONF_SAMPLE=%s\n"
2947  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2948  PG_VERSION,
2950  username, bki_file,
2952  conf_file,
2953  hba_file, ident_file);
2954  if (show_setting)
2955  exit(0);
2956  }
2957 
2969 }
2970 
2971 
2972 void
2974 {
2975  if (strlen(default_text_search_config) == 0)
2976  {
2979  {
2980  printf(_("%s: could not find suitable text search configuration for locale \"%s\"\n"),
2981  progname, lc_ctype);
2982  default_text_search_config = "simple";
2983  }
2984  }
2985  else
2986  {
2987  const char *checkmatch = find_matching_ts_config(lc_ctype);
2988 
2989  if (checkmatch == NULL)
2990  {
2991  printf(_("%s: warning: suitable text search configuration for locale \"%s\" is unknown\n"),
2992  progname, lc_ctype);
2993  }
2994  else if (strcmp(checkmatch, default_text_search_config) != 0)
2995  {
2996  printf(_("%s: warning: specified text search configuration \"%s\" might not match locale \"%s\"\n"),
2998  }
2999  }
3000 
3001  printf(_("The default text search configuration will be set to \"%s\".\n"),
3003 
3004 }
3005 
3006 
3007 void
3009 {
3010  /* some of these are not valid on Windows */
3011 #ifdef SIGHUP
3013 #endif
3014 #ifdef SIGINT
3015  pqsignal(SIGINT, trapsig);
3016 #endif
3017 #ifdef SIGQUIT
3019 #endif
3020 #ifdef SIGTERM
3021  pqsignal(SIGTERM, trapsig);
3022 #endif
3023 
3024  /* Ignore SIGPIPE when writing to backend, so we can clean up */
3025 #ifdef SIGPIPE
3027 #endif
3028 
3029  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
3030 #ifdef SIGSYS
3031  pqsignal(SIGSYS, SIG_IGN);
3032 #endif
3033 }
3034 
3035 
3036 void
3038 {
3039  int ret;
3040 
3041  switch ((ret = pg_check_dir(pg_data)))
3042  {
3043  case 0:
3044  /* PGDATA not there, must create it */
3045  printf(_("creating directory %s ... "),
3046  pg_data);
3047  fflush(stdout);
3048 
3049  if (pg_mkdir_p(pg_data, S_IRWXU) != 0)
3050  {
3051  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3052  progname, pg_data, strerror(errno));
3053  exit_nicely();
3054  }
3055  else
3056  check_ok();
3057 
3058  made_new_pgdata = true;
3059  break;
3060 
3061  case 1:
3062  /* Present but empty, fix permissions and use it */
3063  printf(_("fixing permissions on existing directory %s ... "),
3064  pg_data);
3065  fflush(stdout);
3066 
3067  if (chmod(pg_data, S_IRWXU) != 0)
3068  {
3069  fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
3070  progname, pg_data, strerror(errno));
3071  exit_nicely();
3072  }
3073  else
3074  check_ok();
3075 
3076  found_existing_pgdata = true;
3077  break;
3078 
3079  case 2:
3080  case 3:
3081  case 4:
3082  /* Present and not empty */
3083  fprintf(stderr,
3084  _("%s: directory \"%s\" exists but is not empty\n"),
3085  progname, pg_data);
3086  if (ret != 4)
3087  warn_on_mount_point(ret);
3088  else
3089  fprintf(stderr,
3090  _("If you want to create a new database system, either remove or empty\n"
3091  "the directory \"%s\" or run %s\n"
3092  "with an argument other than \"%s\".\n"),
3094  exit(1); /* no further message needed */
3095 
3096  default:
3097  /* Trouble accessing directory */
3098  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3099  progname, pg_data, strerror(errno));
3100  exit_nicely();
3101  }
3102 }
3103 
3104 
3105 /* Create transaction log directory, and symlink if required */
3106 void
3108 {
3109  char *subdirloc;
3110 
3111  /* form name of the place for the subdirectory or symlink */
3112  subdirloc = psprintf("%s/pg_xlog", pg_data);
3113 
3114  if (strcmp(xlog_dir, "") != 0)
3115  {
3116  int ret;
3117 
3118  /* clean up xlog directory name, check it's absolute */
3120  if (!is_absolute_path(xlog_dir))
3121  {
3122  fprintf(stderr, _("%s: transaction log directory location must be an absolute path\n"), progname);
3123  exit_nicely();
3124  }
3125 
3126  /* check if the specified xlog directory exists/is empty */
3127  switch ((ret = pg_check_dir(xlog_dir)))
3128  {
3129  case 0:
3130  /* xlog directory not there, must create it */
3131  printf(_("creating directory %s ... "),
3132  xlog_dir);
3133  fflush(stdout);
3134 
3135  if (pg_mkdir_p(xlog_dir, S_IRWXU) != 0)
3136  {
3137  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3138  progname, xlog_dir, strerror(errno));
3139  exit_nicely();
3140  }
3141  else
3142  check_ok();
3143 
3144  made_new_xlogdir = true;
3145  break;
3146 
3147  case 1:
3148  /* Present but empty, fix permissions and use it */
3149  printf(_("fixing permissions on existing directory %s ... "),
3150  xlog_dir);
3151  fflush(stdout);
3152 
3153  if (chmod(xlog_dir, S_IRWXU) != 0)
3154  {
3155  fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
3156  progname, xlog_dir, strerror(errno));
3157  exit_nicely();
3158  }
3159  else
3160  check_ok();
3161 
3162  found_existing_xlogdir = true;
3163  break;
3164 
3165  case 2:
3166  case 3:
3167  case 4:
3168  /* Present and not empty */
3169  fprintf(stderr,
3170  _("%s: directory \"%s\" exists but is not empty\n"),
3171  progname, xlog_dir);
3172  if (ret != 4)
3173  warn_on_mount_point(ret);
3174  else
3175  fprintf(stderr,
3176  _("If you want to store the transaction log there, either\n"
3177  "remove or empty the directory \"%s\".\n"),
3178  xlog_dir);
3179  exit_nicely();
3180 
3181  default:
3182  /* Trouble accessing directory */
3183  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3184  progname, xlog_dir, strerror(errno));
3185  exit_nicely();
3186  }
3187 
3188 #ifdef HAVE_SYMLINK
3189  if (symlink(xlog_dir, subdirloc) != 0)
3190  {
3191  fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
3192  progname, subdirloc, strerror(errno));
3193  exit_nicely();
3194  }
3195 #else
3196  fprintf(stderr, _("%s: symlinks are not supported on this platform"));
3197  exit_nicely();
3198 #endif
3199  }
3200  else
3201  {
3202  /* Without -X option, just make the subdirectory normally */
3203  if (mkdir(subdirloc, S_IRWXU) < 0)
3204  {
3205  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3206  progname, subdirloc, strerror(errno));
3207  exit_nicely();
3208  }
3209  }
3210 
3211  free(subdirloc);
3212 }
3213 
3214 
3215 void
3217 {
3218  if (error == 2)
3219  fprintf(stderr,
3220  _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
3221  else if (error == 3)
3222  fprintf(stderr,
3223  _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
3224 
3225  fprintf(stderr,
3226  _("Using a mount point directly as the data directory is not recommended.\n"
3227  "Create a subdirectory under the mount point.\n"));
3228 }
3229 
3230 
3231 void
3233 {
3234  PG_CMD_DECL;
3235  int i;
3236 
3237  setup_signals();
3238 
3239  umask(S_IRWXG | S_IRWXO);
3240 
3242 
3244 
3245  /* Create required subdirectories (other than pg_xlog) */
3246  printf(_("creating subdirectories ... "));
3247  fflush(stdout);
3248 
3249  for (i = 0; i < lengthof(subdirs); i++)
3250  {
3251  char *path;
3252 
3253  path = psprintf("%s/%s", pg_data, subdirs[i]);
3254 
3255  /*
3256  * The parent directory already exists, so we only need mkdir() not
3257  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
3258  */
3259  if (mkdir(path, S_IRWXU) < 0)
3260  {
3261  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3262  progname, path, strerror(errno));
3263  exit_nicely();
3264  }
3265 
3266  free(path);
3267  }
3268 
3269  check_ok();
3270 
3271  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
3273 
3274  /* Select suitable configuration settings */
3275  set_null_conf();
3277 
3278  /* Now create all the text config files */
3279  setup_config();
3280 
3281  /* Bootstrap template1 */
3283 
3284  /*
3285  * Make the per-database PG_VERSION for template1 only after init'ing it
3286  */
3287  write_version_file("base/1");
3288 
3289  /*
3290  * Create the stuff we don't need to use bootstrap mode for, using a
3291  * backend running in simple standalone mode.
3292  */
3293  fputs(_("performing post-bootstrap initialization ... "), stdout);
3294  fflush(stdout);
3295 
3296  snprintf(cmd, sizeof(cmd),
3297  "\"%s\" %s template1 >%s",
3299  DEVNULL);
3300 
3301  PG_CMD_OPEN;
3302 
3303  setup_auth(cmdfd);
3304  if (pwprompt || pwfilename)
3305  get_set_pwd(cmdfd);
3306 
3307  setup_depend(cmdfd);
3308 
3309  setup_sysviews(cmdfd);
3310 
3311  setup_description(cmdfd);
3312 
3313  setup_collation(cmdfd);
3314 
3315  setup_conversion(cmdfd);
3316 
3317  setup_dictionary(cmdfd);
3318 
3319  setup_privileges(cmdfd);
3320 
3321  setup_schema(cmdfd);
3322 
3323  load_plpgsql(cmdfd);
3324 
3325  vacuum_db(cmdfd);
3326 
3327  make_template0(cmdfd);
3328 
3329  make_postgres(cmdfd);
3330 
3331  PG_CMD_CLOSE;
3332 
3333  check_ok();
3334 }
3335 
3336 
3337 int
3338 main(int argc, char *argv[])
3339 {
3340  static struct option long_options[] = {
3341  {"pgdata", required_argument, NULL, 'D'},
3342  {"encoding", required_argument, NULL, 'E'},
3343  {"locale", required_argument, NULL, 1},
3344  {"lc-collate", required_argument, NULL, 2},
3345  {"lc-ctype", required_argument, NULL, 3},
3346  {"lc-monetary", required_argument, NULL, 4},
3347  {"lc-numeric", required_argument, NULL, 5},
3348  {"lc-time", required_argument, NULL, 6},
3349  {"lc-messages", required_argument, NULL, 7},
3350  {"no-locale", no_argument, NULL, 8},
3351  {"text-search-config", required_argument, NULL, 'T'},
3352  {"auth", required_argument, NULL, 'A'},
3353  {"auth-local", required_argument, NULL, 10},
3354  {"auth-host", required_argument, NULL, 11},
3355  {"pwprompt", no_argument, NULL, 'W'},
3356  {"pwfile", required_argument, NULL, 9},
3357  {"username", required_argument, NULL, 'U'},
3358  {"help", no_argument, NULL, '?'},
3359  {"version", no_argument, NULL, 'V'},
3360  {"debug", no_argument, NULL, 'd'},
3361  {"show", no_argument, NULL, 's'},
3362  {"noclean", no_argument, NULL, 'n'},
3363  {"nosync", no_argument, NULL, 'N'},
3364  {"sync-only", no_argument, NULL, 'S'},
3365  {"xlogdir", required_argument, NULL, 'X'},
3366  {"data-checksums", no_argument, NULL, 'k'},
3367  {NULL, 0, NULL, 0}
3368  };
3369 
3370  /*
3371  * options with no short version return a low integer, the rest return
3372  * their short version value
3373  */
3374  int c;
3375  int option_index;
3376  char *effective_user;
3377  char bin_dir[MAXPGPATH];
3378 
3379  /*
3380  * Ensure that buffering behavior of stdout and stderr matches what it is
3381  * in interactive usage (at least on most platforms). This prevents
3382  * unexpected output ordering when, eg, output is redirected to a file.
3383  * POSIX says we must do this before any other usage of these files.
3384  */
3385  setvbuf(stdout, NULL, PG_IOLBF, 0);
3386  setvbuf(stderr, NULL, _IONBF, 0);
3387 
3388  progname = get_progname(argv[0]);
3389  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
3390 
3391  if (argc > 1)
3392  {
3393  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
3394  {
3395  usage(progname);
3396  exit(0);
3397  }
3398  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
3399  {
3400  puts("initdb (PostgreSQL) " PG_VERSION);
3401  exit(0);
3402  }
3403  }
3404 
3405  /* process command-line options */
3406 
3407  while ((c = getopt_long(argc, argv, "dD:E:kL:nNU:WA:sST:X:", long_options, &option_index)) != -1)
3408  {
3409  switch (c)
3410  {
3411  case 'A':
3413 
3414  /*
3415  * When ident is specified, use peer for local connections.
3416  * Mirrored, when peer is specified, use ident for TCP/IP
3417  * connections.
3418  */
3419  if (strcmp(authmethodhost, "ident") == 0)
3420  authmethodlocal = "peer";
3421  else if (strcmp(authmethodlocal, "peer") == 0)
3422  authmethodhost = "ident";
3423  break;
3424  case 10:
3426  break;
3427  case 11:
3429  break;
3430  case 'D':
3432  break;
3433  case 'E':
3435  break;
3436  case 'W':
3437  pwprompt = true;
3438  break;
3439  case 'U':
3441  break;
3442  case 'd':
3443  debug = true;
3444  printf(_("Running in debug mode.\n"));
3445  break;
3446  case 'n':
3447  noclean = true;
3448  printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
3449  break;
3450  case 'N':
3451  do_sync = false;
3452  break;
3453  case 'S':
3454  sync_only = true;
3455  break;
3456  case 'k':
3457  data_checksums = true;
3458  break;
3459  case 'L':
3461  break;
3462  case 1:
3463  locale = pg_strdup(optarg);
3464  break;
3465  case 2:
3467  break;
3468  case 3:
3470  break;
3471  case 4:
3473  break;
3474  case 5:
3476  break;
3477  case 6:
3479  break;
3480  case 7:
3482  break;
3483  case 8:
3484  locale = "C";
3485  break;
3486  case 9:
3488  break;
3489  case 's':
3490  show_setting = true;
3491  break;
3492  case 'T':
3494  break;
3495  case 'X':
3497  break;
3498  default:
3499  /* getopt_long already emitted a complaint */
3500  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3501  progname);
3502  exit(1);
3503  }
3504  }
3505 
3506 
3507  /*
3508  * Non-option argument specifies data directory as long as it wasn't
3509  * already specified with -D / --pgdata
3510  */
3511  if (optind < argc && strlen(pg_data) == 0)
3512  {
3513  pg_data = pg_strdup(argv[optind]);
3514  optind++;
3515  }
3516 
3517  if (optind < argc)
3518  {
3519  fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
3520  progname, argv[optind]);
3521  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3522  progname);
3523  exit(1);
3524  }
3525 
3526  /* If we only need to fsync, just do it and exit */
3527  if (sync_only)
3528  {
3529  setup_pgdata();
3530 
3531  /* must check that directory is readable */
3532  if (pg_check_dir(pg_data) <= 0)
3533  {
3534  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3535  progname, pg_data, strerror(errno));
3536  exit_nicely();
3537  }
3538 
3539  fsync_pgdata();
3540  return 0;
3541  }
3542 
3543  if (pwprompt && pwfilename)
3544  {
3545  fprintf(stderr, _("%s: password prompt and password file cannot be specified together\n"), progname);
3546  exit(1);
3547  }
3548 
3551 
3554 
3556 
3558 
3559  setup_pgdata();
3560 
3561  setup_bin_paths(argv[0]);
3562 
3563  effective_user = get_id();
3564  if (strlen(username) == 0)
3565  username = effective_user;
3566 
3567  if (strncmp(username, "pg_", 3) == 0)
3568  {
3569  fprintf(stderr, _("%s: superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"\n"), progname, username);
3570  exit(1);
3571  }
3572 
3573  printf(_("The files belonging to this database system will be owned "
3574  "by user \"%s\".\n"
3575  "This user must also own the server process.\n\n"),
3576  effective_user);
3577 
3578  set_info_version();
3579 
3581 
3583 
3585 
3586  printf("\n");
3587 
3588  if (data_checksums)
3589  printf(_("Data page checksums are enabled.\n"));
3590  else
3591  printf(_("Data page checksums are disabled.\n"));
3592 
3593  printf("\n");
3594 
3596 
3597  if (do_sync)
3598  fsync_pgdata();
3599  else
3600  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3601 
3602  if (authwarning != NULL)
3603  fprintf(stderr, "%s", authwarning);
3604 
3605  /* Get directory specification used to start this executable */
3606  strlcpy(bin_dir, argv[0], sizeof(bin_dir));
3607  get_parent_directory(bin_dir);
3608 
3609  printf(_("\nSuccess. You can now start the database server using:\n\n"
3610  " %s%s%spg_ctl%s -D %s%s%s -l logfile start\n\n"),
3611  QUOTE_PATH, bin_dir, (strlen(bin_dir) > 0) ? DIR_SEP : "", QUOTE_PATH,
3613 
3614  return 0;
3615 }
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:2925
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:2836
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:2241
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:3216
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:3107
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:3008
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:2313
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:2697
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:2570
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:2232
void initialize_data_directory(void)
Definition: initdb.c:3232
#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:2409
#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:2788
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:3037
#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:2434
static void make_template0(FILE *cmdfd)
Definition: initdb.c:2251
static int locale_date_order(const char *locale)
Definition: initdb.c:2443
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:2973
#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:2201
int main(int argc, char *argv[])
Definition: initdb.c:3338
static bool output_failed
Definition: initdb.c:168
static void setlocales(void)
Definition: initdb.c:2606
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:2506
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:2007
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:2289
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:2657
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:2729
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:2709
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:2748
#define _(x)
Definition: elog.c:83
const char * langname
Definition: initdb.c:850
static void trapsig(int signum)
Definition: initdb.c:2398
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:2174
#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