PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
initdb.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * initdb --- initialize a PostgreSQL installation
4  *
5  * initdb creates (initializes) a PostgreSQL database cluster (site,
6  * instance, installation, whatever). A database cluster is a
7  * collection of PostgreSQL databases all managed by the same server.
8  *
9  * To create the database cluster, we create the directory that contains
10  * all its data, create the files that hold the global tables, create
11  * a few other control files for it, and create three databases: the
12  * template databases "template0" and "template1", and a default user
13  * database "postgres".
14  *
15  * The template databases are ordinary PostgreSQL databases. template0
16  * is never supposed to change after initdb, whereas template1 can be
17  * changed to add site-local standard data. Either one can be copied
18  * to produce a new database.
19  *
20  * For largely-historical reasons, the template1 database is the one built
21  * by the basic bootstrap process. After it is complete, template0 and
22  * the default database, postgres, are made just by copying template1.
23  *
24  * To create template1, we run the postgres (backend) program in bootstrap
25  * mode and feed it data from the postgres.bki library file. After this
26  * initial bootstrap phase, some additional stuff is created by normal
27  * SQL commands fed to a standalone backend. Some of those commands are
28  * just embedded into this program (yeah, it's ugly), but larger chunks
29  * are taken from script files.
30  *
31  *
32  * Note:
33  * The program has some memory leakage - it isn't worth cleaning it up.
34  *
35  * This is a C implementation of the previous shell script for setting up a
36  * PostgreSQL cluster location, and should be highly compatible with it.
37  * author of C translation: Andrew Dunstan mailto:andrew@dunslane.net
38  *
39  * This code is released under the terms of the PostgreSQL License.
40  *
41  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
42  * Portions Copyright (c) 1994, Regents of the University of California
43  *
44  * src/bin/initdb/initdb.c
45  *
46  *-------------------------------------------------------------------------
47  */
48 
49 #include "postgres_fe.h"
50 
51 #include <dirent.h>
52 #include <fcntl.h>
53 #include <sys/stat.h>
54 #include <unistd.h>
55 #include <locale.h>
56 #include <signal.h>
57 #include <time.h>
58 
59 #ifdef HAVE_SHM_OPEN
60 #include "sys/mman.h"
61 #endif
62 
63 #include "catalog/catalog.h"
65 #include "common/username.h"
66 #include "mb/pg_wchar.h"
67 #include "getaddrinfo.h"
68 #include "getopt_long.h"
69 #include "miscadmin.h"
70 
71 
72 /* Define PG_FLUSH_DATA_WORKS if we have an implementation for pg_flush_data */
73 #if defined(HAVE_SYNC_FILE_RANGE)
74 #define PG_FLUSH_DATA_WORKS 1
75 #elif defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
76 #define PG_FLUSH_DATA_WORKS 1
77 #endif
78 
79 /* Ideally this would be in a .h file, but it hardly seems worth the trouble */
80 extern const char *select_default_timezone(const char *share_path);
81 
82 static const char *const auth_methods_host[] = {
83  "trust", "reject", "md5", "password", "ident", "radius",
84 #ifdef ENABLE_GSS
85  "gss",
86 #endif
87 #ifdef ENABLE_SSPI
88  "sspi",
89 #endif
90 #ifdef USE_PAM
91  "pam", "pam ",
92 #endif
93 #ifdef USE_LDAP
94  "ldap",
95 #endif
96 #ifdef USE_SSL
97  "cert",
98 #endif
99  NULL
100 };
101 static const char *const auth_methods_local[] = {
102  "trust", "reject", "md5", "password", "peer", "radius",
103 #ifdef USE_PAM
104  "pam", "pam ",
105 #endif
106 #ifdef USE_LDAP
107  "ldap",
108 #endif
109  NULL
110 };
111 
112 /*
113  * these values are passed in by makefile defines
114  */
115 static char *share_path = NULL;
116 
117 /* values to be obtained from arguments */
118 static char *pg_data = "";
119 static char *encoding = "";
120 static char *locale = "";
121 static char *lc_collate = "";
122 static char *lc_ctype = "";
123 static char *lc_monetary = "";
124 static char *lc_numeric = "";
125 static char *lc_time = "";
126 static char *lc_messages = "";
127 static const char *default_text_search_config = "";
128 static char *username = "";
129 static bool pwprompt = false;
130 static char *pwfilename = NULL;
131 static const char *authmethodhost = "";
132 static const char *authmethodlocal = "";
133 static bool debug = false;
134 static bool noclean = false;
135 static bool do_sync = true;
136 static bool sync_only = false;
137 static bool show_setting = false;
138 static bool data_checksums = false;
139 static char *xlog_dir = "";
140 
141 
142 /* internal vars */
143 static const char *progname;
144 static char *encodingid = "0";
145 static char *bki_file;
146 static char *desc_file;
147 static char *shdesc_file;
148 static char *hba_file;
149 static char *ident_file;
150 static char *conf_file;
151 static char *conversion_file;
152 static char *dictionary_file;
153 static char *info_schema_file;
154 static char *features_file;
155 static char *system_views_file;
156 static bool made_new_pgdata = false;
157 static bool found_existing_pgdata = false;
158 static bool made_new_xlogdir = false;
159 static bool found_existing_xlogdir = false;
160 static char infoversion[100];
161 static bool caught_signal = false;
162 static bool output_failed = false;
163 static int output_errno = 0;
164 static char *pgdata_native;
165 
166 /* defaults */
167 static int n_connections = 10;
168 static int n_buffers = 50;
170 
171 /*
172  * Warning messages for authentication methods
173  */
174 #define AUTHTRUST_WARNING \
175 "# CAUTION: Configuring the system for local \"trust\" authentication\n" \
176 "# allows any local user to connect as any PostgreSQL user, including\n" \
177 "# the database superuser. If you do not trust all your local users,\n" \
178 "# use another authentication method.\n"
179 static char *authwarning = NULL;
180 
181 /*
182  * Centralized knowledge of switches to pass to backend
183  *
184  * Note: we run the backend with -F (fsync disabled) and then do a single
185  * pass of fsync'ing at the end. This is faster than fsync'ing each step.
186  *
187  * Note: in the shell-script version, we also passed PGDATA as a -D switch,
188  * but here it is more convenient to pass it as an environment variable
189  * (no quoting to worry about).
190  */
191 static const char *boot_options = "-F";
192 static const char *backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true";
193 
194 static const char *const subdirs[] = {
195  "global",
196  "pg_xlog/archive_status",
197  "pg_clog",
198  "pg_commit_ts",
199  "pg_dynshmem",
200  "pg_notify",
201  "pg_serial",
202  "pg_snapshots",
203  "pg_subtrans",
204  "pg_twophase",
205  "pg_multixact",
206  "pg_multixact/members",
207  "pg_multixact/offsets",
208  "base",
209  "base/1",
210  "pg_replslot",
211  "pg_tblspc",
212  "pg_stat",
213  "pg_stat_tmp",
214  "pg_logical",
215  "pg_logical/snapshots",
216  "pg_logical/mappings"
217 };
218 
219 
220 /* path to 'initdb' binary directory */
221 static char bin_path[MAXPGPATH];
222 static char backend_exec[MAXPGPATH];
223 
224 static char **replace_token(char **lines,
225  const char *token, const char *replacement);
226 
227 #ifndef HAVE_UNIX_SOCKETS
228 static char **filter_lines_with_token(char **lines, const char *token);
229 #endif
230 static char **readfile(const char *path);
231 static void writefile(char *path, char **lines);
232 static void walkdir(const char *path,
233  void (*action) (const char *fname, bool isdir),
234  bool process_symlinks);
235 #ifdef PG_FLUSH_DATA_WORKS
236 static void pre_sync_fname(const char *fname, bool isdir);
237 #endif
238 static void fsync_fname_ext(const char *fname, bool isdir);
239 static FILE *popen_check(const char *command, const char *mode);
240 static void exit_nicely(void);
241 static char *get_id(void);
242 static char *get_encoding_id(char *encoding_name);
243 static void set_input(char **dest, char *filename);
244 static void check_input(char *path);
245 static void write_version_file(char *extrapath);
246 static void set_null_conf(void);
247 static void test_config_settings(void);
248 static void setup_config(void);
249 static void bootstrap_template1(void);
250 static void setup_auth(FILE *cmdfd);
251 static void get_set_pwd(FILE *cmdfd);
252 static void setup_depend(FILE *cmdfd);
253 static void setup_sysviews(FILE *cmdfd);
254 static void setup_description(FILE *cmdfd);
255 static void setup_collation(FILE *cmdfd);
256 static void setup_conversion(FILE *cmdfd);
257 static void setup_dictionary(FILE *cmdfd);
258 static void setup_privileges(FILE *cmdfd);
259 static void set_info_version(void);
260 static void setup_schema(FILE *cmdfd);
261 static void load_plpgsql(FILE *cmdfd);
262 static void vacuum_db(FILE *cmdfd);
263 static void make_template0(FILE *cmdfd);
264 static void make_postgres(FILE *cmdfd);
265 static void fsync_pgdata(void);
266 static void trapsig(int signum);
267 static void check_ok(void);
268 static char *escape_quotes(const char *src);
269 static int locale_date_order(const char *locale);
270 static void check_locale_name(int category, const char *locale,
271  char **canonname);
272 static bool check_locale_encoding(const char *locale, int encoding);
273 static void setlocales(void);
274 static void usage(const char *progname);
275 void setup_pgdata(void);
276 void setup_bin_paths(const char *argv0);
277 void setup_data_file_paths(void);
278 void setup_locale_encoding(void);
279 void setup_signals(void);
280 void setup_text_search(void);
281 void create_data_directory(void);
282 void create_xlog_or_symlink(void);
283 void warn_on_mount_point(int error);
284 void initialize_data_directory(void);
285 
286 /*
287  * macros for running pipes to postgres
288  */
289 #define PG_CMD_DECL char cmd[MAXPGPATH]; FILE *cmdfd
290 
291 #define PG_CMD_OPEN \
292 do { \
293  cmdfd = popen_check(cmd, "w"); \
294  if (cmdfd == NULL) \
295  exit_nicely(); /* message already printed by popen_check */ \
296 } while (0)
297 
298 #define PG_CMD_CLOSE \
299 do { \
300  if (pclose_check(cmdfd)) \
301  exit_nicely(); /* message already printed by pclose_check */ \
302 } while (0)
303 
304 #define PG_CMD_PUTS(line) \
305 do { \
306  if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
307  output_failed = true, output_errno = errno; \
308 } while (0)
309 
310 #define PG_CMD_PRINTF1(fmt, arg1) \
311 do { \
312  if (fprintf(cmdfd, fmt, arg1) < 0 || fflush(cmdfd) < 0) \
313  output_failed = true, output_errno = errno; \
314 } while (0)
315 
316 #define PG_CMD_PRINTF2(fmt, arg1, arg2) \
317 do { \
318  if (fprintf(cmdfd, fmt, arg1, arg2) < 0 || fflush(cmdfd) < 0) \
319  output_failed = true, output_errno = errno; \
320 } while (0)
321 
322 #define PG_CMD_PRINTF3(fmt, arg1, arg2, arg3) \
323 do { \
324  if (fprintf(cmdfd, fmt, arg1, arg2, arg3) < 0 || fflush(cmdfd) < 0) \
325  output_failed = true, output_errno = errno; \
326 } while (0)
327 
328 #ifndef WIN32
329 #define QUOTE_PATH ""
330 #define DIR_SEP "/"
331 #else
332 #define QUOTE_PATH "\""
333 #define DIR_SEP "\\"
334 #endif
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  snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1290 
1291  writefile(path, conflines);
1292  if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1293  {
1294  fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1295  progname, path, strerror(errno));
1296  exit_nicely();
1297  }
1298 
1299  /*
1300  * create the automatic configuration file to store the configuration
1301  * parameters set by ALTER SYSTEM command. The parameters present in this
1302  * file will override the value of parameters that exists before parse of
1303  * this file.
1304  */
1305  autoconflines[0] = pg_strdup("# Do not edit this file manually!\n");
1306  autoconflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
1307  autoconflines[2] = NULL;
1308 
1309  sprintf(path, "%s/postgresql.auto.conf", pg_data);
1310 
1311  writefile(path, autoconflines);
1312  if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1313  {
1314  fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1315  progname, path, strerror(errno));
1316  exit_nicely();
1317  }
1318 
1319  free(conflines);
1320 
1321 
1322  /* pg_hba.conf */
1323 
1324  conflines = readfile(hba_file);
1325 
1326 #ifndef HAVE_UNIX_SOCKETS
1327  conflines = filter_lines_with_token(conflines, "@remove-line-for-nolocal@");
1328 #else
1329  conflines = replace_token(conflines, "@remove-line-for-nolocal@", "");
1330 #endif
1331 
1332 #ifdef HAVE_IPV6
1333 
1334  /*
1335  * Probe to see if there is really any platform support for IPv6, and
1336  * comment out the relevant pg_hba line if not. This avoids runtime
1337  * warnings if getaddrinfo doesn't actually cope with IPv6. Particularly
1338  * useful on Windows, where executables built on a machine with IPv6 may
1339  * have to run on a machine without.
1340  */
1341  {
1342  struct addrinfo *gai_result;
1343  struct addrinfo hints;
1344  int err = 0;
1345 
1346 #ifdef WIN32
1347  /* need to call WSAStartup before calling getaddrinfo */
1348  WSADATA wsaData;
1349 
1350  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
1351 #endif
1352 
1353  /* for best results, this code should match parse_hba() */
1354  hints.ai_flags = AI_NUMERICHOST;
1355  hints.ai_family = AF_UNSPEC;
1356  hints.ai_socktype = 0;
1357  hints.ai_protocol = 0;
1358  hints.ai_addrlen = 0;
1359  hints.ai_canonname = NULL;
1360  hints.ai_addr = NULL;
1361  hints.ai_next = NULL;
1362 
1363  if (err != 0 ||
1364  getaddrinfo("::1", NULL, &hints, &gai_result) != 0)
1365  conflines = replace_token(conflines,
1366  "host all all ::1",
1367  "#host all all ::1");
1368  }
1369 #else /* !HAVE_IPV6 */
1370  /* If we didn't compile IPV6 support at all, always comment it out */
1371  conflines = replace_token(conflines,
1372  "host all all ::1",
1373  "#host all all ::1");
1374 #endif /* HAVE_IPV6 */
1375 
1376  /* Replace default authentication methods */
1377  conflines = replace_token(conflines,
1378  "@authmethodhost@",
1379  authmethodhost);
1380  conflines = replace_token(conflines,
1381  "@authmethodlocal@",
1382  authmethodlocal);
1383 
1384  conflines = replace_token(conflines,
1385  "@authcomment@",
1386  (strcmp(authmethodlocal, "trust") == 0 || strcmp(authmethodhost, "trust") == 0) ? AUTHTRUST_WARNING : "");
1387 
1388  /* Replace username for replication */
1389  conflines = replace_token(conflines,
1390  "@default_username@",
1391  username);
1392 
1393  snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1394 
1395  writefile(path, conflines);
1396  if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1397  {
1398  fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1399  progname, path, strerror(errno));
1400  exit_nicely();
1401  }
1402 
1403  free(conflines);
1404 
1405  /* pg_ident.conf */
1406 
1407  conflines = readfile(ident_file);
1408 
1409  snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1410 
1411  writefile(path, conflines);
1412  if (chmod(path, S_IRUSR | S_IWUSR) != 0)
1413  {
1414  fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
1415  progname, path, strerror(errno));
1416  exit_nicely();
1417  }
1418 
1419  free(conflines);
1420 
1421  check_ok();
1422 }
1423 
1424 
1425 /*
1426  * run the BKI script in bootstrap mode to create template1
1427  */
1428 static void
1430 {
1431  PG_CMD_DECL;
1432  char **line;
1433  char *talkargs = "";
1434  char **bki_lines;
1435  char headerline[MAXPGPATH];
1436  char buf[64];
1437 
1438  printf(_("running bootstrap script ... "));
1439  fflush(stdout);
1440 
1441  if (debug)
1442  talkargs = "-d 5";
1443 
1444  bki_lines = readfile(bki_file);
1445 
1446  /* Check that bki file appears to be of the right version */
1447 
1448  snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1449  PG_MAJORVERSION);
1450 
1451  if (strcmp(headerline, *bki_lines) != 0)
1452  {
1453  fprintf(stderr,
1454  _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
1455  "Check your installation or specify the correct path "
1456  "using the option -L.\n"),
1457  progname, bki_file, PG_VERSION);
1458  exit_nicely();
1459  }
1460 
1461  /* Substitute for various symbols used in the BKI file */
1462 
1463  sprintf(buf, "%d", NAMEDATALEN);
1464  bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
1465 
1466  sprintf(buf, "%d", (int) sizeof(Pointer));
1467  bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
1468 
1469  bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
1470  (sizeof(Pointer) == 4) ? "i" : "d");
1471 
1472  bki_lines = replace_token(bki_lines, "FLOAT4PASSBYVAL",
1473  FLOAT4PASSBYVAL ? "true" : "false");
1474 
1475  bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
1476  FLOAT8PASSBYVAL ? "true" : "false");
1477 
1478  bki_lines = replace_token(bki_lines, "POSTGRES", escape_quotes(username));
1479 
1480  bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
1481 
1482  bki_lines = replace_token(bki_lines, "LC_COLLATE", escape_quotes(lc_collate));
1483 
1484  bki_lines = replace_token(bki_lines, "LC_CTYPE", escape_quotes(lc_ctype));
1485 
1486  /*
1487  * Pass correct LC_xxx environment to bootstrap.
1488  *
1489  * The shell script arranged to restore the LC settings afterwards, but
1490  * there doesn't seem to be any compelling reason to do that.
1491  */
1492  snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1493  putenv(pg_strdup(cmd));
1494 
1495  snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1496  putenv(pg_strdup(cmd));
1497 
1498  unsetenv("LC_ALL");
1499 
1500  /* Also ensure backend isn't confused by this environment var: */
1501  unsetenv("PGCLIENTENCODING");
1502 
1503  snprintf(cmd, sizeof(cmd),
1504  "\"%s\" --boot -x1 %s %s %s",
1505  backend_exec,
1506  data_checksums ? "-k" : "",
1507  boot_options, talkargs);
1508 
1509  PG_CMD_OPEN;
1510 
1511  for (line = bki_lines; *line != NULL; line++)
1512  {
1513  PG_CMD_PUTS(*line);
1514  free(*line);
1515  }
1516 
1517  PG_CMD_CLOSE;
1518 
1519  free(bki_lines);
1520 
1521  check_ok();
1522 }
1523 
1524 /*
1525  * set up the shadow password table
1526  */
1527 static void
1528 setup_auth(FILE *cmdfd)
1529 {
1530  const char *const * line;
1531  static const char *const pg_authid_setup[] = {
1532  /*
1533  * The authid table shouldn't be readable except through views, to
1534  * ensure passwords are not publicly visible.
1535  */
1536  "REVOKE ALL on pg_authid FROM public;\n\n",
1537  NULL
1538  };
1539 
1540  for (line = pg_authid_setup; *line != NULL; line++)
1541  PG_CMD_PUTS(*line);
1542 }
1543 
1544 /*
1545  * get the superuser password if required, and call postgres to set it
1546  */
1547 static void
1548 get_set_pwd(FILE *cmdfd)
1549 {
1550  char *pwd1,
1551  *pwd2;
1552 
1553  if (pwprompt)
1554  {
1555  /*
1556  * Read password from terminal
1557  */
1558  pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
1559  pwd2 = simple_prompt("Enter it again: ", 100, false);
1560  if (strcmp(pwd1, pwd2) != 0)
1561  {
1562  fprintf(stderr, _("Passwords didn't match.\n"));
1563  exit_nicely();
1564  }
1565  free(pwd2);
1566  }
1567  else
1568  {
1569  /*
1570  * Read password from file
1571  *
1572  * Ideally this should insist that the file not be world-readable.
1573  * However, this option is mainly intended for use on Windows where
1574  * file permissions may not exist at all, so we'll skip the paranoia
1575  * for now.
1576  */
1577  FILE *pwf = fopen(pwfilename, "r");
1578  char pwdbuf[MAXPGPATH];
1579  int i;
1580 
1581  if (!pwf)
1582  {
1583  fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1584  progname, pwfilename, strerror(errno));
1585  exit_nicely();
1586  }
1587  if (!fgets(pwdbuf, sizeof(pwdbuf), pwf))
1588  {
1589  if (ferror(pwf))
1590  fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
1591  progname, pwfilename, strerror(errno));
1592  else
1593  fprintf(stderr, _("%s: password file \"%s\" is empty\n"),
1594  progname, pwfilename);
1595  exit_nicely();
1596  }
1597  fclose(pwf);
1598 
1599  i = strlen(pwdbuf);
1600  while (i > 0 && (pwdbuf[i - 1] == '\r' || pwdbuf[i - 1] == '\n'))
1601  pwdbuf[--i] = '\0';
1602 
1603  pwd1 = pg_strdup(pwdbuf);
1604 
1605  }
1606 
1607  PG_CMD_PRINTF2("ALTER USER \"%s\" WITH PASSWORD E'%s';\n\n",
1608  username, escape_quotes(pwd1));
1609 
1610  free(pwd1);
1611 }
1612 
1613 /*
1614  * set up pg_depend
1615  */
1616 static void
1617 setup_depend(FILE *cmdfd)
1618 {
1619  const char *const * line;
1620  static const char *const pg_depend_setup[] = {
1621  /*
1622  * Make PIN entries in pg_depend for all objects made so far in the
1623  * tables that the dependency code handles. This is overkill (the
1624  * system doesn't really depend on having every last weird datatype,
1625  * for instance) but generating only the minimum required set of
1626  * dependencies seems hard.
1627  *
1628  * Note that we deliberately do not pin the system views, which
1629  * haven't been created yet. Also, no conversions, databases, or
1630  * tablespaces are pinned.
1631  *
1632  * First delete any already-made entries; PINs override all else, and
1633  * must be the only entries for their objects.
1634  */
1635  "DELETE FROM pg_depend;\n\n",
1636  "VACUUM pg_depend;\n\n",
1637  "DELETE FROM pg_shdepend;\n\n",
1638  "VACUUM pg_shdepend;\n\n",
1639 
1640  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1641  " FROM pg_class;\n\n",
1642  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1643  " FROM pg_proc;\n\n",
1644  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1645  " FROM pg_type;\n\n",
1646  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1647  " FROM pg_cast;\n\n",
1648  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1649  " FROM pg_constraint;\n\n",
1650  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1651  " FROM pg_attrdef;\n\n",
1652  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1653  " FROM pg_language;\n\n",
1654  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1655  " FROM pg_operator;\n\n",
1656  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1657  " FROM pg_opclass;\n\n",
1658  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1659  " FROM pg_opfamily;\n\n",
1660  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1661  " FROM pg_amop;\n\n",
1662  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1663  " FROM pg_amproc;\n\n",
1664  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1665  " FROM pg_rewrite;\n\n",
1666  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1667  " FROM pg_trigger;\n\n",
1668 
1669  /*
1670  * restriction here to avoid pinning the public namespace
1671  */
1672  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1673  " FROM pg_namespace "
1674  " WHERE nspname LIKE 'pg%';\n\n",
1675 
1676  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1677  " FROM pg_ts_parser;\n\n",
1678  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1679  " FROM pg_ts_dict;\n\n",
1680  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1681  " FROM pg_ts_template;\n\n",
1682  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1683  " FROM pg_ts_config;\n\n",
1684  "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1685  " FROM pg_collation;\n\n",
1686  "INSERT INTO pg_shdepend SELECT 0,0,0,0, tableoid,oid, 'p' "
1687  " FROM pg_authid;\n\n",
1688  NULL
1689  };
1690 
1691  for (line = pg_depend_setup; *line != NULL; line++)
1692  PG_CMD_PUTS(*line);
1693 }
1694 
1695 /*
1696  * set up system views
1697  */
1698 static void
1699 setup_sysviews(FILE *cmdfd)
1700 {
1701  char **line;
1702  char **sysviews_setup;
1703 
1704  sysviews_setup = readfile(system_views_file);
1705 
1706  for (line = sysviews_setup; *line != NULL; line++)
1707  {
1708  PG_CMD_PUTS(*line);
1709  free(*line);
1710  }
1711 
1712  free(sysviews_setup);
1713 }
1714 
1715 /*
1716  * load description data
1717  */
1718 static void
1719 setup_description(FILE *cmdfd)
1720 {
1721  PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_description ( "
1722  " objoid oid, "
1723  " classname name, "
1724  " objsubid int4, "
1725  " description text) WITHOUT OIDS;\n\n");
1726 
1727  PG_CMD_PRINTF1("COPY tmp_pg_description FROM E'%s';\n\n",
1729 
1730  PG_CMD_PUTS("INSERT INTO pg_description "
1731  " SELECT t.objoid, c.oid, t.objsubid, t.description "
1732  " FROM tmp_pg_description t, pg_class c "
1733  " WHERE c.relname = t.classname;\n\n");
1734 
1735  PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_shdescription ( "
1736  " objoid oid, "
1737  " classname name, "
1738  " description text) WITHOUT OIDS;\n\n");
1739 
1740  PG_CMD_PRINTF1("COPY tmp_pg_shdescription FROM E'%s';\n\n",
1742 
1743  PG_CMD_PUTS("INSERT INTO pg_shdescription "
1744  " SELECT t.objoid, c.oid, t.description "
1745  " FROM tmp_pg_shdescription t, pg_class c "
1746  " WHERE c.relname = t.classname;\n\n");
1747 
1748  /* Create default descriptions for operator implementation functions */
1749  PG_CMD_PUTS("WITH funcdescs AS ( "
1750  "SELECT p.oid as p_oid, oprname, "
1751  "coalesce(obj_description(o.oid, 'pg_operator'),'') as opdesc "
1752  "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
1753  "INSERT INTO pg_description "
1754  " SELECT p_oid, 'pg_proc'::regclass, 0, "
1755  " 'implementation of ' || oprname || ' operator' "
1756  " FROM funcdescs "
1757  " WHERE opdesc NOT LIKE 'deprecated%' AND "
1758  " NOT EXISTS (SELECT 1 FROM pg_description "
1759  " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass);\n\n");
1760 
1761  /*
1762  * Even though the tables are temp, drop them explicitly so they don't get
1763  * copied into template0/postgres databases.
1764  */
1765  PG_CMD_PUTS("DROP TABLE tmp_pg_description;\n\n");
1766  PG_CMD_PUTS("DROP TABLE tmp_pg_shdescription;\n\n");
1767 }
1768 
1769 #ifdef HAVE_LOCALE_T
1770 /*
1771  * "Normalize" a locale name, stripping off encoding tags such as
1772  * ".utf8" (e.g., "en_US.utf8" -> "en_US", but "br_FR.iso885915@euro"
1773  * -> "br_FR@euro"). Return true if a new, different name was
1774  * generated.
1775  */
1776 static bool
1777 normalize_locale_name(char *new, const char *old)
1778 {
1779  char *n = new;
1780  const char *o = old;
1781  bool changed = false;
1782 
1783  while (*o)
1784  {
1785  if (*o == '.')
1786  {
1787  /* skip over encoding tag such as ".utf8" or ".UTF-8" */
1788  o++;
1789  while ((*o >= 'A' && *o <= 'Z')
1790  || (*o >= 'a' && *o <= 'z')
1791  || (*o >= '0' && *o <= '9')
1792  || (*o == '-'))
1793  o++;
1794  changed = true;
1795  }
1796  else
1797  *n++ = *o++;
1798  }
1799  *n = '\0';
1800 
1801  return changed;
1802 }
1803 #endif /* HAVE_LOCALE_T */
1804 
1805 /*
1806  * populate pg_collation
1807  */
1808 static void
1809 setup_collation(FILE *cmdfd)
1810 {
1811 #if defined(HAVE_LOCALE_T) && !defined(WIN32)
1812  int i;
1813  FILE *locale_a_handle;
1814  char localebuf[NAMEDATALEN]; /* we assume ASCII so this is fine */
1815  int count = 0;
1816 
1817  locale_a_handle = popen_check("locale -a", "r");
1818  if (!locale_a_handle)
1819  return; /* complaint already printed */
1820 
1821  PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_collation ( "
1822  " collname name, "
1823  " locale name, "
1824  " encoding int) WITHOUT OIDS;\n\n");
1825 
1826  while (fgets(localebuf, sizeof(localebuf), locale_a_handle))
1827  {
1828  size_t len;
1829  int enc;
1830  bool skip;
1831  char *quoted_locale;
1832  char alias[NAMEDATALEN];
1833 
1834  len = strlen(localebuf);
1835 
1836  if (len == 0 || localebuf[len - 1] != '\n')
1837  {
1838  if (debug)
1839  fprintf(stderr, _("%s: locale name too long, skipped: \"%s\"\n"),
1840  progname, localebuf);
1841  continue;
1842  }
1843  localebuf[len - 1] = '\0';
1844 
1845  /*
1846  * Some systems have locale names that don't consist entirely of ASCII
1847  * letters (such as "bokm&aring;l" or "fran&ccedil;ais"). This is
1848  * pretty silly, since we need the locale itself to interpret the
1849  * non-ASCII characters. We can't do much with those, so we filter
1850  * them out.
1851  */
1852  skip = false;
1853  for (i = 0; i < len; i++)
1854  {
1855  if (IS_HIGHBIT_SET(localebuf[i]))
1856  {
1857  skip = true;
1858  break;
1859  }
1860  }
1861  if (skip)
1862  {
1863  if (debug)
1864  fprintf(stderr, _("%s: locale name has non-ASCII characters, skipped: \"%s\"\n"),
1865  progname, localebuf);
1866  continue;
1867  }
1868 
1869  enc = pg_get_encoding_from_locale(localebuf, debug);
1870  if (enc < 0)
1871  {
1872  /* error message printed by pg_get_encoding_from_locale() */
1873  continue;
1874  }
1875  if (!PG_VALID_BE_ENCODING(enc))
1876  continue; /* ignore locales for client-only encodings */
1877  if (enc == PG_SQL_ASCII)
1878  continue; /* C/POSIX are already in the catalog */
1879 
1880  count++;
1881 
1882  quoted_locale = escape_quotes(localebuf);
1883 
1884  PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n\n",
1885  quoted_locale, quoted_locale, enc);
1886 
1887  /*
1888  * Generate aliases such as "en_US" in addition to "en_US.utf8" for
1889  * ease of use. Note that collation names are unique per encoding
1890  * only, so this doesn't clash with "en_US" for LATIN1, say.
1891  */
1892  if (normalize_locale_name(alias, localebuf))
1893  {
1894  char *quoted_alias = escape_quotes(alias);
1895 
1896  PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n\n",
1897  quoted_alias, quoted_locale, enc);
1898  free(quoted_alias);
1899  }
1900  free(quoted_locale);
1901  }
1902 
1903  /* Add an SQL-standard name */
1904  PG_CMD_PRINTF1("INSERT INTO tmp_pg_collation VALUES ('ucs_basic', 'C', %d);\n\n", PG_UTF8);
1905 
1906  /*
1907  * When copying collations to the final location, eliminate aliases that
1908  * conflict with an existing locale name for the same encoding. For
1909  * example, "br_FR.iso88591" is normalized to "br_FR", both for encoding
1910  * LATIN1. But the unnormalized locale "br_FR" already exists for LATIN1.
1911  * Prefer the alias that matches the OS locale name, else the first locale
1912  * name by sort order (arbitrary choice to be deterministic).
1913  *
1914  * Also, eliminate any aliases that conflict with pg_collation's
1915  * hard-wired entries for "C" etc.
1916  */
1917  PG_CMD_PUTS("INSERT INTO pg_collation (collname, collnamespace, collowner, collencoding, collcollate, collctype) "
1918  " SELECT DISTINCT ON (collname, encoding)"
1919  " collname, "
1920  " (SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog') AS collnamespace, "
1921  " (SELECT relowner FROM pg_class WHERE relname = 'pg_collation') AS collowner, "
1922  " encoding, locale, locale "
1923  " FROM tmp_pg_collation"
1924  " WHERE NOT EXISTS (SELECT 1 FROM pg_collation WHERE collname = tmp_pg_collation.collname)"
1925  " ORDER BY collname, encoding, (collname = locale) DESC, locale;\n\n");
1926 
1927  /*
1928  * Even though the table is temp, drop it explicitly so it doesn't get
1929  * copied into template0/postgres databases.
1930  */
1931  PG_CMD_PUTS("DROP TABLE tmp_pg_collation;\n\n");
1932 
1933  pclose(locale_a_handle);
1934 
1935  if (count == 0 && !debug)
1936  {
1937  printf(_("No usable system locales were found.\n"));
1938  printf(_("Use the option \"--debug\" to see details.\n"));
1939  }
1940 #endif /* not HAVE_LOCALE_T && not WIN32 */
1941 }
1942 
1943 /*
1944  * load conversion functions
1945  */
1946 static void
1947 setup_conversion(FILE *cmdfd)
1948 {
1949  char **line;
1950  char **conv_lines;
1951 
1952  conv_lines = readfile(conversion_file);
1953  for (line = conv_lines; *line != NULL; line++)
1954  {
1955  if (strstr(*line, "DROP CONVERSION") != *line)
1956  PG_CMD_PUTS(*line);
1957  free(*line);
1958  }
1959 
1960  free(conv_lines);
1961 }
1962 
1963 /*
1964  * load extra dictionaries (Snowball stemmers)
1965  */
1966 static void
1967 setup_dictionary(FILE *cmdfd)
1968 {
1969  char **line;
1970  char **conv_lines;
1971 
1972  conv_lines = readfile(dictionary_file);
1973  for (line = conv_lines; *line != NULL; line++)
1974  {
1975  PG_CMD_PUTS(*line);
1976  free(*line);
1977  }
1978 
1979  free(conv_lines);
1980 }
1981 
1982 /*
1983  * Set up privileges
1984  *
1985  * We mark most system catalogs as world-readable. We don't currently have
1986  * to touch functions, languages, or databases, because their default
1987  * permissions are OK.
1988  *
1989  * Some objects may require different permissions by default, so we
1990  * make sure we don't overwrite privilege sets that have already been
1991  * set (NOT NULL).
1992  */
1993 static void
1994 setup_privileges(FILE *cmdfd)
1995 {
1996  char **line;
1997  char **priv_lines;
1998  static char *privileges_setup[] = {
1999  "UPDATE pg_class "
2000  " SET relacl = E'{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
2001  " WHERE relkind IN ('r', 'v', 'm', 'S') AND relacl IS NULL;\n\n",
2002  "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n\n",
2003  "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n\n",
2004  "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n",
2005  NULL
2006  };
2007 
2008  priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
2010  for (line = priv_lines; *line != NULL; line++)
2011  PG_CMD_PUTS(*line);
2012 }
2013 
2014 /*
2015  * extract the strange version of version required for information schema
2016  * (09.08.0007abc)
2017  */
2018 static void
2020 {
2021  char *letterversion;
2022  long major = 0,
2023  minor = 0,
2024  micro = 0;
2025  char *endptr;
2026  char *vstr = pg_strdup(PG_VERSION);
2027  char *ptr;
2028 
2029  ptr = vstr + (strlen(vstr) - 1);
2030  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
2031  ptr--;
2032  letterversion = ptr + 1;
2033  major = strtol(vstr, &endptr, 10);
2034  if (*endptr)
2035  minor = strtol(endptr + 1, &endptr, 10);
2036  if (*endptr)
2037  micro = strtol(endptr + 1, &endptr, 10);
2038  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
2039  major, minor, micro, letterversion);
2040 }
2041 
2042 /*
2043  * load info schema and populate from features file
2044  */
2045 static void
2046 setup_schema(FILE *cmdfd)
2047 {
2048  char **line;
2049  char **lines;
2050 
2051  lines = readfile(info_schema_file);
2052 
2053  for (line = lines; *line != NULL; line++)
2054  {
2055  PG_CMD_PUTS(*line);
2056  free(*line);
2057  }
2058 
2059  free(lines);
2060 
2061  PG_CMD_PRINTF1("UPDATE information_schema.sql_implementation_info "
2062  " SET character_value = '%s' "
2063  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
2064  infoversion);
2065 
2066  PG_CMD_PRINTF1("COPY information_schema.sql_features "
2067  " (feature_id, feature_name, sub_feature_id, "
2068  " sub_feature_name, is_supported, comments) "
2069  " FROM E'%s';\n\n",
2071 }
2072 
2073 /*
2074  * load PL/pgsql server-side language
2075  */
2076 static void
2077 load_plpgsql(FILE *cmdfd)
2078 {
2079  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
2080 }
2081 
2082 /*
2083  * clean everything up in template1
2084  */
2085 static void
2086 vacuum_db(FILE *cmdfd)
2087 {
2088  /* Run analyze before VACUUM so the statistics are frozen. */
2089  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
2090 }
2091 
2092 /*
2093  * copy template1 to template0
2094  */
2095 static void
2096 make_template0(FILE *cmdfd)
2097 {
2098  const char *const * line;
2099  static const char *const template0_setup[] = {
2100  "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false;\n\n",
2101 
2102  /*
2103  * We use the OID of template0 to determine lastsysoid
2104  */
2105  "UPDATE pg_database SET datlastsysoid = "
2106  " (SELECT oid FROM pg_database "
2107  " WHERE datname = 'template0');\n\n",
2108 
2109  /*
2110  * Explicitly revoke public create-schema and create-temp-table
2111  * privileges in template1 and template0; else the latter would be on
2112  * by default
2113  */
2114  "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n",
2115  "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n",
2116 
2117  "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n",
2118 
2119  /*
2120  * Finally vacuum to clean up dead rows in pg_database
2121  */
2122  "VACUUM pg_database;\n\n",
2123  NULL
2124  };
2125 
2126  for (line = template0_setup; *line; line++)
2127  PG_CMD_PUTS(*line);
2128 }
2129 
2130 /*
2131  * copy template1 to postgres
2132  */
2133 static void
2134 make_postgres(FILE *cmdfd)
2135 {
2136  const char *const * line;
2137  static const char *const postgres_setup[] = {
2138  "CREATE DATABASE postgres;\n\n",
2139  "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",
2140  NULL
2141  };
2142 
2143  for (line = postgres_setup; *line; line++)
2144  PG_CMD_PUTS(*line);
2145 }
2146 
2147 /*
2148  * Issue fsync recursively on PGDATA and all its contents.
2149  *
2150  * We fsync regular files and directories wherever they are, but we
2151  * follow symlinks only for pg_xlog and immediately under pg_tblspc.
2152  * Other symlinks are presumed to point at files we're not responsible
2153  * for fsyncing, and might not have privileges to write at all.
2154  *
2155  * Errors are reported but not considered fatal.
2156  */
2157 static void
2159 {
2160  bool xlog_is_symlink;
2161  char pg_xlog[MAXPGPATH];
2162  char pg_tblspc[MAXPGPATH];
2163 
2164  fputs(_("syncing data to disk ... "), stdout);
2165  fflush(stdout);
2166 
2167  snprintf(pg_xlog, MAXPGPATH, "%s/pg_xlog", pg_data);
2168  snprintf(pg_tblspc, MAXPGPATH, "%s/pg_tblspc", pg_data);
2169 
2170  /*
2171  * If pg_xlog is a symlink, we'll need to recurse into it separately,
2172  * because the first walkdir below will ignore it.
2173  */
2174  xlog_is_symlink = false;
2175 
2176 #ifndef WIN32
2177  {
2178  struct stat st;
2179 
2180  if (lstat(pg_xlog, &st) < 0)
2181  fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
2182  progname, pg_xlog, strerror(errno));
2183  else if (S_ISLNK(st.st_mode))
2184  xlog_is_symlink = true;
2185  }
2186 #else
2187  if (pgwin32_is_junction(pg_xlog))
2188  xlog_is_symlink = true;
2189 #endif
2190 
2191  /*
2192  * If possible, hint to the kernel that we're soon going to fsync the data
2193  * directory and its contents.
2194  */
2195 #ifdef PG_FLUSH_DATA_WORKS
2196  walkdir(pg_data, pre_sync_fname, false);
2197  if (xlog_is_symlink)
2198  walkdir(pg_xlog, pre_sync_fname, false);
2199  walkdir(pg_tblspc, pre_sync_fname, true);
2200 #endif
2201 
2202  /*
2203  * Now we do the fsync()s in the same order.
2204  *
2205  * The main call ignores symlinks, so in addition to specially processing
2206  * pg_xlog if it's a symlink, pg_tblspc has to be visited separately with
2207  * process_symlinks = true. Note that if there are any plain directories
2208  * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
2209  * so we don't worry about optimizing it.
2210  */
2211  walkdir(pg_data, fsync_fname_ext, false);
2212  if (xlog_is_symlink)
2213  walkdir(pg_xlog, fsync_fname_ext, false);
2214  walkdir(pg_tblspc, fsync_fname_ext, true);
2215 
2216  check_ok();
2217 }
2218 
2219 
2220 /*
2221  * signal handler in case we are interrupted.
2222  *
2223  * The Windows runtime docs at
2224  * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
2225  * specifically forbid a number of things being done from a signal handler,
2226  * including IO, memory allocation and system calls, and only allow jmpbuf
2227  * if you are handling SIGFPE.
2228  *
2229  * I avoided doing the forbidden things by setting a flag instead of calling
2230  * exit_nicely() directly.
2231  *
2232  * Also note the behaviour of Windows with SIGINT, which says this:
2233  * Note SIGINT is not supported for any Win32 application, including
2234  * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
2235  * Win32 operating systems generate a new thread to specifically handle
2236  * that interrupt. This can cause a single-thread application such as UNIX,
2237  * to become multithreaded, resulting in unexpected behavior.
2238  *
2239  * I have no idea how to handle this. (Strange they call UNIX an application!)
2240  * So this will need some testing on Windows.
2241  */
2242 static void
2243 trapsig(int signum)
2244 {
2245  /* handle systems that reset the handler, like Windows (grr) */
2246  pqsignal(signum, trapsig);
2247  caught_signal = true;
2248 }
2249 
2250 /*
2251  * call exit_nicely() if we got a signal, or else output "ok".
2252  */
2253 static void
2255 {
2256  if (caught_signal)
2257  {
2258  printf(_("caught signal\n"));
2259  fflush(stdout);
2260  exit_nicely();
2261  }
2262  else if (output_failed)
2263  {
2264  printf(_("could not write to child process: %s\n"),
2266  fflush(stdout);
2267  exit_nicely();
2268  }
2269  else
2270  {
2271  /* all seems well */
2272  printf(_("ok\n"));
2273  fflush(stdout);
2274  }
2275 }
2276 
2277 /* Hack to suppress a warning about %x from some versions of gcc */
2278 static inline size_t
2279 my_strftime(char *s, size_t max, const char *fmt, const struct tm * tm)
2280 {
2281  return strftime(s, max, fmt, tm);
2282 }
2283 
2284 /*
2285  * Determine likely date order from locale
2286  */
2287 static int
2289 {
2290  struct tm testtime;
2291  char buf[128];
2292  char *posD;
2293  char *posM;
2294  char *posY;
2295  char *save;
2296  size_t res;
2297  int result;
2298 
2299  result = DATEORDER_MDY; /* default */
2300 
2301  save = setlocale(LC_TIME, NULL);
2302  if (!save)
2303  return result;
2304  save = pg_strdup(save);
2305 
2306  setlocale(LC_TIME, locale);
2307 
2308  memset(&testtime, 0, sizeof(testtime));
2309  testtime.tm_mday = 22;
2310  testtime.tm_mon = 10; /* November, should come out as "11" */
2311  testtime.tm_year = 133; /* 2033 */
2312 
2313  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
2314 
2315  setlocale(LC_TIME, save);
2316  free(save);
2317 
2318  if (res == 0)
2319  return result;
2320 
2321  posM = strstr(buf, "11");
2322  posD = strstr(buf, "22");
2323  posY = strstr(buf, "33");
2324 
2325  if (!posM || !posD || !posY)
2326  return result;
2327 
2328  if (posY < posM && posM < posD)
2329  result = DATEORDER_YMD;
2330  else if (posD < posM)
2331  result = DATEORDER_DMY;
2332  else
2333  result = DATEORDER_MDY;
2334 
2335  return result;
2336 }
2337 
2338 /*
2339  * Verify that locale name is valid for the locale category.
2340  *
2341  * If successful, and canonname isn't NULL, a malloc'd copy of the locale's
2342  * canonical name is stored there. This is especially useful for figuring out
2343  * what locale name "" means (ie, the environment value). (Actually,
2344  * it seems that on most implementations that's the only thing it's good for;
2345  * we could wish that setlocale gave back a canonically spelled version of
2346  * the locale name, but typically it doesn't.)
2347  *
2348  * this should match the backend's check_locale() function
2349  */
2350 static void
2351 check_locale_name(int category, const char *locale, char **canonname)
2352 {
2353  char *save;
2354  char *res;
2355 
2356  if (canonname)
2357  *canonname = NULL; /* in case of failure */
2358 
2359  save = setlocale(category, NULL);
2360  if (!save)
2361  {
2362  fprintf(stderr, _("%s: setlocale() failed\n"),
2363  progname);
2364  exit(1);
2365  }
2366 
2367  /* save may be pointing at a modifiable scratch variable, so copy it. */
2368  save = pg_strdup(save);
2369 
2370  /* set the locale with setlocale, to see if it accepts it. */
2371  res = setlocale(category, locale);
2372 
2373  /* save canonical name if requested. */
2374  if (res && canonname)
2375  *canonname = pg_strdup(res);
2376 
2377  /* restore old value. */
2378  if (!setlocale(category, save))
2379  {
2380  fprintf(stderr, _("%s: failed to restore old locale \"%s\"\n"),
2381  progname, save);
2382  exit(1);
2383  }
2384  free(save);
2385 
2386  /* complain if locale wasn't valid */
2387  if (res == NULL)
2388  {
2389  if (*locale)
2390  fprintf(stderr, _("%s: invalid locale name \"%s\"\n"),
2391  progname, locale);
2392  else
2393  {
2394  /*
2395  * If no relevant switch was given on command line, locale is an
2396  * empty string, which is not too helpful to report. Presumably
2397  * setlocale() found something it did not like in the environment.
2398  * Ideally we'd report the bad environment variable, but since
2399  * setlocale's behavior is implementation-specific, it's hard to
2400  * be sure what it didn't like. Print a safe generic message.
2401  */
2402  fprintf(stderr, _("%s: invalid locale settings; check LANG and LC_* environment variables\n"),
2403  progname);
2404  }
2405  exit(1);
2406  }
2407 }
2408 
2409 /*
2410  * check if the chosen encoding matches the encoding required by the locale
2411  *
2412  * this should match the similar check in the backend createdb() function
2413  */
2414 static bool
2415 check_locale_encoding(const char *locale, int user_enc)
2416 {
2417  int locale_enc;
2418 
2419  locale_enc = pg_get_encoding_from_locale(locale, true);
2420 
2421  /* See notes in createdb() to understand these tests */
2422  if (!(locale_enc == user_enc ||
2423  locale_enc == PG_SQL_ASCII ||
2424  locale_enc == -1 ||
2425 #ifdef WIN32
2426  user_enc == PG_UTF8 ||
2427 #endif
2428  user_enc == PG_SQL_ASCII))
2429  {
2430  fprintf(stderr, _("%s: encoding mismatch\n"), progname);
2431  fprintf(stderr,
2432  _("The encoding you selected (%s) and the encoding that the\n"
2433  "selected locale uses (%s) do not match. This would lead to\n"
2434  "misbehavior in various character string processing functions.\n"
2435  "Rerun %s and either do not specify an encoding explicitly,\n"
2436  "or choose a matching combination.\n"),
2437  pg_encoding_to_char(user_enc),
2438  pg_encoding_to_char(locale_enc),
2439  progname);
2440  return false;
2441  }
2442  return true;
2443 }
2444 
2445 /*
2446  * set up the locale variables
2447  *
2448  * assumes we have called setlocale(LC_ALL, "") -- see set_pglocale_pgservice
2449  */
2450 static void
2452 {
2453  char *canonname;
2454 
2455  /* set empty lc_* values to locale config if set */
2456 
2457  if (strlen(locale) > 0)
2458  {
2459  if (strlen(lc_ctype) == 0)
2460  lc_ctype = locale;
2461  if (strlen(lc_collate) == 0)
2462  lc_collate = locale;
2463  if (strlen(lc_numeric) == 0)
2464  lc_numeric = locale;
2465  if (strlen(lc_time) == 0)
2466  lc_time = locale;
2467  if (strlen(lc_monetary) == 0)
2468  lc_monetary = locale;
2469  if (strlen(lc_messages) == 0)
2470  lc_messages = locale;
2471  }
2472 
2473  /*
2474  * canonicalize locale names, and obtain any missing values from our
2475  * current environment
2476  */
2477 
2478  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2479  lc_ctype = canonname;
2480  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2481  lc_collate = canonname;
2482  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2483  lc_numeric = canonname;
2484  check_locale_name(LC_TIME, lc_time, &canonname);
2485  lc_time = canonname;
2486  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2487  lc_monetary = canonname;
2488 #if defined(LC_MESSAGES) && !defined(WIN32)
2489  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2490  lc_messages = canonname;
2491 #else
2492  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2493  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2494  lc_messages = canonname;
2495 #endif
2496 }
2497 
2498 /*
2499  * print help text
2500  */
2501 static void
2502 usage(const char *progname)
2503 {
2504  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2505  printf(_("Usage:\n"));
2506  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2507  printf(_("\nOptions:\n"));
2508  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2509  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2510  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2511  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2512  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2513  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2514  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2515  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2516  " set default locale in the respective category for\n"
2517  " new databases (default taken from environment)\n"));
2518  printf(_(" --no-locale equivalent to --locale=C\n"));
2519  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2520  printf(_(" -T, --text-search-config=CFG\n"
2521  " default text search configuration\n"));
2522  printf(_(" -U, --username=NAME database superuser name\n"));
2523  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2524  printf(_(" -X, --xlogdir=XLOGDIR location for the transaction log directory\n"));
2525  printf(_("\nLess commonly used options:\n"));
2526  printf(_(" -d, --debug generate lots of debugging output\n"));
2527  printf(_(" -k, --data-checksums use data page checksums\n"));
2528  printf(_(" -L DIRECTORY where to find the input files\n"));
2529  printf(_(" -n, --noclean do not clean up after errors\n"));
2530  printf(_(" -N, --nosync do not wait for changes to be written safely to disk\n"));
2531  printf(_(" -s, --show show internal settings\n"));
2532  printf(_(" -S, --sync-only only sync data directory\n"));
2533  printf(_("\nOther options:\n"));
2534  printf(_(" -V, --version output version information, then exit\n"));
2535  printf(_(" -?, --help show this help, then exit\n"));
2536  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2537  "is used.\n"));
2538  printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2539 }
2540 
2541 static void
2542 check_authmethod_unspecified(const char **authmethod)
2543 {
2544  if (*authmethod == NULL || strlen(*authmethod) == 0)
2545  {
2546  authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
2547  "You can change this by editing pg_hba.conf or using the option -A, or\n"
2548  "--auth-local and --auth-host, the next time you run initdb.\n");
2549  *authmethod = "trust";
2550  }
2551 }
2552 
2553 static void
2554 check_authmethod_valid(const char *authmethod, const char *const * valid_methods, const char *conntype)
2555 {
2556  const char *const * p;
2557 
2558  for (p = valid_methods; *p; p++)
2559  {
2560  if (strcmp(authmethod, *p) == 0)
2561  return;
2562  /* with space = param */
2563  if (strchr(authmethod, ' '))
2564  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2565  return;
2566  }
2567 
2568  fprintf(stderr, _("%s: invalid authentication method \"%s\" for \"%s\" connections\n"),
2569  progname, authmethod, conntype);
2570  exit(1);
2571 }
2572 
2573 static void
2575 {
2576  if ((strcmp(authmethodlocal, "md5") == 0 ||
2577  strcmp(authmethodlocal, "password") == 0) &&
2578  (strcmp(authmethodhost, "md5") == 0 ||
2579  strcmp(authmethodhost, "password") == 0) &&
2580  !(pwprompt || pwfilename))
2581  {
2582  fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname,
2583  (strcmp(authmethodlocal, "md5") == 0 ||
2584  strcmp(authmethodlocal, "password") == 0)
2585  ? authmethodlocal
2586  : authmethodhost);
2587  exit(1);
2588  }
2589 }
2590 
2591 
2592 void
2594 {
2595  char *pgdata_get_env,
2596  *pgdata_set_env;
2597 
2598  if (strlen(pg_data) == 0)
2599  {
2600  pgdata_get_env = getenv("PGDATA");
2601  if (pgdata_get_env && strlen(pgdata_get_env))
2602  {
2603  /* PGDATA found */
2604  pg_data = pg_strdup(pgdata_get_env);
2605  }
2606  else
2607  {
2608  fprintf(stderr,
2609  _("%s: no data directory specified\n"
2610  "You must identify the directory where the data for this database system\n"
2611  "will reside. Do this with either the invocation option -D or the\n"
2612  "environment variable PGDATA.\n"),
2613  progname);
2614  exit(1);
2615  }
2616  }
2617 
2620 
2621  /*
2622  * we have to set PGDATA for postgres rather than pass it on the command
2623  * line to avoid dumb quoting problems on Windows, and we would especially
2624  * need quotes otherwise on Windows because paths there are most likely to
2625  * have embedded spaces.
2626  */
2627  pgdata_set_env = psprintf("PGDATA=%s", pg_data);
2628  putenv(pgdata_set_env);
2629 }
2630 
2631 
2632 void
2634 {
2635  int ret;
2636 
2637  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2638  backend_exec)) < 0)
2639  {
2640  char full_path[MAXPGPATH];
2641 
2642  if (find_my_exec(argv0, full_path) < 0)
2643  strlcpy(full_path, progname, sizeof(full_path));
2644 
2645  if (ret == -1)
2646  fprintf(stderr,
2647  _("The program \"postgres\" is needed by %s "
2648  "but was not found in the\n"
2649  "same directory as \"%s\".\n"
2650  "Check your installation.\n"),
2651  progname, full_path);
2652  else
2653  fprintf(stderr,
2654  _("The program \"postgres\" was found by \"%s\"\n"
2655  "but was not the same version as %s.\n"
2656  "Check your installation.\n"),
2657  full_path, progname);
2658  exit(1);
2659  }
2660 
2661  /* store binary directory */
2662  strcpy(bin_path, backend_exec);
2663  *last_dir_separator(bin_path) = '\0';
2665 
2666  if (!share_path)
2667  {
2670  }
2671  else if (!is_absolute_path(share_path))
2672  {
2673  fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
2674  exit(1);
2675  }
2676 
2678 }
2679 
2680 void
2682 {
2683  int user_enc;
2684 
2685  setlocales();
2686 
2687  if (strcmp(lc_ctype, lc_collate) == 0 &&
2688  strcmp(lc_ctype, lc_time) == 0 &&
2689  strcmp(lc_ctype, lc_numeric) == 0 &&
2690  strcmp(lc_ctype, lc_monetary) == 0 &&
2691  strcmp(lc_ctype, lc_messages) == 0)
2692  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2693  else
2694  {
2695  printf(_("The database cluster will be initialized with locales\n"
2696  " COLLATE: %s\n"
2697  " CTYPE: %s\n"
2698  " MESSAGES: %s\n"
2699  " MONETARY: %s\n"
2700  " NUMERIC: %s\n"
2701  " TIME: %s\n"),
2702  lc_collate,
2703  lc_ctype,
2704  lc_messages,
2705  lc_monetary,
2706  lc_numeric,
2707  lc_time);
2708  }
2709 
2710  if (strlen(encoding) == 0)
2711  {
2712  int ctype_enc;
2713 
2714  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2715 
2716  if (ctype_enc == -1)
2717  {
2718  /* Couldn't recognize the locale's codeset */
2719  fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"),
2720  progname, lc_ctype);
2721  fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2722  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2723  progname);
2724  exit(1);
2725  }
2726  else if (!pg_valid_server_encoding_id(ctype_enc))
2727  {
2728  /*
2729  * We recognized it, but it's not a legal server encoding. On
2730  * Windows, UTF-8 works with any locale, so we can fall back to
2731  * UTF-8.
2732  */
2733 #ifdef WIN32
2734  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2735  "The default database encoding will be set to \"%s\" instead.\n"),
2736  pg_encoding_to_char(ctype_enc),
2738  ctype_enc = PG_UTF8;
2739  encodingid = encodingid_to_string(ctype_enc);
2740 #else
2741  fprintf(stderr,
2742  _("%s: locale \"%s\" requires unsupported encoding \"%s\"\n"),
2743  progname, lc_ctype, pg_encoding_to_char(ctype_enc));
2744  fprintf(stderr,
2745  _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
2746  "Rerun %s with a different locale selection.\n"),
2747  pg_encoding_to_char(ctype_enc), progname);
2748  exit(1);
2749 #endif
2750  }
2751  else
2752  {
2753  encodingid = encodingid_to_string(ctype_enc);
2754  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2755  pg_encoding_to_char(ctype_enc));
2756  }
2757  }
2758  else
2760 
2761  user_enc = atoi(encodingid);
2762  if (!check_locale_encoding(lc_ctype, user_enc) ||
2763  !check_locale_encoding(lc_collate, user_enc))
2764  exit(1); /* check_locale_encoding printed the error */
2765 
2766 }
2767 
2768 
2769 void
2771 {
2772  set_input(&bki_file, "postgres.bki");
2773  set_input(&desc_file, "postgres.description");
2774  set_input(&shdesc_file, "postgres.shdescription");
2775  set_input(&hba_file, "pg_hba.conf.sample");
2776  set_input(&ident_file, "pg_ident.conf.sample");
2777  set_input(&conf_file, "postgresql.conf.sample");
2778  set_input(&conversion_file, "conversion_create.sql");
2779  set_input(&dictionary_file, "snowball_create.sql");
2780  set_input(&info_schema_file, "information_schema.sql");
2781  set_input(&features_file, "sql_features.txt");
2782  set_input(&system_views_file, "system_views.sql");
2783 
2784  if (show_setting || debug)
2785  {
2786  fprintf(stderr,
2787  "VERSION=%s\n"
2788  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2789  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2790  "POSTGRES_DESCR=%s\nPOSTGRES_SHDESCR=%s\n"
2791  "POSTGRESQL_CONF_SAMPLE=%s\n"
2792  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2793  PG_VERSION,
2795  username, bki_file,
2797  conf_file,
2798  hba_file, ident_file);
2799  if (show_setting)
2800  exit(0);
2801  }
2802 
2814 }
2815 
2816 
2817 void
2819 {
2820  if (strlen(default_text_search_config) == 0)
2821  {
2824  {
2825  printf(_("%s: could not find suitable text search configuration for locale \"%s\"\n"),
2826  progname, lc_ctype);
2827  default_text_search_config = "simple";
2828  }
2829  }
2830  else
2831  {
2832  const char *checkmatch = find_matching_ts_config(lc_ctype);
2833 
2834  if (checkmatch == NULL)
2835  {
2836  printf(_("%s: warning: suitable text search configuration for locale \"%s\" is unknown\n"),
2837  progname, lc_ctype);
2838  }
2839  else if (strcmp(checkmatch, default_text_search_config) != 0)
2840  {
2841  printf(_("%s: warning: specified text search configuration \"%s\" might not match locale \"%s\"\n"),
2843  }
2844  }
2845 
2846  printf(_("The default text search configuration will be set to \"%s\".\n"),
2848 
2849 }
2850 
2851 
2852 void
2854 {
2855  /* some of these are not valid on Windows */
2856 #ifdef SIGHUP
2858 #endif
2859 #ifdef SIGINT
2860  pqsignal(SIGINT, trapsig);
2861 #endif
2862 #ifdef SIGQUIT
2864 #endif
2865 #ifdef SIGTERM
2866  pqsignal(SIGTERM, trapsig);
2867 #endif
2868 
2869  /* Ignore SIGPIPE when writing to backend, so we can clean up */
2870 #ifdef SIGPIPE
2872 #endif
2873 
2874  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
2875 #ifdef SIGSYS
2876  pqsignal(SIGSYS, SIG_IGN);
2877 #endif
2878 }
2879 
2880 
2881 void
2883 {
2884  int ret;
2885 
2886  switch ((ret = pg_check_dir(pg_data)))
2887  {
2888  case 0:
2889  /* PGDATA not there, must create it */
2890  printf(_("creating directory %s ... "),
2891  pg_data);
2892  fflush(stdout);
2893 
2894  if (pg_mkdir_p(pg_data, S_IRWXU) != 0)
2895  {
2896  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
2897  progname, pg_data, strerror(errno));
2898  exit_nicely();
2899  }
2900  else
2901  check_ok();
2902 
2903  made_new_pgdata = true;
2904  break;
2905 
2906  case 1:
2907  /* Present but empty, fix permissions and use it */
2908  printf(_("fixing permissions on existing directory %s ... "),
2909  pg_data);
2910  fflush(stdout);
2911 
2912  if (chmod(pg_data, S_IRWXU) != 0)
2913  {
2914  fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
2915  progname, pg_data, strerror(errno));
2916  exit_nicely();
2917  }
2918  else
2919  check_ok();
2920 
2921  found_existing_pgdata = true;
2922  break;
2923 
2924  case 2:
2925  case 3:
2926  case 4:
2927  /* Present and not empty */
2928  fprintf(stderr,
2929  _("%s: directory \"%s\" exists but is not empty\n"),
2930  progname, pg_data);
2931  if (ret != 4)
2932  warn_on_mount_point(ret);
2933  else
2934  fprintf(stderr,
2935  _("If you want to create a new database system, either remove or empty\n"
2936  "the directory \"%s\" or run %s\n"
2937  "with an argument other than \"%s\".\n"),
2939  exit(1); /* no further message needed */
2940 
2941  default:
2942  /* Trouble accessing directory */
2943  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
2944  progname, pg_data, strerror(errno));
2945  exit_nicely();
2946  }
2947 }
2948 
2949 
2950 /* Create transaction log directory, and symlink if required */
2951 void
2953 {
2954  char *subdirloc;
2955 
2956  /* form name of the place for the subdirectory or symlink */
2957  subdirloc = psprintf("%s/pg_xlog", pg_data);
2958 
2959  if (strcmp(xlog_dir, "") != 0)
2960  {
2961  int ret;
2962 
2963  /* clean up xlog directory name, check it's absolute */
2965  if (!is_absolute_path(xlog_dir))
2966  {
2967  fprintf(stderr, _("%s: transaction log directory location must be an absolute path\n"), progname);
2968  exit_nicely();
2969  }
2970 
2971  /* check if the specified xlog directory exists/is empty */
2972  switch ((ret = pg_check_dir(xlog_dir)))
2973  {
2974  case 0:
2975  /* xlog directory not there, must create it */
2976  printf(_("creating directory %s ... "),
2977  xlog_dir);
2978  fflush(stdout);
2979 
2980  if (pg_mkdir_p(xlog_dir, S_IRWXU) != 0)
2981  {
2982  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
2983  progname, xlog_dir, strerror(errno));
2984  exit_nicely();
2985  }
2986  else
2987  check_ok();
2988 
2989  made_new_xlogdir = true;
2990  break;
2991 
2992  case 1:
2993  /* Present but empty, fix permissions and use it */
2994  printf(_("fixing permissions on existing directory %s ... "),
2995  xlog_dir);
2996  fflush(stdout);
2997 
2998  if (chmod(xlog_dir, S_IRWXU) != 0)
2999  {
3000  fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
3001  progname, xlog_dir, strerror(errno));
3002  exit_nicely();
3003  }
3004  else
3005  check_ok();
3006 
3007  found_existing_xlogdir = true;
3008  break;
3009 
3010  case 2:
3011  case 3:
3012  case 4:
3013  /* Present and not empty */
3014  fprintf(stderr,
3015  _("%s: directory \"%s\" exists but is not empty\n"),
3016  progname, xlog_dir);
3017  if (ret != 4)
3018  warn_on_mount_point(ret);
3019  else
3020  fprintf(stderr,
3021  _("If you want to store the transaction log there, either\n"
3022  "remove or empty the directory \"%s\".\n"),
3023  xlog_dir);
3024  exit_nicely();
3025 
3026  default:
3027  /* Trouble accessing directory */
3028  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3029  progname, xlog_dir, strerror(errno));
3030  exit_nicely();
3031  }
3032 
3033 #ifdef HAVE_SYMLINK
3034  if (symlink(xlog_dir, subdirloc) != 0)
3035  {
3036  fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
3037  progname, subdirloc, strerror(errno));
3038  exit_nicely();
3039  }
3040 #else
3041  fprintf(stderr, _("%s: symlinks are not supported on this platform"));
3042  exit_nicely();
3043 #endif
3044  }
3045  else
3046  {
3047  /* Without -X option, just make the subdirectory normally */
3048  if (mkdir(subdirloc, S_IRWXU) < 0)
3049  {
3050  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3051  progname, subdirloc, strerror(errno));
3052  exit_nicely();
3053  }
3054  }
3055 
3056  free(subdirloc);
3057 }
3058 
3059 
3060 void
3062 {
3063  if (error == 2)
3064  fprintf(stderr,
3065  _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
3066  else if (error == 3)
3067  fprintf(stderr,
3068  _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
3069 
3070  fprintf(stderr,
3071  _("Using a mount point directly as the data directory is not recommended.\n"
3072  "Create a subdirectory under the mount point.\n"));
3073 }
3074 
3075 
3076 void
3078 {
3079  PG_CMD_DECL;
3080  int i;
3081 
3082  setup_signals();
3083 
3084  umask(S_IRWXG | S_IRWXO);
3085 
3087 
3089 
3090  /* Create required subdirectories (other than pg_xlog) */
3091  printf(_("creating subdirectories ... "));
3092  fflush(stdout);
3093 
3094  for (i = 0; i < lengthof(subdirs); i++)
3095  {
3096  char *path;
3097 
3098  path = psprintf("%s/%s", pg_data, subdirs[i]);
3099 
3100  /*
3101  * The parent directory already exists, so we only need mkdir() not
3102  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
3103  */
3104  if (mkdir(path, S_IRWXU) < 0)
3105  {
3106  fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
3107  progname, path, strerror(errno));
3108  exit_nicely();
3109  }
3110 
3111  free(path);
3112  }
3113 
3114  check_ok();
3115 
3116  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
3118 
3119  /* Select suitable configuration settings */
3120  set_null_conf();
3122 
3123  /* Now create all the text config files */
3124  setup_config();
3125 
3126  /* Bootstrap template1 */
3128 
3129  /*
3130  * Make the per-database PG_VERSION for template1 only after init'ing it
3131  */
3132  write_version_file("base/1");
3133 
3134  /*
3135  * Create the stuff we don't need to use bootstrap mode for, using a
3136  * backend running in simple standalone mode.
3137  */
3138  fputs(_("performing post-bootstrap initialization ... "), stdout);
3139  fflush(stdout);
3140 
3141  snprintf(cmd, sizeof(cmd),
3142  "\"%s\" %s template1 >%s",
3144  DEVNULL);
3145 
3146  PG_CMD_OPEN;
3147 
3148  setup_auth(cmdfd);
3149  if (pwprompt || pwfilename)
3150  get_set_pwd(cmdfd);
3151 
3152  setup_depend(cmdfd);
3153 
3154  setup_sysviews(cmdfd);
3155 
3156  setup_description(cmdfd);
3157 
3158  setup_collation(cmdfd);
3159 
3160  setup_conversion(cmdfd);
3161 
3162  setup_dictionary(cmdfd);
3163 
3164  setup_privileges(cmdfd);
3165 
3166  setup_schema(cmdfd);
3167 
3168  load_plpgsql(cmdfd);
3169 
3170  vacuum_db(cmdfd);
3171 
3172  make_template0(cmdfd);
3173 
3174  make_postgres(cmdfd);
3175 
3176  PG_CMD_CLOSE;
3177 
3178  check_ok();
3179 }
3180 
3181 
3182 int
3183 main(int argc, char *argv[])
3184 {
3185  static struct option long_options[] = {
3186  {"pgdata", required_argument, NULL, 'D'},
3187  {"encoding", required_argument, NULL, 'E'},
3188  {"locale", required_argument, NULL, 1},
3189  {"lc-collate", required_argument, NULL, 2},
3190  {"lc-ctype", required_argument, NULL, 3},
3191  {"lc-monetary", required_argument, NULL, 4},
3192  {"lc-numeric", required_argument, NULL, 5},
3193  {"lc-time", required_argument, NULL, 6},
3194  {"lc-messages", required_argument, NULL, 7},
3195  {"no-locale", no_argument, NULL, 8},
3196  {"text-search-config", required_argument, NULL, 'T'},
3197  {"auth", required_argument, NULL, 'A'},
3198  {"auth-local", required_argument, NULL, 10},
3199  {"auth-host", required_argument, NULL, 11},
3200  {"pwprompt", no_argument, NULL, 'W'},
3201  {"pwfile", required_argument, NULL, 9},
3202  {"username", required_argument, NULL, 'U'},
3203  {"help", no_argument, NULL, '?'},
3204  {"version", no_argument, NULL, 'V'},
3205  {"debug", no_argument, NULL, 'd'},
3206  {"show", no_argument, NULL, 's'},
3207  {"noclean", no_argument, NULL, 'n'},
3208  {"nosync", no_argument, NULL, 'N'},
3209  {"sync-only", no_argument, NULL, 'S'},
3210  {"xlogdir", required_argument, NULL, 'X'},
3211  {"data-checksums", no_argument, NULL, 'k'},
3212  {NULL, 0, NULL, 0}
3213  };
3214 
3215  /*
3216  * options with no short version return a low integer, the rest return
3217  * their short version value
3218  */
3219  int c;
3220  int option_index;
3221  char *effective_user;
3222  char bin_dir[MAXPGPATH];
3223 
3224  /*
3225  * Ensure that buffering behavior of stdout and stderr matches what it is
3226  * in interactive usage (at least on most platforms). This prevents
3227  * unexpected output ordering when, eg, output is redirected to a file.
3228  * POSIX says we must do this before any other usage of these files.
3229  */
3230  setvbuf(stdout, NULL, PG_IOLBF, 0);
3231  setvbuf(stderr, NULL, _IONBF, 0);
3232 
3233  progname = get_progname(argv[0]);
3234  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
3235 
3236  if (argc > 1)
3237  {
3238  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
3239  {
3240  usage(progname);
3241  exit(0);
3242  }
3243  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
3244  {
3245  puts("initdb (PostgreSQL) " PG_VERSION);
3246  exit(0);
3247  }
3248  }
3249 
3250  /* process command-line options */
3251 
3252  while ((c = getopt_long(argc, argv, "dD:E:kL:nNU:WA:sST:X:", long_options, &option_index)) != -1)
3253  {
3254  switch (c)
3255  {
3256  case 'A':
3258 
3259  /*
3260  * When ident is specified, use peer for local connections.
3261  * Mirrored, when peer is specified, use ident for TCP/IP
3262  * connections.
3263  */
3264  if (strcmp(authmethodhost, "ident") == 0)
3265  authmethodlocal = "peer";
3266  else if (strcmp(authmethodlocal, "peer") == 0)
3267  authmethodhost = "ident";
3268  break;
3269  case 10:
3271  break;
3272  case 11:
3274  break;
3275  case 'D':
3277  break;
3278  case 'E':
3280  break;
3281  case 'W':
3282  pwprompt = true;
3283  break;
3284  case 'U':
3286  break;
3287  case 'd':
3288  debug = true;
3289  printf(_("Running in debug mode.\n"));
3290  break;
3291  case 'n':
3292  noclean = true;
3293  printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
3294  break;
3295  case 'N':
3296  do_sync = false;
3297  break;
3298  case 'S':
3299  sync_only = true;
3300  break;
3301  case 'k':
3302  data_checksums = true;
3303  break;
3304  case 'L':
3306  break;
3307  case 1:
3308  locale = pg_strdup(optarg);
3309  break;
3310  case 2:
3312  break;
3313  case 3:
3315  break;
3316  case 4:
3318  break;
3319  case 5:
3321  break;
3322  case 6:
3324  break;
3325  case 7:
3327  break;
3328  case 8:
3329  locale = "C";
3330  break;
3331  case 9:
3333  break;
3334  case 's':
3335  show_setting = true;
3336  break;
3337  case 'T':
3339  break;
3340  case 'X':
3342  break;
3343  default:
3344  /* getopt_long already emitted a complaint */
3345  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3346  progname);
3347  exit(1);
3348  }
3349  }
3350 
3351 
3352  /*
3353  * Non-option argument specifies data directory as long as it wasn't
3354  * already specified with -D / --pgdata
3355  */
3356  if (optind < argc && strlen(pg_data) == 0)
3357  {
3358  pg_data = pg_strdup(argv[optind]);
3359  optind++;
3360  }
3361 
3362  if (optind < argc)
3363  {
3364  fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
3365  progname, argv[optind]);
3366  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3367  progname);
3368  exit(1);
3369  }
3370 
3371  /* If we only need to fsync, just do it and exit */
3372  if (sync_only)
3373  {
3374  setup_pgdata();
3375 
3376  /* must check that directory is readable */
3377  if (pg_check_dir(pg_data) <= 0)
3378  {
3379  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
3380  progname, pg_data, strerror(errno));
3381  exit_nicely();
3382  }
3383 
3384  fsync_pgdata();
3385  return 0;
3386  }
3387 
3388  if (pwprompt && pwfilename)
3389  {
3390  fprintf(stderr, _("%s: password prompt and password file cannot be specified together\n"), progname);
3391  exit(1);
3392  }
3393 
3396 
3399 
3401 
3403 
3404  setup_pgdata();
3405 
3406  setup_bin_paths(argv[0]);
3407 
3408  effective_user = get_id();
3409  if (strlen(username) == 0)
3410  username = effective_user;
3411 
3412  printf(_("The files belonging to this database system will be owned "
3413  "by user \"%s\".\n"
3414  "This user must also own the server process.\n\n"),
3415  effective_user);
3416 
3417  set_info_version();
3418 
3420 
3422 
3424 
3425  printf("\n");
3426 
3427  if (data_checksums)
3428  printf(_("Data page checksums are enabled.\n"));
3429  else
3430  printf(_("Data page checksums are disabled.\n"));
3431 
3432  printf("\n");
3433 
3435 
3436  if (do_sync)
3437  fsync_pgdata();
3438  else
3439  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3440 
3441  if (authwarning != NULL)
3442  fprintf(stderr, "%s", authwarning);
3443 
3444  /* Get directory specification used to start this executable */
3445  strlcpy(bin_dir, argv[0], sizeof(bin_dir));
3446  get_parent_directory(bin_dir);
3447 
3448  printf(_("\nSuccess. You can now start the database server using:\n\n"
3449  " %s%s%spg_ctl%s -D %s%s%s -l logfile start\n\n"),
3450  QUOTE_PATH, bin_dir, (strlen(bin_dir) > 0) ? DIR_SEP : "", QUOTE_PATH,
3452 
3453  return 0;
3454 }
static char * lc_monetary
Definition: initdb.c:123
#define DIR_SEP
Definition: initdb.c:330
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:1111
void setup_data_file_paths(void)
Definition: initdb.c:2770
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:1617
#define MIN_BUFS_FOR_CONNS(nconns)
#define PG_CMD_PRINTF3(fmt, arg1, arg2, arg3)
Definition: initdb.c:322
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:357
static char * argv0
Definition: pg_ctl.c:90
static char * choose_dsm_implementation(void)
Definition: initdb.c:1049
void setup_locale_encoding(void)
Definition: initdb.c:2681
static FILE * popen_check(const char *command, const char *mode)
Definition: initdb.c:706
static char infoversion[100]
Definition: initdb.c:160
static bool debug
Definition: initdb.c:133
static void vacuum_db(FILE *cmdfd)
Definition: initdb.c:2086
int system(const char *command)
Definition: system.c:52
static char * system_views_file
Definition: initdb.c:155
static void error(void)
Definition: sql-dyntest.c:147
static char * lc_collate
Definition: initdb.c:121
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:3061
static char * conf_file
Definition: initdb.c:150
const char * get_progname(const char *argv0)
Definition: path.c:419
static const char * backend_options
Definition: initdb.c:192
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:154
#define mkdir(a, b)
Definition: win32.h:51
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void setup_auth(FILE *cmdfd)
Definition: initdb.c:1528
static void setup_dictionary(FILE *cmdfd)
Definition: initdb.c:1967
static bool made_new_xlogdir
Definition: initdb.c:158
#define AUTHTRUST_WARNING
Definition: initdb.c:174
void canonicalize_path(char *path)
Definition: path.c:220
static bool caught_signal
Definition: initdb.c:161
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:2952
static void bootstrap_template1(void)
Definition: initdb.c:1429
#define PG_BINARY_W
Definition: c.h:1010
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:2853
static const struct tsearch_config_match tsearch_config_languages[]
Definition: initdb.c:847
static void get_set_pwd(FILE *cmdfd)
Definition: initdb.c:1548
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define lengthof(array)
Definition: c.h:543
static bool pwprompt
Definition: initdb.c:129
static char * pgdata_native
Definition: initdb.c:164
#define PG_CMD_PUTS(line)
Definition: initdb.c:304
#define putenv(x)
Definition: win32.h:404
#define AI_NUMERICHOST
Definition: getaddrinfo.h:75
static chr newline(void)
Definition: regc_lex.c:1139
Definition: dirent.h:9
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1007
#define SIGQUIT
Definition: win32.h:183
static char * get_id(void)
Definition: initdb.c:788
static char * share_path
Definition: initdb.c:115
static void fsync_pgdata(void)
Definition: initdb.c:2158
static char * encodingid
Definition: initdb.c:144
static struct pg_tm tm
Definition: localtime.c:116
void get_restricted_token(const char *progname)
static void set_null_conf(void)
Definition: initdb.c:1015
static const char * authmethodlocal
Definition: initdb.c:132
#define NAMEDATALEN
static char * lc_time
Definition: initdb.c:125
static void check_input(char *path)
Definition: initdb.c:943
static int n_connections
Definition: initdb.c:167
static void check_authmethod_unspecified(const char **authmethod)
Definition: initdb.c:2542
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:231
#define SIG_IGN
Definition: win32.h:179
int optind
Definition: getopt.c:51
#define IS_HIGHBIT_SET(ch)
Definition: c.h:938
#define PG_CMD_DECL
Definition: initdb.c:289
Definition: dirent.c:25
struct pg_encoding enc
Definition: encode.c:522
static const char *const subdirs[]
Definition: initdb.c:194
static char * lc_messages
Definition: initdb.c:126
static char * desc_file
Definition: initdb.c:146
#define MAXPGPATH
static bool check_locale_encoding(const char *locale, int encoding)
Definition: initdb.c:2415
static const char * default_text_search_config
Definition: initdb.c:127
static char * lc_ctype
Definition: initdb.c:122
#define PG_CMD_OPEN
Definition: initdb.c:291
static char * conversion_file
Definition: initdb.c:151
const char * tsconfname
Definition: initdb.c:843
static void setup_config(void)
Definition: initdb.c:1189
static char * lc_numeric
Definition: initdb.c:124
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:157
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:2077
void initialize_data_directory(void)
Definition: initdb.c:3077
#define is_absolute_path(filename)
Definition: port.h:76
#define PG_CMD_PRINTF1(fmt, arg1)
Definition: initdb.c:310
void get_parent_directory(char *path)
Definition: path.c:820
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
unsigned int uint32
Definition: c.h:254
static void setup_description(FILE *cmdfd)
Definition: initdb.c:1719
static char * pg_data
Definition: initdb.c:118
#define DEVNULL
Definition: port.h:115
static char * pwfilename
Definition: initdb.c:130
static void check_ok(void)
Definition: initdb.c:2254
#define fsync(fd)
Definition: win32.h:56
static bool found_existing_xlogdir
Definition: initdb.c:159
static bool made_new_pgdata
Definition: initdb.c:156
char * simple_prompt(const char *prompt, int maxlen, bool echo)
Definition: sprompt.c:38
static char * dictionary_file
Definition: initdb.c:152
#define DATEORDER_YMD
Definition: miscadmin.h:214
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:2633
static const char * progname
Definition: initdb.c:143
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:36
void create_data_directory(void)
Definition: initdb.c:2882
#define PG_CMD_CLOSE
Definition: initdb.c:298
#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:191
static char * xlog_dir
Definition: initdb.c:139
#define PG_TEXTDOMAIN(domain)
Definition: c.h:981
static bool data_checksums
Definition: initdb.c:138
static char * info_schema_file
Definition: initdb.c:153
static size_t my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
Definition: initdb.c:2279
static void make_template0(FILE *cmdfd)
Definition: initdb.c:2096
static int locale_date_order(const char *locale)
Definition: initdb.c:2288
static void setup_conversion(FILE *cmdfd)
Definition: initdb.c:1947
char * last_dir_separator(const char *filename)
Definition: path.c:134
#define PG_IOLBF
Definition: port.h:338
#define SIGPIPE
Definition: win32.h:187
#define S_IRWXO
Definition: win32.h:467
#define DATEORDER_DMY
Definition: miscadmin.h:215
#define SIGHUP
Definition: win32.h:182
static char * username
Definition: initdb.c:128
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:406
static char * get_encoding_id(char *encoding_name)
Definition: initdb.c:823
#define DATEORDER_MDY
Definition: miscadmin.h:216
static void infile(const char *filename)
Definition: zic.c:825
static char * encoding
Definition: initdb.c:119
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:167
#define free(a)
Definition: header.h:60
int ai_protocol
Definition: getaddrinfo.h:105
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:531
static char * authwarning
Definition: initdb.c:179
void setup_text_search(void)
Definition: initdb.c:2818
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:293
#define NULL
Definition: c.h:215
static void setup_collation(FILE *cmdfd)
Definition: initdb.c:1809
static char ** filter_lines_with_token(char **lines, const char *token)
Definition: initdb.c:413
static bool do_sync
Definition: initdb.c:135
int ai_socktype
Definition: getaddrinfo.h:104
static void setup_schema(FILE *cmdfd)
Definition: initdb.c:2046
int main(int argc, char *argv[])
Definition: initdb.c:3183
static bool output_failed
Definition: initdb.c:162
static void setlocales(void)
Definition: initdb.c:2451
struct dirent * readdir(DIR *)
Definition: dirent.c:78
#define QUOTE_PATH
Definition: initdb.c:329
#define unsetenv(x)
Definition: win32.h:405
static void check_locale_name(int category, const char *locale, char **canonname)
Definition: initdb.c:2351
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:463
static int n_buffers
Definition: initdb.c:168
static const char *const auth_methods_host[]
Definition: initdb.c:82
static char * escape_quotes(const char *src)
Definition: initdb.c:337
static int output_errno
Definition: initdb.c:163
static char * filename
Definition: pg_dumpall.c:85
struct addrinfo * ai_next
Definition: getaddrinfo.h:109
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:550
static void writefile(char *path, char **lines)
Definition: initdb.c:502
char * optarg
Definition: getopt.c:53
static void setup_privileges(FILE *cmdfd)
Definition: initdb.c:1994
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:2134
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:31
static char bin_path[MAXPGPATH]
Definition: initdb.c:221
static void usage(const char *progname)
Definition: initdb.c:2502
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:2574
static char backend_exec[MAXPGPATH]
Definition: initdb.c:222
static char * ident_file
Definition: initdb.c:149
static char * locale
Definition: initdb.c:120
static char ** readfile(const char *path)
Definition: initdb.c:440
static char * shdesc_file
Definition: initdb.c:147
static char * bki_file
Definition: initdb.c:145
static char * dynamic_shared_memory_type
Definition: initdb.c:169
static const char * authmethodhost
Definition: initdb.c:131
size_t ai_addrlen
Definition: getaddrinfo.h:106
static bool sync_only
Definition: initdb.c:136
char d_name[MAX_PATH]
Definition: dirent.h:14
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:95
#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:101
static void check_authmethod_valid(const char *authmethod, const char *const *valid_methods, const char *conntype)
Definition: initdb.c:2554
static void setup_sysviews(FILE *cmdfd)
Definition: initdb.c:1699
void get_share_path(const char *my_exec_path, char *ret_path)
Definition: path.c:670
#define PG_CMD_PRINTF2(fmt, arg1, arg2)
Definition: initdb.c:316
#define lstat(path, sb)
Definition: win32.h:258
void setup_pgdata(void)
Definition: initdb.c:2593
#define _(x)
Definition: elog.c:83
const char * langname
Definition: initdb.c:844
static void trapsig(int signum)
Definition: initdb.c:2243
struct sockaddr * ai_addr
Definition: getaddrinfo.h:107
static char * hba_file
Definition: initdb.c:148
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
static void set_info_version(void)
Definition: initdb.c:2019
#define DEFAULT_PGSOCKET_DIR
static bool show_setting
Definition: initdb.c:137
static bool noclean
Definition: initdb.c:134
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:76
int ai_family
Definition: getaddrinfo.h:103