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