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