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