PostgreSQL Source Code  git master
initdb.c File Reference
#include "postgres_fe.h"
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include "access/xlog_internal.h"
#include "catalog/pg_authid_d.h"
#include "catalog/pg_class_d.h"
#include "catalog/pg_collation_d.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/logging.h"
#include "common/restricted_token.h"
#include "common/string.h"
#include "common/username.h"
#include "fe_utils/string_utils.h"
#include "getaddrinfo.h"
#include "getopt_long.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
Include dependency graph for initdb.c:

Go to the source code of this file.

Data Structures

struct  tsearch_config_match
 

Macros

#define AUTHTRUST_WARNING
 
#define PG_CMD_DECL   char cmd[MAXPGPATH]; FILE *cmdfd
 
#define PG_CMD_OPEN
 
#define PG_CMD_CLOSE
 
#define PG_CMD_PUTS(line)
 
#define PG_CMD_PRINTF(fmt, ...)
 
#define MIN_BUFS_FOR_CONNS(nconns)   ((nconns) * 10)
 

Functions

const char * select_default_timezone (const char *share_path)
 
static char ** replace_token (char **lines, const char *token, const char *replacement)
 
static char ** filter_lines_with_token (char **lines, const char *token)
 
static char ** readfile (const char *path)
 
static void writefile (char *path, char **lines)
 
static FILE * popen_check (const char *command, const char *mode)
 
static char * get_id (void)
 
static int get_encoding_id (const char *encoding_name)
 
static void set_input (char **dest, const char *filename)
 
static void check_input (char *path)
 
static void write_version_file (const char *extrapath)
 
static void set_null_conf (void)
 
static void test_config_settings (void)
 
static void setup_config (void)
 
static void bootstrap_template1 (void)
 
static void setup_auth (FILE *cmdfd)
 
static void get_su_pwd (void)
 
static void setup_depend (FILE *cmdfd)
 
static void setup_run_file (FILE *cmdfd, const char *filename)
 
static void setup_description (FILE *cmdfd)
 
static void setup_collation (FILE *cmdfd)
 
static void setup_privileges (FILE *cmdfd)
 
static void set_info_version (void)
 
static void setup_schema (FILE *cmdfd)
 
static void load_plpgsql (FILE *cmdfd)
 
static void vacuum_db (FILE *cmdfd)
 
static void make_template0 (FILE *cmdfd)
 
static void make_postgres (FILE *cmdfd)
 
static void trapsig (int signum)
 
static void check_ok (void)
 
static char * escape_quotes (const char *src)
 
static char * escape_quotes_bki (const char *src)
 
static int locale_date_order (const char *locale)
 
static void check_locale_name (int category, const char *locale, char **canonname)
 
static bool check_locale_encoding (const char *locale, int encoding)
 
static void setlocales (void)
 
static void usage (const char *progname)
 
void setup_pgdata (void)
 
void setup_bin_paths (const char *argv0)
 
void setup_data_file_paths (void)
 
void setup_locale_encoding (void)
 
void setup_signals (void)
 
void setup_text_search (void)
 
void create_data_directory (void)
 
void create_xlog_or_symlink (void)
 
void warn_on_mount_point (int error)
 
void initialize_data_directory (void)
 
static void cleanup_directories_atexit (void)
 
static char * encodingid_to_string (int enc)
 
static const char * find_matching_ts_config (const char *lc_type)
 
static const char * choose_dsm_implementation (void)
 
static char * pretty_wal_size (int segment_count)
 
static size_t my_strftime (char *s, size_t max, const char *fmt, const struct tm *tm)
 
static void check_authmethod_unspecified (const char **authmethod)
 
static void check_authmethod_valid (const char *authmethod, const char *const *valid_methods, const char *conntype)
 
static void check_need_password (const char *authmethodlocal, const char *authmethodhost)
 
int main (int argc, char *argv[])
 

Variables

static const char *const auth_methods_host []
 
static const char *const auth_methods_local []
 
static char * share_path = NULL
 
static char * pg_data = NULL
 
static char * encoding = NULL
 
static char * locale = NULL
 
static char * lc_collate = NULL
 
static char * lc_ctype = NULL
 
static char * lc_monetary = NULL
 
static char * lc_numeric = NULL
 
static char * lc_time = NULL
 
static char * lc_messages = NULL
 
static const char * default_text_search_config = NULL
 
static char * username = NULL
 
static bool pwprompt = false
 
static char * pwfilename = NULL
 
static char * superuser_password = NULL
 
static const char * authmethodhost = NULL
 
static const char * authmethodlocal = NULL
 
static bool debug = false
 
static bool noclean = false
 
static bool noinstructions = false
 
static bool do_sync = true
 
static bool sync_only = false
 
static bool show_setting = false
 
static bool data_checksums = false
 
static char * xlog_dir = NULL
 
static char * str_wal_segment_size_mb = NULL
 
static int wal_segment_size_mb
 
static const char * progname
 
static int encodingid
 
static char * bki_file
 
static char * hba_file
 
static char * ident_file
 
static char * conf_file
 
static char * dictionary_file
 
static char * info_schema_file
 
static char * features_file
 
static char * system_constraints_file
 
static char * system_functions_file
 
static char * system_views_file
 
static bool success = false
 
static bool made_new_pgdata = false
 
static bool found_existing_pgdata = false
 
static bool made_new_xlogdir = false
 
static bool found_existing_xlogdir = false
 
static char infoversion [100]
 
static bool caught_signal = false
 
static bool output_failed = false
 
static int output_errno = 0
 
static char * pgdata_native
 
static int n_connections = 10
 
static int n_buffers = 50
 
static const char * dynamic_shared_memory_type = NULL
 
static const char * default_timezone = NULL
 
static bool authwarning = false
 
static const char * boot_options = "-F"
 
static const char * backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true"
 
static char * extra_options = ""
 
static const char *const subdirs []
 
static char bin_path [MAXPGPATH]
 
static char backend_exec [MAXPGPATH]
 
static const struct tsearch_config_match tsearch_config_languages []
 

Macro Definition Documentation

◆ AUTHTRUST_WARNING

#define AUTHTRUST_WARNING
Value:
"# CAUTION: Configuring the system for local \"trust\" authentication\n" \
"# allows any local user to connect as any PostgreSQL user, including\n" \
"# the database superuser. If you do not trust all your local users,\n" \
"# use another authentication method.\n"

Definition at line 185 of file initdb.c.

Referenced by setup_config().

◆ MIN_BUFS_FOR_CONNS

#define MIN_BUFS_FOR_CONNS (   nconns)    ((nconns) * 10)

Referenced by test_config_settings().

◆ PG_CMD_CLOSE

#define PG_CMD_CLOSE
Value:
do { \
if (pclose_check(cmdfd)) \
exit(1); /* message already printed by pclose_check */ \
} while (0)
int pclose_check(FILE *stream)
Definition: exec.c:395

Definition at line 302 of file initdb.c.

Referenced by bootstrap_template1(), and initialize_data_directory().

◆ PG_CMD_DECL

#define PG_CMD_DECL   char cmd[MAXPGPATH]; FILE *cmdfd

Definition at line 293 of file initdb.c.

Referenced by bootstrap_template1(), and initialize_data_directory().

◆ PG_CMD_OPEN

#define PG_CMD_OPEN
Value:
do { \
cmdfd = popen_check(cmd, "w"); \
if (cmdfd == NULL) \
exit(1); /* message already printed by popen_check */ \
} while (0)
static FILE * popen_check(const char *command, const char *mode)
Definition: initdb.c:531

Definition at line 295 of file initdb.c.

Referenced by bootstrap_template1(), and initialize_data_directory().

◆ PG_CMD_PRINTF

#define PG_CMD_PRINTF (   fmt,
  ... 
)
Value:
do { \
if (fprintf(cmdfd, fmt, __VA_ARGS__) < 0 || fflush(cmdfd) < 0) \
output_failed = true, output_errno = errno; \
} while (0)
#define fprintf
Definition: port.h:221
static int output_errno
Definition: initdb.c:173

Definition at line 314 of file initdb.c.

Referenced by setup_auth(), setup_collation(), and setup_schema().

◆ PG_CMD_PUTS

#define PG_CMD_PUTS (   line)
Value:
do { \
if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
output_failed = true, output_errno = errno; \
} while (0)
static int output_errno
Definition: initdb.c:173

Definition at line 308 of file initdb.c.

Referenced by bootstrap_template1(), load_plpgsql(), make_postgres(), make_template0(), setup_auth(), setup_collation(), setup_depend(), setup_description(), setup_privileges(), setup_run_file(), and vacuum_db().

Function Documentation

◆ bootstrap_template1()

static void bootstrap_template1 ( void  )
static

Definition at line 1351 of file initdb.c.

References _, backend_exec, bki_file, boot_options, buf, check_ok(), data_checksums, debug, encodingid, encodingid_to_string(), escape_quotes_bki(), extra_options, FLOAT8PASSBYVAL, fprintf, free, lc_collate, lc_ctype, MAXPGPATH, NAMEDATALEN, PG_CMD_CLOSE, PG_CMD_DECL, PG_CMD_OPEN, PG_CMD_PUTS, pg_log_error, printf, readfile(), replace_token(), snprintf, sprintf, generate_unaccent_rules::stdout, unsetenv, username, and wal_segment_size_mb.

Referenced by initialize_data_directory().

1352 {
1353  PG_CMD_DECL;
1354  char **line;
1355  char **bki_lines;
1356  char headerline[MAXPGPATH];
1357  char buf[64];
1358 
1359  printf(_("running bootstrap script ... "));
1360  fflush(stdout);
1361 
1362  bki_lines = readfile(bki_file);
1363 
1364  /* Check that bki file appears to be of the right version */
1365 
1366  snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1367  PG_MAJORVERSION);
1368 
1369  if (strcmp(headerline, *bki_lines) != 0)
1370  {
1371  pg_log_error("input file \"%s\" does not belong to PostgreSQL %s",
1372  bki_file, PG_VERSION);
1373  fprintf(stderr,
1374  _("Check your installation or specify the correct path "
1375  "using the option -L.\n"));
1376  exit(1);
1377  }
1378 
1379  /* Substitute for various symbols used in the BKI file */
1380 
1381  sprintf(buf, "%d", NAMEDATALEN);
1382  bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
1383 
1384  sprintf(buf, "%d", (int) sizeof(Pointer));
1385  bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
1386 
1387  bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
1388  (sizeof(Pointer) == 4) ? "i" : "d");
1389 
1390  bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
1391  FLOAT8PASSBYVAL ? "true" : "false");
1392 
1393  bki_lines = replace_token(bki_lines, "POSTGRES",
1395 
1396  bki_lines = replace_token(bki_lines, "ENCODING",
1398 
1399  bki_lines = replace_token(bki_lines, "LC_COLLATE",
1401 
1402  bki_lines = replace_token(bki_lines, "LC_CTYPE",
1404 
1405  /* Also ensure backend isn't confused by this environment var: */
1406  unsetenv("PGCLIENTENCODING");
1407 
1408  snprintf(cmd, sizeof(cmd),
1409  "\"%s\" --boot -X %u %s %s %s %s",
1410  backend_exec,
1411  wal_segment_size_mb * (1024 * 1024),
1412  data_checksums ? "-k" : "",
1414  debug ? "-d 5" : "");
1415 
1416 
1417  PG_CMD_OPEN;
1418 
1419  for (line = bki_lines; *line != NULL; line++)
1420  {
1421  PG_CMD_PUTS(*line);
1422  free(*line);
1423  }
1424 
1425  PG_CMD_CLOSE;
1426 
1427  free(bki_lines);
1428 
1429  check_ok();
1430 }
static int encodingid
Definition: initdb.c:154
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:371
static bool debug
Definition: initdb.c:140
static char * lc_collate
Definition: initdb.c:127
static char * encodingid_to_string(int enc)
Definition: initdb.c:623
#define pg_log_error(...)
Definition: logging.h:80
#define printf(...)
Definition: port.h:223
#define PG_CMD_PUTS(line)
Definition: initdb.c:308
#define fprintf
Definition: port.h:221
#define NAMEDATALEN
#define sprintf
Definition: port.h:219
char * Pointer
Definition: c.h:418
#define PG_CMD_DECL
Definition: initdb.c:293
#define MAXPGPATH
static char * lc_ctype
Definition: initdb.c:128
#define PG_CMD_OPEN
Definition: initdb.c:295
static char * buf
Definition: pg_test_fsync.c:68
static int wal_segment_size_mb
Definition: initdb.c:149
static void check_ok(void)
Definition: initdb.c:1920
#define PG_CMD_CLOSE
Definition: initdb.c:302
static char * extra_options
Definition: initdb.c:206
static const char * boot_options
Definition: initdb.c:202
static bool data_checksums
Definition: initdb.c:146
static char * username
Definition: initdb.c:134
#define free(a)
Definition: header.h:65
#define FLOAT8PASSBYVAL
Definition: c.h:570
static char backend_exec[MAXPGPATH]
Definition: initdb.c:236
static char ** readfile(const char *path)
Definition: initdb.c:454
static char * bki_file
Definition: initdb.c:155
#define snprintf
Definition: port.h:217
#define _(x)
Definition: elog.c:89
static char * escape_quotes_bki(const char *src)
Definition: initdb.c:344
#define unsetenv(x)
Definition: win32_port.h:508

◆ check_authmethod_unspecified()

static void check_authmethod_unspecified ( const char **  authmethod)
static

Definition at line 2213 of file initdb.c.

References authwarning.

Referenced by main().

2214 {
2215  if (*authmethod == NULL)
2216  {
2217  authwarning = true;
2218  *authmethod = "trust";
2219  }
2220 }
static bool authwarning
Definition: initdb.c:190

◆ check_authmethod_valid()

static void check_authmethod_valid ( const char *  authmethod,
const char *const *  valid_methods,
const char *  conntype 
)
static

Definition at line 2223 of file initdb.c.

References pg_log_error.

Referenced by main().

2224 {
2225  const char *const *p;
2226 
2227  for (p = valid_methods; *p; p++)
2228  {
2229  if (strcmp(authmethod, *p) == 0)
2230  return;
2231  /* with space = param */
2232  if (strchr(authmethod, ' '))
2233  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2234  return;
2235  }
2236 
2237  pg_log_error("invalid authentication method \"%s\" for \"%s\" connections",
2238  authmethod, conntype);
2239  exit(1);
2240 }
#define pg_log_error(...)
Definition: logging.h:80

◆ check_input()

static void check_input ( char *  path)
static

Definition at line 781 of file initdb.c.

References _, fprintf, pg_log_error, S_ISREG, stat::st_mode, and stat.

Referenced by setup_data_file_paths().

782 {
783  struct stat statbuf;
784 
785  if (stat(path, &statbuf) != 0)
786  {
787  if (errno == ENOENT)
788  {
789  pg_log_error("file \"%s\" does not exist", path);
790  fprintf(stderr,
791  _("This might mean you have a corrupted installation or identified\n"
792  "the wrong directory with the invocation option -L.\n"));
793  }
794  else
795  {
796  pg_log_error("could not access file \"%s\": %m", path);
797  fprintf(stderr,
798  _("This might mean you have a corrupted installation or identified\n"
799  "the wrong directory with the invocation option -L.\n"));
800  }
801  exit(1);
802  }
803  if (!S_ISREG(statbuf.st_mode))
804  {
805  pg_log_error("file \"%s\" is not a regular file", path);
806  fprintf(stderr,
807  _("This might mean you have a corrupted installation or identified\n"
808  "the wrong directory with the invocation option -L.\n"));
809  exit(1);
810  }
811 }
#define pg_log_error(...)
Definition: logging.h:80
#define fprintf
Definition: port.h:221
#define S_ISREG(m)
Definition: win32_port.h:327
#define _(x)
Definition: elog.c:89
#define stat
Definition: win32_port.h:283

◆ check_locale_encoding()

static bool check_locale_encoding ( const char *  locale,
int  encoding 
)
static

Definition at line 2081 of file initdb.c.

References _, fprintf, pg_encoding_to_char(), pg_get_encoding_from_locale(), pg_log_error, PG_SQL_ASCII, PG_UTF8, and progname.

Referenced by setup_locale_encoding().

2082 {
2083  int locale_enc;
2084 
2085  locale_enc = pg_get_encoding_from_locale(locale, true);
2086 
2087  /* See notes in createdb() to understand these tests */
2088  if (!(locale_enc == user_enc ||
2089  locale_enc == PG_SQL_ASCII ||
2090  locale_enc == -1 ||
2091 #ifdef WIN32
2092  user_enc == PG_UTF8 ||
2093 #endif
2094  user_enc == PG_SQL_ASCII))
2095  {
2096  pg_log_error("encoding mismatch");
2097  fprintf(stderr,
2098  _("The encoding you selected (%s) and the encoding that the\n"
2099  "selected locale uses (%s) do not match. This would lead to\n"
2100  "misbehavior in various character string processing functions.\n"
2101  "Rerun %s and either do not specify an encoding explicitly,\n"
2102  "or choose a matching combination.\n"),
2103  pg_encoding_to_char(user_enc),
2104  pg_encoding_to_char(locale_enc),
2105  progname);
2106  return false;
2107  }
2108  return true;
2109 }
#define pg_log_error(...)
Definition: logging.h:80
#define fprintf
Definition: port.h:221
static const char * progname
Definition: initdb.c:153
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:452
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
static char * locale
Definition: initdb.c:126
#define _(x)
Definition: elog.c:89

◆ check_locale_name()

static void check_locale_name ( int  category,
const char *  locale,
char **  canonname 
)
static

Definition at line 2017 of file initdb.c.

References free, pg_log_error, pg_strdup(), and setlocale.

Referenced by setlocales().

2018 {
2019  char *save;
2020  char *res;
2021 
2022  if (canonname)
2023  *canonname = NULL; /* in case of failure */
2024 
2025  save = setlocale(category, NULL);
2026  if (!save)
2027  {
2028  pg_log_error("setlocale() failed");
2029  exit(1);
2030  }
2031 
2032  /* save may be pointing at a modifiable scratch variable, so copy it. */
2033  save = pg_strdup(save);
2034 
2035  /* for setlocale() call */
2036  if (!locale)
2037  locale = "";
2038 
2039  /* set the locale with setlocale, to see if it accepts it. */
2040  res = setlocale(category, locale);
2041 
2042  /* save canonical name if requested. */
2043  if (res && canonname)
2044  *canonname = pg_strdup(res);
2045 
2046  /* restore old value. */
2047  if (!setlocale(category, save))
2048  {
2049  pg_log_error("failed to restore old locale \"%s\"", save);
2050  exit(1);
2051  }
2052  free(save);
2053 
2054  /* complain if locale wasn't valid */
2055  if (res == NULL)
2056  {
2057  if (*locale)
2058  pg_log_error("invalid locale name \"%s\"", locale);
2059  else
2060  {
2061  /*
2062  * If no relevant switch was given on command line, locale is an
2063  * empty string, which is not too helpful to report. Presumably
2064  * setlocale() found something it did not like in the environment.
2065  * Ideally we'd report the bad environment variable, but since
2066  * setlocale's behavior is implementation-specific, it's hard to
2067  * be sure what it didn't like. Print a safe generic message.
2068  */
2069  pg_log_error("invalid locale settings; check LANG and LC_* environment variables");
2070  }
2071  exit(1);
2072  }
2073 }
#define setlocale(a, b)
Definition: win32_port.h:446
#define pg_log_error(...)
Definition: logging.h:80
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define free(a)
Definition: header.h:65
static char * locale
Definition: initdb.c:126

◆ check_need_password()

static void check_need_password ( const char *  authmethodlocal,
const char *  authmethodhost 
)
static

Definition at line 2243 of file initdb.c.

References pg_log_error, pwfilename, and pwprompt.

Referenced by main().

2244 {
2245  if ((strcmp(authmethodlocal, "md5") == 0 ||
2246  strcmp(authmethodlocal, "password") == 0 ||
2247  strcmp(authmethodlocal, "scram-sha-256") == 0) &&
2248  (strcmp(authmethodhost, "md5") == 0 ||
2249  strcmp(authmethodhost, "password") == 0 ||
2250  strcmp(authmethodhost, "scram-sha-256") == 0) &&
2251  !(pwprompt || pwfilename))
2252  {
2253  pg_log_error("must specify a password for the superuser to enable password authentication");
2254  exit(1);
2255  }
2256 }
#define pg_log_error(...)
Definition: logging.h:80
static bool pwprompt
Definition: initdb.c:135
static const char * authmethodlocal
Definition: initdb.c:139
static char * pwfilename
Definition: initdb.c:136
static const char * authmethodhost
Definition: initdb.c:138

◆ check_ok()

static void check_ok ( void  )
static

Definition at line 1920 of file initdb.c.

References _, caught_signal, output_errno, output_failed, printf, generate_unaccent_rules::stdout, and strerror.

Referenced by adjust_data_dir(), bootstrap_template1(), check_cluster_versions(), check_for_composite_data_type_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_new_tablespace_dir(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), copy_subdir_files(), copy_xact_xlog_xid(), create_data_directory(), create_new_objects(), create_script_for_old_cluster_deletion(), create_xlog_or_symlink(), disable_old_cluster(), generate_old_dump(), initialize_data_directory(), main(), new_9_0_populate_pg_largeobject_metadata(), old_11_check_for_sql_identifier_data_type_usage(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), prepare_new_cluster(), prepare_new_globals(), remove_new_subdir(), report_extension_updates(), set_frozenxids(), setup_config(), and transfer_all_new_tablespaces().

1921 {
1922  if (caught_signal)
1923  {
1924  printf(_("caught signal\n"));
1925  fflush(stdout);
1926  exit(1);
1927  }
1928  else if (output_failed)
1929  {
1930  printf(_("could not write to child process: %s\n"),
1932  fflush(stdout);
1933  exit(1);
1934  }
1935  else
1936  {
1937  /* all seems well */
1938  printf(_("ok\n"));
1939  fflush(stdout);
1940  }
1941 }
static bool caught_signal
Definition: initdb.c:171
#define printf(...)
Definition: port.h:223
#define strerror
Definition: port.h:230
static bool output_failed
Definition: initdb.c:172
static int output_errno
Definition: initdb.c:173
#define _(x)
Definition: elog.c:89

◆ choose_dsm_implementation()

static const char* choose_dsm_implementation ( void  )
static

Definition at line 879 of file initdb.c.

References close, fd(), name, random(), snprintf, and srandom().

Referenced by test_config_settings().

880 {
881 #ifdef HAVE_SHM_OPEN
882  int ntries = 10;
883 
884  /* Initialize random(); this function is its only user in this program. */
885  srandom((unsigned int) (getpid() ^ time(NULL)));
886 
887  while (ntries > 0)
888  {
889  uint32 handle;
890  char name[64];
891  int fd;
892 
893  handle = random();
894  snprintf(name, 64, "/PostgreSQL.%u", handle);
895  if ((fd = shm_open(name, O_CREAT | O_RDWR | O_EXCL, 0600)) != -1)
896  {
897  close(fd);
898  shm_unlink(name);
899  return "posix";
900  }
901  if (errno != EEXIST)
902  break;
903  --ntries;
904  }
905 #endif
906 
907 #ifdef WIN32
908  return "windows";
909 #else
910  return "sysv";
911 #endif
912 }
long random(void)
Definition: random.c:22
static int fd(const char *x, int i)
Definition: preproc-init.c:105
unsigned int uint32
Definition: c.h:441
const char * name
Definition: encode.c:561
void srandom(unsigned int seed)
Definition: srandom.c:22
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:217

◆ cleanup_directories_atexit()

static void cleanup_directories_atexit ( void  )
static

Definition at line 549 of file initdb.c.

References found_existing_pgdata, found_existing_xlogdir, made_new_pgdata, made_new_xlogdir, noclean, pg_data, pg_log_error, pg_log_info, rmtree(), success, and xlog_dir.

Referenced by main().

550 {
551  if (success)
552  return;
553 
554  if (!noclean)
555  {
556  if (made_new_pgdata)
557  {
558  pg_log_info("removing data directory \"%s\"", pg_data);
559  if (!rmtree(pg_data, true))
560  pg_log_error("failed to remove data directory");
561  }
562  else if (found_existing_pgdata)
563  {
564  pg_log_info("removing contents of data directory \"%s\"",
565  pg_data);
566  if (!rmtree(pg_data, false))
567  pg_log_error("failed to remove contents of data directory");
568  }
569 
570  if (made_new_xlogdir)
571  {
572  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
573  if (!rmtree(xlog_dir, true))
574  pg_log_error("failed to remove WAL directory");
575  }
576  else if (found_existing_xlogdir)
577  {
578  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
579  if (!rmtree(xlog_dir, false))
580  pg_log_error("failed to remove contents of WAL directory");
581  }
582  /* otherwise died during startup, do nothing! */
583  }
584  else
585  {
587  pg_log_info("data directory \"%s\" not removed at user's request",
588  pg_data);
589 
591  pg_log_info("WAL directory \"%s\" not removed at user's request",
592  xlog_dir);
593  }
594 }
#define pg_log_error(...)
Definition: logging.h:80
static bool made_new_xlogdir
Definition: initdb.c:168
static bool found_existing_pgdata
Definition: initdb.c:167
static char * pg_data
Definition: initdb.c:124
static bool found_existing_xlogdir
Definition: initdb.c:169
static bool made_new_pgdata
Definition: initdb.c:166
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
static char * xlog_dir
Definition: initdb.c:147
static bool success
Definition: initdb.c:165
#define pg_log_info(...)
Definition: logging.h:88
static bool noclean
Definition: initdb.c:141

◆ create_data_directory()

void create_data_directory ( void  )

Definition at line 2538 of file initdb.c.

References _, check_ok(), found_existing_pgdata, fprintf, made_new_pgdata, pg_check_dir(), pg_data, pg_dir_create_mode, pg_log_error, pg_mkdir_p(), printf, progname, generate_unaccent_rules::stdout, and warn_on_mount_point().

Referenced by initialize_data_directory().

2539 {
2540  int ret;
2541 
2542  switch ((ret = pg_check_dir(pg_data)))
2543  {
2544  case 0:
2545  /* PGDATA not there, must create it */
2546  printf(_("creating directory %s ... "),
2547  pg_data);
2548  fflush(stdout);
2549 
2551  {
2552  pg_log_error("could not create directory \"%s\": %m", pg_data);
2553  exit(1);
2554  }
2555  else
2556  check_ok();
2557 
2558  made_new_pgdata = true;
2559  break;
2560 
2561  case 1:
2562  /* Present but empty, fix permissions and use it */
2563  printf(_("fixing permissions on existing directory %s ... "),
2564  pg_data);
2565  fflush(stdout);
2566 
2567  if (chmod(pg_data, pg_dir_create_mode) != 0)
2568  {
2569  pg_log_error("could not change permissions of directory \"%s\": %m",
2570  pg_data);
2571  exit(1);
2572  }
2573  else
2574  check_ok();
2575 
2576  found_existing_pgdata = true;
2577  break;
2578 
2579  case 2:
2580  case 3:
2581  case 4:
2582  /* Present and not empty */
2583  pg_log_error("directory \"%s\" exists but is not empty", pg_data);
2584  if (ret != 4)
2585  warn_on_mount_point(ret);
2586  else
2587  fprintf(stderr,
2588  _("If you want to create a new database system, either remove or empty\n"
2589  "the directory \"%s\" or run %s\n"
2590  "with an argument other than \"%s\".\n"),
2592  exit(1); /* no further message needed */
2593 
2594  default:
2595  /* Trouble accessing directory */
2596  pg_log_error("could not access directory \"%s\": %m", pg_data);
2597  exit(1);
2598  }
2599 }
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
void warn_on_mount_point(int error)
Definition: initdb.c:2710
#define pg_log_error(...)
Definition: logging.h:80
#define printf(...)
Definition: port.h:223
#define fprintf
Definition: port.h:221
static bool found_existing_pgdata
Definition: initdb.c:167
static char * pg_data
Definition: initdb.c:124
static void check_ok(void)
Definition: initdb.c:1920
static bool made_new_pgdata
Definition: initdb.c:166
static const char * progname
Definition: initdb.c:153
int pg_dir_create_mode
Definition: file_perm.c:18
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:31
#define _(x)
Definition: elog.c:89

◆ create_xlog_or_symlink()

void create_xlog_or_symlink ( void  )

Definition at line 2604 of file initdb.c.

References _, canonicalize_path(), check_ok(), found_existing_xlogdir, fprintf, free, is_absolute_path, made_new_xlogdir, mkdir, pg_check_dir(), pg_data, pg_dir_create_mode, pg_log_error, pg_mkdir_p(), printf, psprintf(), generate_unaccent_rules::stdout, symlink, warn_on_mount_point(), and xlog_dir.

Referenced by initialize_data_directory().

2605 {
2606  char *subdirloc;
2607 
2608  /* form name of the place for the subdirectory or symlink */
2609  subdirloc = psprintf("%s/pg_wal", pg_data);
2610 
2611  if (xlog_dir)
2612  {
2613  int ret;
2614 
2615  /* clean up xlog directory name, check it's absolute */
2617  if (!is_absolute_path(xlog_dir))
2618  {
2619  pg_log_error("WAL directory location must be an absolute path");
2620  exit(1);
2621  }
2622 
2623  /* check if the specified xlog directory exists/is empty */
2624  switch ((ret = pg_check_dir(xlog_dir)))
2625  {
2626  case 0:
2627  /* xlog directory not there, must create it */
2628  printf(_("creating directory %s ... "),
2629  xlog_dir);
2630  fflush(stdout);
2631 
2633  {
2634  pg_log_error("could not create directory \"%s\": %m",
2635  xlog_dir);
2636  exit(1);
2637  }
2638  else
2639  check_ok();
2640 
2641  made_new_xlogdir = true;
2642  break;
2643 
2644  case 1:
2645  /* Present but empty, fix permissions and use it */
2646  printf(_("fixing permissions on existing directory %s ... "),
2647  xlog_dir);
2648  fflush(stdout);
2649 
2650  if (chmod(xlog_dir, pg_dir_create_mode) != 0)
2651  {
2652  pg_log_error("could not change permissions of directory \"%s\": %m",
2653  xlog_dir);
2654  exit(1);
2655  }
2656  else
2657  check_ok();
2658 
2659  found_existing_xlogdir = true;
2660  break;
2661 
2662  case 2:
2663  case 3:
2664  case 4:
2665  /* Present and not empty */
2666  pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
2667  if (ret != 4)
2668  warn_on_mount_point(ret);
2669  else
2670  fprintf(stderr,
2671  _("If you want to store the WAL there, either remove or empty the directory\n"
2672  "\"%s\".\n"),
2673  xlog_dir);
2674  exit(1);
2675 
2676  default:
2677  /* Trouble accessing directory */
2678  pg_log_error("could not access directory \"%s\": %m", xlog_dir);
2679  exit(1);
2680  }
2681 
2682 #ifdef HAVE_SYMLINK
2683  if (symlink(xlog_dir, subdirloc) != 0)
2684  {
2685  pg_log_error("could not create symbolic link \"%s\": %m",
2686  subdirloc);
2687  exit(1);
2688  }
2689 #else
2690  pg_log_error("symlinks are not supported on this platform");
2691  exit(1);
2692 #endif
2693  }
2694  else
2695  {
2696  /* Without -X option, just make the subdirectory normally */
2697  if (mkdir(subdirloc, pg_dir_create_mode) < 0)
2698  {
2699  pg_log_error("could not create directory \"%s\": %m",
2700  subdirloc);
2701  exit(1);
2702  }
2703  }
2704 
2705  free(subdirloc);
2706 }
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
void warn_on_mount_point(int error)
Definition: initdb.c:2710
#define pg_log_error(...)
Definition: logging.h:80
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static bool made_new_xlogdir
Definition: initdb.c:168
void canonicalize_path(char *path)
Definition: path.c:254
#define printf(...)
Definition: port.h:223
#define fprintf
Definition: port.h:221
#define symlink(oldpath, newpath)
Definition: win32_port.h:235
#define is_absolute_path(filename)
Definition: port.h:86
static char * pg_data
Definition: initdb.c:124
static void check_ok(void)
Definition: initdb.c:1920
static bool found_existing_xlogdir
Definition: initdb.c:169
int pg_dir_create_mode
Definition: file_perm.c:18
static char * xlog_dir
Definition: initdb.c:147
#define free(a)
Definition: header.h:65
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:31
#define mkdir(a, b)
Definition: win32_port.h:71
#define _(x)
Definition: elog.c:89

◆ encodingid_to_string()

static char* encodingid_to_string ( int  enc)
static

Definition at line 623 of file initdb.c.

References pg_strdup(), and sprintf.

Referenced by bootstrap_template1().

624 {
625  char result[20];
626 
627  sprintf(result, "%d", enc);
628  return pg_strdup(result);
629 }
#define sprintf
Definition: port.h:219
struct pg_encoding enc
Definition: encode.c:562
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85

◆ escape_quotes()

static char * escape_quotes ( const char *  src)
static

Definition at line 325 of file initdb.c.

References escape_single_quotes_ascii(), and pg_log_error.

Referenced by escape_quotes_bki(), setup_auth(), setup_config(), setup_privileges(), and setup_schema().

326 {
327  char *result = escape_single_quotes_ascii(src);
328 
329  if (!result)
330  {
331  pg_log_error("out of memory");
332  exit(1);
333  }
334  return result;
335 }
#define pg_log_error(...)
Definition: logging.h:80
char * escape_single_quotes_ascii(const char *src)
Definition: quotes.c:33

◆ escape_quotes_bki()

static char * escape_quotes_bki ( const char *  src)
static

Definition at line 344 of file initdb.c.

References escape_quotes(), free, and pg_malloc().

Referenced by bootstrap_template1().

345 {
346  char *result;
347  char *data = escape_quotes(src);
348  char *resultp;
349  char *datap;
350 
351  result = (char *) pg_malloc(strlen(data) + 3);
352  resultp = result;
353  *resultp++ = '\'';
354  for (datap = data; *datap; datap++)
355  *resultp++ = *datap;
356  *resultp++ = '\'';
357  *resultp = '\0';
358 
359  free(data);
360  return result;
361 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define free(a)
Definition: header.h:65
static char * escape_quotes(const char *src)
Definition: initdb.c:325

◆ filter_lines_with_token()

static char ** filter_lines_with_token ( char **  lines,
const char *  token 
)
static

Definition at line 427 of file initdb.c.

References i, and pg_malloc().

Referenced by setup_config().

428 {
429  int numlines = 1;
430  int i,
431  src,
432  dst;
433  char **result;
434 
435  for (i = 0; lines[i]; i++)
436  numlines++;
437 
438  result = (char **) pg_malloc(numlines * sizeof(char *));
439 
440  for (src = 0, dst = 0; src < numlines; src++)
441  {
442  if (lines[src] == NULL || strstr(lines[src], token) == NULL)
443  result[dst++] = lines[src];
444  }
445 
446  return result;
447 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
int i

◆ find_matching_ts_config()

static const char* find_matching_ts_config ( const char *  lc_type)
static

Definition at line 726 of file initdb.c.

References free, i, tsearch_config_match::langname, pg_strcasecmp(), pg_strdup(), and tsearch_config_match::tsconfname.

Referenced by setup_text_search().

727 {
728  int i;
729  char *langname,
730  *ptr;
731 
732  /*
733  * Convert lc_ctype to a language name by stripping everything after an
734  * underscore (usual case) or a hyphen (Windows "locale name"; see
735  * comments at IsoLocaleName()).
736  *
737  * XXX Should ' ' be a stop character? This would select "norwegian" for
738  * the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
739  * should also accept the "nn" and "nb" Unix locales.
740  *
741  * Just for paranoia, we also stop at '.' or '@'.
742  */
743  if (lc_type == NULL)
744  langname = pg_strdup("");
745  else
746  {
747  ptr = langname = pg_strdup(lc_type);
748  while (*ptr &&
749  *ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
750  ptr++;
751  *ptr = '\0';
752  }
753 
754  for (i = 0; tsearch_config_languages[i].tsconfname; i++)
755  {
756  if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
757  {
758  free(langname);
760  }
761  }
762 
763  free(langname);
764  return NULL;
765 }
static const struct tsearch_config_match tsearch_config_languages[]
Definition: initdb.c:659
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * tsconfname
Definition: initdb.c:655
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define free(a)
Definition: header.h:65
int i

◆ get_encoding_id()

static int get_encoding_id ( const char *  encoding_name)
static

Definition at line 635 of file initdb.c.

References enc, pg_log_error, and pg_valid_server_encoding().

Referenced by setup_locale_encoding().

636 {
637  int enc;
638 
639  if (encoding_name && *encoding_name)
640  {
641  if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
642  return enc;
643  }
644  pg_log_error("\"%s\" is not a valid server encoding name",
645  encoding_name ? encoding_name : "(null)");
646  exit(1);
647 }
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
#define pg_log_error(...)
Definition: logging.h:80
struct pg_encoding enc
Definition: encode.c:562

◆ get_id()

static char * get_id ( void  )
static

Definition at line 602 of file initdb.c.

References _, fprintf, get_user_name_or_exit(), pg_log_error, pg_strdup(), progname, and username.

Referenced by main().

603 {
604  const char *username;
605 
606 #ifndef WIN32
607  if (geteuid() == 0) /* 0 is root's uid */
608  {
609  pg_log_error("cannot be run as root");
610  fprintf(stderr,
611  _("Please log in (using, e.g., \"su\") as the (unprivileged) user that will\n"
612  "own the server process.\n"));
613  exit(1);
614  }
615 #endif
616 
617  username = get_user_name_or_exit(progname);
618 
619  return pg_strdup(username);
620 }
#define pg_log_error(...)
Definition: logging.h:80
#define fprintf
Definition: port.h:221
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static const char * progname
Definition: initdb.c:153
static char * username
Definition: initdb.c:134
#define _(x)
Definition: elog.c:89
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:74

◆ get_su_pwd()

static void get_su_pwd ( void  )
static

Definition at line 1460 of file initdb.c.

References _, fprintf, free, pg_get_line(), pg_log_error, pg_strip_crlf(), printf, pwfilename, pwprompt, simple_prompt(), generate_unaccent_rules::stdout, and superuser_password.

Referenced by main().

1461 {
1462  char *pwd1;
1463 
1464  if (pwprompt)
1465  {
1466  /*
1467  * Read password from terminal
1468  */
1469  char *pwd2;
1470 
1471  printf("\n");
1472  fflush(stdout);
1473  pwd1 = simple_prompt("Enter new superuser password: ", false);
1474  pwd2 = simple_prompt("Enter it again: ", false);
1475  if (strcmp(pwd1, pwd2) != 0)
1476  {
1477  fprintf(stderr, _("Passwords didn't match.\n"));
1478  exit(1);
1479  }
1480  free(pwd2);
1481  }
1482  else
1483  {
1484  /*
1485  * Read password from file
1486  *
1487  * Ideally this should insist that the file not be world-readable.
1488  * However, this option is mainly intended for use on Windows where
1489  * file permissions may not exist at all, so we'll skip the paranoia
1490  * for now.
1491  */
1492  FILE *pwf = fopen(pwfilename, "r");
1493 
1494  if (!pwf)
1495  {
1496  pg_log_error("could not open file \"%s\" for reading: %m",
1497  pwfilename);
1498  exit(1);
1499  }
1500  pwd1 = pg_get_line(pwf);
1501  if (!pwd1)
1502  {
1503  if (ferror(pwf))
1504  pg_log_error("could not read password from file \"%s\": %m",
1505  pwfilename);
1506  else
1507  pg_log_error("password file \"%s\" is empty",
1508  pwfilename);
1509  exit(1);
1510  }
1511  fclose(pwf);
1512 
1513  (void) pg_strip_crlf(pwd1);
1514  }
1515 
1516  superuser_password = pwd1;
1517 }
int pg_strip_crlf(char *str)
Definition: string.c:121
#define pg_log_error(...)
Definition: logging.h:80
#define printf(...)
Definition: port.h:223
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static bool pwprompt
Definition: initdb.c:135
#define fprintf
Definition: port.h:221
static char * pwfilename
Definition: initdb.c:136
#define free(a)
Definition: header.h:65
static char * superuser_password
Definition: initdb.c:137
char * pg_get_line(FILE *stream)
Definition: pg_get_line.c:52
#define _(x)
Definition: elog.c:89

◆ initialize_data_directory()

void initialize_data_directory ( void  )

Definition at line 2726 of file initdb.c.

References _, backend_exec, backend_options, bootstrap_template1(), check_ok(), create_data_directory(), create_xlog_or_symlink(), DEVNULL, dictionary_file, extra_options, free, i, lengthof, load_plpgsql(), make_postgres(), make_template0(), mkdir, PG_CMD_CLOSE, PG_CMD_DECL, PG_CMD_OPEN, pg_data, pg_dir_create_mode, pg_log_error, pg_mode_mask, printf, psprintf(), set_null_conf(), setup_auth(), setup_collation(), setup_config(), setup_depend(), setup_description(), setup_privileges(), setup_run_file(), setup_schema(), setup_signals(), snprintf, generate_unaccent_rules::stdout, subdirs, system_constraints_file, system_functions_file, system_views_file, test_config_settings(), vacuum_db(), and write_version_file().

Referenced by main().

2727 {
2728  PG_CMD_DECL;
2729  int i;
2730 
2731  setup_signals();
2732 
2733  /*
2734  * Set mask based on requested PGDATA permissions. pg_mode_mask, and
2735  * friends like pg_dir_create_mode, are set to owner-only by default and
2736  * then updated if -g is passed in by calling SetDataDirectoryCreatePerm()
2737  * when parsing our options (see above).
2738  */
2739  umask(pg_mode_mask);
2740 
2742 
2744 
2745  /* Create required subdirectories (other than pg_wal) */
2746  printf(_("creating subdirectories ... "));
2747  fflush(stdout);
2748 
2749  for (i = 0; i < lengthof(subdirs); i++)
2750  {
2751  char *path;
2752 
2753  path = psprintf("%s/%s", pg_data, subdirs[i]);
2754 
2755  /*
2756  * The parent directory already exists, so we only need mkdir() not
2757  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
2758  */
2759  if (mkdir(path, pg_dir_create_mode) < 0)
2760  {
2761  pg_log_error("could not create directory \"%s\": %m", path);
2762  exit(1);
2763  }
2764 
2765  free(path);
2766  }
2767 
2768  check_ok();
2769 
2770  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2771  write_version_file(NULL);
2772 
2773  /* Select suitable configuration settings */
2774  set_null_conf();
2776 
2777  /* Now create all the text config files */
2778  setup_config();
2779 
2780  /* Bootstrap template1 */
2782 
2783  /*
2784  * Make the per-database PG_VERSION for template1 only after init'ing it
2785  */
2786  write_version_file("base/1");
2787 
2788  /*
2789  * Create the stuff we don't need to use bootstrap mode for, using a
2790  * backend running in simple standalone mode.
2791  */
2792  fputs(_("performing post-bootstrap initialization ... "), stdout);
2793  fflush(stdout);
2794 
2795  snprintf(cmd, sizeof(cmd),
2796  "\"%s\" %s %s template1 >%s",
2798  DEVNULL);
2799 
2800  PG_CMD_OPEN;
2801 
2802  setup_auth(cmdfd);
2803 
2805 
2807 
2808  setup_depend(cmdfd);
2809 
2810  /*
2811  * Note that no objects created after setup_depend() will be "pinned".
2812  * They are all droppable at the whim of the DBA.
2813  */
2814 
2816 
2817  setup_description(cmdfd);
2818 
2819  setup_collation(cmdfd);
2820 
2822 
2823  setup_privileges(cmdfd);
2824 
2825  setup_schema(cmdfd);
2826 
2827  load_plpgsql(cmdfd);
2828 
2829  vacuum_db(cmdfd);
2830 
2831  make_template0(cmdfd);
2832 
2833  make_postgres(cmdfd);
2834 
2835  PG_CMD_CLOSE;
2836 
2837  check_ok();
2838 }
static void setup_depend(FILE *cmdfd)
Definition: initdb.c:1523
static char * system_constraints_file
Definition: initdb.c:162
static void vacuum_db(FILE *cmdfd)
Definition: initdb.c:1826
static char * system_views_file
Definition: initdb.c:164
static const char * backend_options
Definition: initdb.c:203
#define pg_log_error(...)
Definition: logging.h:80
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void setup_auth(FILE *cmdfd)
Definition: initdb.c:1436
void create_xlog_or_symlink(void)
Definition: initdb.c:2604
static void bootstrap_template1(void)
Definition: initdb.c:1351
static void setup_run_file(FILE *cmdfd, const char *filename)
Definition: initdb.c:1543
#define printf(...)
Definition: port.h:223
void setup_signals(void)
Definition: initdb.c:2509
#define lengthof(array)
Definition: c.h:734
static char * system_functions_file
Definition: initdb.c:163
static void set_null_conf(void)
Definition: initdb.c:847
#define PG_CMD_DECL
Definition: initdb.c:293
static const char *const subdirs[]
Definition: initdb.c:208
#define PG_CMD_OPEN
Definition: initdb.c:295
static void setup_config(void)
Definition: initdb.c:1051
static void load_plpgsql(FILE *cmdfd)
Definition: initdb.c:1817
static void write_version_file(const char *extrapath)
Definition: initdb.c:818
static void setup_description(FILE *cmdfd)
Definition: initdb.c:1564
static char * pg_data
Definition: initdb.c:124
#define DEVNULL
Definition: port.h:148
static void check_ok(void)
Definition: initdb.c:1920
static char * dictionary_file
Definition: initdb.c:159
static void test_config_settings(void)
Definition: initdb.c:920
void create_data_directory(void)
Definition: initdb.c:2538
int pg_dir_create_mode
Definition: file_perm.c:18
#define PG_CMD_CLOSE
Definition: initdb.c:302
static char * extra_options
Definition: initdb.c:206
static void make_template0(FILE *cmdfd)
Definition: initdb.c:1836
#define free(a)
Definition: header.h:65
static void setup_collation(FILE *cmdfd)
Definition: initdb.c:1585
static void setup_schema(FILE *cmdfd)
Definition: initdb.c:1797
static void setup_privileges(FILE *cmdfd)
Definition: initdb.c:1620
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:1874
int i
static char backend_exec[MAXPGPATH]
Definition: initdb.c:236
#define mkdir(a, b)
Definition: win32_port.h:71
#define snprintf
Definition: port.h:217
#define _(x)
Definition: elog.c:89
int pg_mode_mask
Definition: file_perm.c:25

◆ load_plpgsql()

static void load_plpgsql ( FILE *  cmdfd)
static

Definition at line 1817 of file initdb.c.

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

1818 {
1819  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
1820 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ locale_date_order()

static int locale_date_order ( const char *  locale)
static

Definition at line 1954 of file initdb.c.

References buf, DATEORDER_DMY, DATEORDER_MDY, DATEORDER_YMD, free, my_strftime(), pg_strdup(), setlocale, and tm.

Referenced by setup_config().

1955 {
1956  struct tm testtime;
1957  char buf[128];
1958  char *posD;
1959  char *posM;
1960  char *posY;
1961  char *save;
1962  size_t res;
1963  int result;
1964 
1965  result = DATEORDER_MDY; /* default */
1966 
1967  save = setlocale(LC_TIME, NULL);
1968  if (!save)
1969  return result;
1970  save = pg_strdup(save);
1971 
1972  setlocale(LC_TIME, locale);
1973 
1974  memset(&testtime, 0, sizeof(testtime));
1975  testtime.tm_mday = 22;
1976  testtime.tm_mon = 10; /* November, should come out as "11" */
1977  testtime.tm_year = 133; /* 2033 */
1978 
1979  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
1980 
1981  setlocale(LC_TIME, save);
1982  free(save);
1983 
1984  if (res == 0)
1985  return result;
1986 
1987  posM = strstr(buf, "11");
1988  posD = strstr(buf, "22");
1989  posY = strstr(buf, "33");
1990 
1991  if (!posM || !posD || !posY)
1992  return result;
1993 
1994  if (posY < posM && posM < posD)
1995  result = DATEORDER_YMD;
1996  else if (posD < posM)
1997  result = DATEORDER_DMY;
1998  else
1999  result = DATEORDER_MDY;
2000 
2001  return result;
2002 }
#define setlocale(a, b)
Definition: win32_port.h:446
static struct pg_tm tm
Definition: localtime.c:102
static char * buf
Definition: pg_test_fsync.c:68
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define DATEORDER_YMD
Definition: miscadmin.h:235
static size_t my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
Definition: initdb.c:1945
#define DATEORDER_DMY
Definition: miscadmin.h:236
#define DATEORDER_MDY
Definition: miscadmin.h:237
#define free(a)
Definition: header.h:65
static char * locale
Definition: initdb.c:126

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 2842 of file initdb.c.

References _, appendPQExpBuffer(), appendPQExpBufferStr(), appendShellString(), auth_methods_host, auth_methods_local, authmethodhost, authmethodlocal, authwarning, canonicalize_path(), check_authmethod_unspecified(), check_authmethod_valid(), check_need_password(), check_ok(), cleanup_directories_atexit(), createPQExpBuffer(), PQExpBufferData::data, data_checksums, debug, default_text_search_config, DEFAULT_XLOG_SEG_SIZE, destroyPQExpBuffer(), do_sync, encoding, extra_options, fprintf, get_id(), get_parent_directory(), get_progname(), get_restricted_token(), get_su_pwd(), getopt_long(), initialize_data_directory(), IsValidWalSegSize, join_path_components(), lc_collate, lc_ctype, lc_messages, lc_monetary, lc_numeric, lc_time, locale, make_native_path(), MAXPGPATH, no_argument, noclean, noinstructions, optarg, optind, pg_check_dir(), pg_data, PG_DIR_MODE_GROUP, PG_IOLBF, pg_log_error, pg_log_warning, pg_logging_init(), pg_strdup(), PG_TEXTDOMAIN, pgdata_native, printf, progname, psprintf(), pwfilename, pwprompt, required_argument, set_info_version(), set_pglocale_pgservice(), SetDataDirectoryCreatePerm(), setup_bin_paths(), setup_data_file_paths(), setup_locale_encoding(), setup_pgdata(), setup_text_search(), share_path, show_setting, generate_unaccent_rules::stdout, str_wal_segment_size_mb, strlcpy(), success, sync_only, usage(), username, wal_segment_size_mb, and xlog_dir.

2843 {
2844  static struct option long_options[] = {
2845  {"pgdata", required_argument, NULL, 'D'},
2846  {"encoding", required_argument, NULL, 'E'},
2847  {"locale", required_argument, NULL, 1},
2848  {"lc-collate", required_argument, NULL, 2},
2849  {"lc-ctype", required_argument, NULL, 3},
2850  {"lc-monetary", required_argument, NULL, 4},
2851  {"lc-numeric", required_argument, NULL, 5},
2852  {"lc-time", required_argument, NULL, 6},
2853  {"lc-messages", required_argument, NULL, 7},
2854  {"no-locale", no_argument, NULL, 8},
2855  {"text-search-config", required_argument, NULL, 'T'},
2856  {"auth", required_argument, NULL, 'A'},
2857  {"auth-local", required_argument, NULL, 10},
2858  {"auth-host", required_argument, NULL, 11},
2859  {"pwprompt", no_argument, NULL, 'W'},
2860  {"pwfile", required_argument, NULL, 9},
2861  {"username", required_argument, NULL, 'U'},
2862  {"help", no_argument, NULL, '?'},
2863  {"version", no_argument, NULL, 'V'},
2864  {"debug", no_argument, NULL, 'd'},
2865  {"show", no_argument, NULL, 's'},
2866  {"noclean", no_argument, NULL, 'n'}, /* for backwards compatibility */
2867  {"no-clean", no_argument, NULL, 'n'},
2868  {"nosync", no_argument, NULL, 'N'}, /* for backwards compatibility */
2869  {"no-sync", no_argument, NULL, 'N'},
2870  {"no-instructions", no_argument, NULL, 13},
2871  {"sync-only", no_argument, NULL, 'S'},
2872  {"waldir", required_argument, NULL, 'X'},
2873  {"wal-segsize", required_argument, NULL, 12},
2874  {"data-checksums", no_argument, NULL, 'k'},
2875  {"allow-group-access", no_argument, NULL, 'g'},
2876  {"discard-caches", no_argument, NULL, 14},
2877  {NULL, 0, NULL, 0}
2878  };
2879 
2880  /*
2881  * options with no short version return a low integer, the rest return
2882  * their short version value
2883  */
2884  int c;
2885  int option_index;
2886  char *effective_user;
2887  PQExpBuffer start_db_cmd;
2888  char pg_ctl_path[MAXPGPATH];
2889 
2890  /*
2891  * Ensure that buffering behavior of stdout matches what it is in
2892  * interactive usage (at least on most platforms). This prevents
2893  * unexpected output ordering when, eg, output is redirected to a file.
2894  * POSIX says we must do this before any other usage of these files.
2895  */
2896  setvbuf(stdout, NULL, PG_IOLBF, 0);
2897 
2898  pg_logging_init(argv[0]);
2899  progname = get_progname(argv[0]);
2900  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
2901 
2902  if (argc > 1)
2903  {
2904  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2905  {
2906  usage(progname);
2907  exit(0);
2908  }
2909  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2910  {
2911  puts("initdb (PostgreSQL) " PG_VERSION);
2912  exit(0);
2913  }
2914  }
2915 
2916  /* process command-line options */
2917 
2918  while ((c = getopt_long(argc, argv, "A:dD:E:gkL:nNsST:U:WX:", long_options, &option_index)) != -1)
2919  {
2920  switch (c)
2921  {
2922  case 'A':
2924 
2925  /*
2926  * When ident is specified, use peer for local connections.
2927  * Mirrored, when peer is specified, use ident for TCP/IP
2928  * connections.
2929  */
2930  if (strcmp(authmethodhost, "ident") == 0)
2931  authmethodlocal = "peer";
2932  else if (strcmp(authmethodlocal, "peer") == 0)
2933  authmethodhost = "ident";
2934  break;
2935  case 10:
2937  break;
2938  case 11:
2940  break;
2941  case 'D':
2943  break;
2944  case 'E':
2946  break;
2947  case 'W':
2948  pwprompt = true;
2949  break;
2950  case 'U':
2952  break;
2953  case 'd':
2954  debug = true;
2955  printf(_("Running in debug mode.\n"));
2956  break;
2957  case 'n':
2958  noclean = true;
2959  printf(_("Running in no-clean mode. Mistakes will not be cleaned up.\n"));
2960  break;
2961  case 'N':
2962  do_sync = false;
2963  break;
2964  case 'S':
2965  sync_only = true;
2966  break;
2967  case 'k':
2968  data_checksums = true;
2969  break;
2970  case 'L':
2972  break;
2973  case 1:
2974  locale = pg_strdup(optarg);
2975  break;
2976  case 2:
2978  break;
2979  case 3:
2981  break;
2982  case 4:
2984  break;
2985  case 5:
2987  break;
2988  case 6:
2990  break;
2991  case 7:
2993  break;
2994  case 8:
2995  locale = "C";
2996  break;
2997  case 9:
2999  break;
3000  case 's':
3001  show_setting = true;
3002  break;
3003  case 'T':
3005  break;
3006  case 'X':
3008  break;
3009  case 12:
3011  break;
3012  case 13:
3013  noinstructions = true;
3014  break;
3015  case 'g':
3017  break;
3018  case 14:
3019  extra_options = psprintf("%s %s",
3020  extra_options,
3021  "-c debug_discard_caches=1");
3022  break;
3023  default:
3024  /* getopt_long already emitted a complaint */
3025  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3026  progname);
3027  exit(1);
3028  }
3029  }
3030 
3031 
3032  /*
3033  * Non-option argument specifies data directory as long as it wasn't
3034  * already specified with -D / --pgdata
3035  */
3036  if (optind < argc && !pg_data)
3037  {
3038  pg_data = pg_strdup(argv[optind]);
3039  optind++;
3040  }
3041 
3042  if (optind < argc)
3043  {
3044  pg_log_error("too many command-line arguments (first is \"%s\")",
3045  argv[optind]);
3046  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
3047  progname);
3048  exit(1);
3049  }
3050 
3052 
3053  /* If we only need to fsync, just do it and exit */
3054  if (sync_only)
3055  {
3056  setup_pgdata();
3057 
3058  /* must check that directory is readable */
3059  if (pg_check_dir(pg_data) <= 0)
3060  {
3061  pg_log_error("could not access directory \"%s\": %m", pg_data);
3062  exit(1);
3063  }
3064 
3065  fputs(_("syncing data to disk ... "), stdout);
3066  fflush(stdout);
3067  fsync_pgdata(pg_data, PG_VERSION_NUM);
3068  check_ok();
3069  return 0;
3070  }
3071 
3072  if (pwprompt && pwfilename)
3073  {
3074  pg_log_error("password prompt and password file cannot be specified together");
3075  exit(1);
3076  }
3077 
3080 
3083 
3085 
3086  /* set wal segment size */
3087  if (str_wal_segment_size_mb == NULL)
3088  wal_segment_size_mb = (DEFAULT_XLOG_SEG_SIZE) / (1024 * 1024);
3089  else
3090  {
3091  char *endptr;
3092 
3093  /* check that the argument is a number */
3094  wal_segment_size_mb = strtol(str_wal_segment_size_mb, &endptr, 10);
3095 
3096  /* verify that wal segment size is valid */
3097  if (endptr == str_wal_segment_size_mb || *endptr != '\0')
3098  {
3099  pg_log_error("argument of --wal-segsize must be a number");
3100  exit(1);
3101  }
3102  if (!IsValidWalSegSize(wal_segment_size_mb * 1024 * 1024))
3103  {
3104  pg_log_error("argument of --wal-segsize must be a power of 2 between 1 and 1024");
3105  exit(1);
3106  }
3107  }
3108 
3110 
3111  setup_pgdata();
3112 
3113  setup_bin_paths(argv[0]);
3114 
3115  effective_user = get_id();
3116  if (!username)
3117  username = effective_user;
3118 
3119  if (strncmp(username, "pg_", 3) == 0)
3120  {
3121  pg_log_error("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
3122  exit(1);
3123  }
3124 
3125  printf(_("The files belonging to this database system will be owned "
3126  "by user \"%s\".\n"
3127  "This user must also own the server process.\n\n"),
3128  effective_user);
3129 
3130  set_info_version();
3131 
3133 
3135 
3137 
3138  printf("\n");
3139 
3140  if (data_checksums)
3141  printf(_("Data page checksums are enabled.\n"));
3142  else
3143  printf(_("Data page checksums are disabled.\n"));
3144 
3145  if (pwprompt || pwfilename)
3146  get_su_pwd();
3147 
3148  printf("\n");
3149 
3151 
3152  if (do_sync)
3153  {
3154  fputs(_("syncing data to disk ... "), stdout);
3155  fflush(stdout);
3156  fsync_pgdata(pg_data, PG_VERSION_NUM);
3157  check_ok();
3158  }
3159  else
3160  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3161 
3162  if (authwarning)
3163  {
3164  printf("\n");
3165  pg_log_warning("enabling \"trust\" authentication for local connections");
3166  fprintf(stderr, _("You can change this by editing pg_hba.conf or using the option -A, or\n"
3167  "--auth-local and --auth-host, the next time you run initdb.\n"));
3168  }
3169 
3170  if (!noinstructions)
3171  {
3172  /*
3173  * Build up a shell command to tell the user how to start the server
3174  */
3175  start_db_cmd = createPQExpBuffer();
3176 
3177  /* Get directory specification used to start initdb ... */
3178  strlcpy(pg_ctl_path, argv[0], sizeof(pg_ctl_path));
3179  canonicalize_path(pg_ctl_path);
3180  get_parent_directory(pg_ctl_path);
3181  /* ... and tag on pg_ctl instead */
3182  join_path_components(pg_ctl_path, pg_ctl_path, "pg_ctl");
3183 
3184  /* Convert the path to use native separators */
3185  make_native_path(pg_ctl_path);
3186 
3187  /* path to pg_ctl, properly quoted */
3188  appendShellString(start_db_cmd, pg_ctl_path);
3189 
3190  /* add -D switch, with properly quoted data directory */
3191  appendPQExpBufferStr(start_db_cmd, " -D ");
3192  appendShellString(start_db_cmd, pgdata_native);
3193 
3194  /* add suggested -l switch and "start" command */
3195  /* translator: This is a placeholder in a shell command. */
3196  appendPQExpBuffer(start_db_cmd, " -l %s start", _("logfile"));
3197 
3198  printf(_("\nSuccess. You can now start the database server using:\n\n"
3199  " %s\n\n"),
3200  start_db_cmd->data);
3201 
3202  destroyPQExpBuffer(start_db_cmd);
3203  }
3204 
3205 
3206  success = true;
3207  return 0;
3208 }
static char * lc_monetary
Definition: initdb.c:129
#define IsValidWalSegSize(size)
Definition: xlog_internal.h:96
static void cleanup_directories_atexit(void)
Definition: initdb.c:549
void setup_data_file_paths(void)
Definition: initdb.c:2430
void setup_locale_encoding(void)
Definition: initdb.c:2346
static bool debug
Definition: initdb.c:140
static char * lc_collate
Definition: initdb.c:127
const char * get_progname(const char *argv0)
Definition: path.c:453
#define pg_log_error(...)
Definition: logging.h:80
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
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
void make_native_path(char *path)
Definition: path.c:166
#define DEFAULT_XLOG_SEG_SIZE
void canonicalize_path(char *path)
Definition: path.c:254
#define printf(...)
Definition: port.h:223
static bool pwprompt
Definition: initdb.c:135
static char * pgdata_native
Definition: initdb.c:174
static void get_su_pwd(void)
Definition: initdb.c:1460
#define fprintf
Definition: port.h:221
static char * get_id(void)
Definition: initdb.c:602
static char * share_path
Definition: initdb.c:121
static const char * authmethodlocal
Definition: initdb.c:139
static char * lc_time
Definition: initdb.c:131
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
static void check_authmethod_unspecified(const char **authmethod)
Definition: initdb.c:2213
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:50
static bool authwarning
Definition: initdb.c:190
static char * lc_messages
Definition: initdb.c:132
#define MAXPGPATH
static const char * default_text_search_config
Definition: initdb.c:133
static char * lc_ctype
Definition: initdb.c:128
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static char * lc_numeric
Definition: initdb.c:130
char * c
void initialize_data_directory(void)
Definition: initdb.c:2726
static int wal_segment_size_mb
Definition: initdb.c:149
void get_parent_directory(char *path)
Definition: path.c:854
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * pg_data
Definition: initdb.c:124
static char * pwfilename
Definition: initdb.c:136
static void check_ok(void)
Definition: initdb.c:1920
void setup_bin_paths(const char *argv0)
Definition: initdb.c:2301
static const char * progname
Definition: initdb.c:153
#define no_argument
Definition: getopt_long.h:24
static char * extra_options
Definition: initdb.c:206
static char * xlog_dir
Definition: initdb.c:147
#define PG_DIR_MODE_GROUP
Definition: file_perm.h:35
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1215
static bool data_checksums
Definition: initdb.c:146
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
#define PG_IOLBF
Definition: port.h:345
static char * username
Definition: initdb.c:134
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:429
static char * encoding
Definition: initdb.c:125
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void setup_text_search(void)
Definition: initdb.c:2474
static char * str_wal_segment_size_mb
Definition: initdb.c:148
static bool do_sync
Definition: initdb.c:143
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
static const char *const auth_methods_host[]
Definition: initdb.c:82
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:433
char * optarg
Definition: getopt.c:52
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:31
static void usage(const char *progname)
Definition: initdb.c:2168
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
static void check_need_password(const char *authmethodlocal, const char *authmethodhost)
Definition: initdb.c:2243
static char * locale
Definition: initdb.c:126
static const char * authmethodhost
Definition: initdb.c:138
static bool sync_only
Definition: initdb.c:144
#define pg_log_warning(...)
Definition: pgfnames.c:24
static const char *const auth_methods_local[]
Definition: initdb.c:104
static bool success
Definition: initdb.c:165
static void check_authmethod_valid(const char *authmethod, const char *const *valid_methods, const char *conntype)
Definition: initdb.c:2223
void setup_pgdata(void)
Definition: initdb.c:2260
#define _(x)
Definition: elog.c:89
static void set_info_version(void)
Definition: initdb.c:1770
static bool show_setting
Definition: initdb.c:145
static bool noinstructions
Definition: initdb.c:142
static bool noclean
Definition: initdb.c:141

◆ make_postgres()

static void make_postgres ( FILE *  cmdfd)
static

Definition at line 1874 of file initdb.c.

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

1875 {
1876  const char *const *line;
1877  static const char *const postgres_setup[] = {
1878  "CREATE DATABASE postgres;\n\n",
1879  "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",
1880  NULL
1881  };
1882 
1883  for (line = postgres_setup; *line; line++)
1884  PG_CMD_PUTS(*line);
1885 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ make_template0()

static void make_template0 ( FILE *  cmdfd)
static

Definition at line 1836 of file initdb.c.

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

1837 {
1838  const char *const *line;
1839  static const char *const template0_setup[] = {
1840  "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false;\n\n",
1841 
1842  /*
1843  * We use the OID of template0 to determine datlastsysoid
1844  */
1845  "UPDATE pg_database SET datlastsysoid = "
1846  " (SELECT oid FROM pg_database "
1847  " WHERE datname = 'template0');\n\n",
1848 
1849  /*
1850  * Explicitly revoke public create-schema and create-temp-table
1851  * privileges in template1 and template0; else the latter would be on
1852  * by default
1853  */
1854  "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n",
1855  "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n",
1856 
1857  "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n",
1858 
1859  /*
1860  * Finally vacuum to clean up dead rows in pg_database
1861  */
1862  "VACUUM pg_database;\n\n",
1863  NULL
1864  };
1865 
1866  for (line = template0_setup; *line; line++)
1867  PG_CMD_PUTS(*line);
1868 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ my_strftime()

static size_t my_strftime ( char *  s,
size_t  max,
const char *  fmt,
const struct tm tm 
)
inlinestatic

Definition at line 1945 of file initdb.c.

Referenced by locale_date_order().

1946 {
1947  return strftime(s, max, fmt, tm);
1948 }
static struct pg_tm tm
Definition: localtime.c:102

◆ popen_check()

static FILE * popen_check ( const char *  command,
const char *  mode 
)
static

Definition at line 531 of file initdb.c.

References pg_log_error, and generate_unaccent_rules::stdout.

532 {
533  FILE *cmdfd;
534 
535  fflush(stdout);
536  fflush(stderr);
537  errno = 0;
538  cmdfd = popen(command, mode);
539  if (cmdfd == NULL)
540  pg_log_error("could not execute command \"%s\": %m", command);
541  return cmdfd;
542 }
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define pg_log_error(...)
Definition: logging.h:80

◆ pretty_wal_size()

static char* pretty_wal_size ( int  segment_count)
static

Definition at line 1034 of file initdb.c.

References pg_malloc(), snprintf, and wal_segment_size_mb.

Referenced by setup_config().

1035 {
1036  int sz = wal_segment_size_mb * segment_count;
1037  char *result = pg_malloc(14);
1038 
1039  if ((sz % 1024) == 0)
1040  snprintf(result, 14, "%dGB", sz / 1024);
1041  else
1042  snprintf(result, 14, "%dMB", sz);
1043 
1044  return result;
1045 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static int wal_segment_size_mb
Definition: initdb.c:149
#define snprintf
Definition: port.h:217

◆ readfile()

static char ** readfile ( const char *  path)
static

Definition at line 454 of file initdb.c.

References StringInfoData::data, infile(), initStringInfo(), pfree(), pg_get_line_buf(), pg_log_error, pg_malloc(), pg_realloc(), and pg_strdup().

Referenced by bootstrap_template1(), setup_config(), and setup_run_file().

455 {
456  char **result;
457  FILE *infile;
458  StringInfoData line;
459  int maxlines;
460  int n;
461 
462  if ((infile = fopen(path, "r")) == NULL)
463  {
464  pg_log_error("could not open file \"%s\" for reading: %m", path);
465  exit(1);
466  }
467 
468  initStringInfo(&line);
469 
470  maxlines = 1024;
471  result = (char **) pg_malloc(maxlines * sizeof(char *));
472 
473  n = 0;
474  while (pg_get_line_buf(infile, &line))
475  {
476  /* make sure there will be room for a trailing NULL pointer */
477  if (n >= maxlines - 1)
478  {
479  maxlines *= 2;
480  result = (char **) pg_realloc(result, maxlines * sizeof(char *));
481  }
482 
483  result[n++] = pg_strdup(line.data);
484  }
485  result[n] = NULL;
486 
487  pfree(line.data);
488 
489  fclose(infile);
490 
491  return result;
492 }
bool pg_get_line_buf(FILE *stream, StringInfo buf)
Definition: pg_get_line.c:88
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define pg_log_error(...)
Definition: logging.h:80
void pfree(void *pointer)
Definition: mcxt.c:1169
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static void infile(const char *filename)
Definition: zic.c:1241

◆ replace_token()

static char ** replace_token ( char **  lines,
const char *  token,
const char *  replacement 
)
static

Definition at line 371 of file initdb.c.

References i, newline(), and pg_malloc().

Referenced by bootstrap_template1(), setup_config(), and setup_privileges().

372 {
373  int numlines = 1;
374  int i;
375  char **result;
376  int toklen,
377  replen,
378  diff;
379 
380  for (i = 0; lines[i]; i++)
381  numlines++;
382 
383  result = (char **) pg_malloc(numlines * sizeof(char *));
384 
385  toklen = strlen(token);
386  replen = strlen(replacement);
387  diff = replen - toklen;
388 
389  for (i = 0; i < numlines; i++)
390  {
391  char *where;
392  char *newline;
393  int pre;
394 
395  /* just copy pointer if NULL or no change needed */
396  if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
397  {
398  result[i] = lines[i];
399  continue;
400  }
401 
402  /* if we get here a change is needed - set up new line */
403 
404  newline = (char *) pg_malloc(strlen(lines[i]) + diff + 1);
405 
406  pre = where - lines[i];
407 
408  memcpy(newline, lines[i], pre);
409 
410  memcpy(newline + pre, replacement, replen);
411 
412  strcpy(newline + pre + replen, lines[i] + pre + toklen);
413 
414  result[i] = newline;
415  }
416 
417  return result;
418 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static chr newline(void)
Definition: regc_lex.c:1001
int i

◆ select_default_timezone()

const char* select_default_timezone ( const char *  share_path)

Definition at line 1757 of file findtimezone.c.

References identify_system_timezone(), snprintf, tzdirpath, and validate_zone().

Referenced by test_config_settings().

1758 {
1759  const char *tzname;
1760 
1761  /* Initialize timezone directory path, if needed */
1762 #ifndef SYSTEMTZDIR
1763  snprintf(tzdirpath, sizeof(tzdirpath), "%s/timezone", share_path);
1764 #endif
1765 
1766  /* Check TZ environment variable */
1767  tzname = getenv("TZ");
1768  if (validate_zone(tzname))
1769  return tzname;
1770 
1771  /* Nope, so try to identify the system timezone */
1772  tzname = identify_system_timezone();
1773  if (validate_zone(tzname))
1774  return tzname;
1775 
1776  return NULL;
1777 }
static bool validate_zone(const char *tzname)
static char * share_path
Definition: initdb.c:121
static char tzdirpath[MAXPGPATH]
Definition: findtimezone.c:27
static const char * identify_system_timezone(void)
Definition: findtimezone.c:331
#define snprintf
Definition: port.h:217

◆ set_info_version()

static void set_info_version ( void  )
static

Definition at line 1770 of file initdb.c.

References infoversion, pg_strdup(), and snprintf.

Referenced by main().

1771 {
1772  char *letterversion;
1773  long major = 0,
1774  minor = 0,
1775  micro = 0;
1776  char *endptr;
1777  char *vstr = pg_strdup(PG_VERSION);
1778  char *ptr;
1779 
1780  ptr = vstr + (strlen(vstr) - 1);
1781  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1782  ptr--;
1783  letterversion = ptr + 1;
1784  major = strtol(vstr, &endptr, 10);
1785  if (*endptr)
1786  minor = strtol(endptr + 1, &endptr, 10);
1787  if (*endptr)
1788  micro = strtol(endptr + 1, &endptr, 10);
1789  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1790  major, minor, micro, letterversion);
1791 }
static char infoversion[100]
Definition: initdb.c:170
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define snprintf
Definition: port.h:217

◆ set_input()

static void set_input ( char **  dest,
const char *  filename 
)
static

Definition at line 772 of file initdb.c.

References psprintf(), and share_path.

Referenced by setup_data_file_paths().

773 {
774  *dest = psprintf("%s/%s", share_path, filename);
775 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static char * share_path
Definition: initdb.c:121
static char * filename
Definition: pg_dumpall.c:92

◆ set_null_conf()

static void set_null_conf ( void  )
static

Definition at line 847 of file initdb.c.

References conf_file, free, PG_BINARY_W, pg_data, pg_log_error, and psprintf().

Referenced by initialize_data_directory().

848 {
849  FILE *conf_file;
850  char *path;
851 
852  path = psprintf("%s/postgresql.conf", pg_data);
853  conf_file = fopen(path, PG_BINARY_W);
854  if (conf_file == NULL)
855  {
856  pg_log_error("could not open file \"%s\" for writing: %m", path);
857  exit(1);
858  }
859  if (fclose(conf_file))
860  {
861  pg_log_error("could not write file \"%s\": %m", path);
862  exit(1);
863  }
864  free(path);
865 }
static char * conf_file
Definition: initdb.c:158
#define pg_log_error(...)
Definition: logging.h:80
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define PG_BINARY_W
Definition: c.h:1274
static char * pg_data
Definition: initdb.c:124
#define free(a)
Definition: header.h:65

◆ setlocales()

static void setlocales ( void  )
static

Definition at line 2117 of file initdb.c.

References check_locale_name(), lc_collate, lc_ctype, lc_messages, lc_monetary, lc_numeric, lc_time, and locale.

Referenced by setup_locale_encoding().

2118 {
2119  char *canonname;
2120 
2121  /* set empty lc_* values to locale config if set */
2122 
2123  if (locale)
2124  {
2125  if (!lc_ctype)
2126  lc_ctype = locale;
2127  if (!lc_collate)
2128  lc_collate = locale;
2129  if (!lc_numeric)
2130  lc_numeric = locale;
2131  if (!lc_time)
2132  lc_time = locale;
2133  if (!lc_monetary)
2134  lc_monetary = locale;
2135  if (!lc_messages)
2136  lc_messages = locale;
2137  }
2138 
2139  /*
2140  * canonicalize locale names, and obtain any missing values from our
2141  * current environment
2142  */
2143 
2144  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2145  lc_ctype = canonname;
2146  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2147  lc_collate = canonname;
2148  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2149  lc_numeric = canonname;
2150  check_locale_name(LC_TIME, lc_time, &canonname);
2151  lc_time = canonname;
2152  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2153  lc_monetary = canonname;
2154 #if defined(LC_MESSAGES) && !defined(WIN32)
2155  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2156  lc_messages = canonname;
2157 #else
2158  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2159  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2160  lc_messages = canonname;
2161 #endif
2162 }
static char * lc_monetary
Definition: initdb.c:129
static char * lc_collate
Definition: initdb.c:127
static char * lc_time
Definition: initdb.c:131
static char * lc_messages
Definition: initdb.c:132
static char * lc_ctype
Definition: initdb.c:128
static char * lc_numeric
Definition: initdb.c:130
static void check_locale_name(int category, const char *locale, char **canonname)
Definition: initdb.c:2017
static char * locale
Definition: initdb.c:126

◆ setup_auth()

static void setup_auth ( FILE *  cmdfd)
static

Definition at line 1436 of file initdb.c.

References escape_quotes(), PG_CMD_PRINTF, PG_CMD_PUTS, superuser_password, and username.

Referenced by initialize_data_directory().

1437 {
1438  const char *const *line;
1439  static const char *const pg_authid_setup[] = {
1440  /*
1441  * The authid table shouldn't be readable except through views, to
1442  * ensure passwords are not publicly visible.
1443  */
1444  "REVOKE ALL ON pg_authid FROM public;\n\n",
1445  NULL
1446  };
1447 
1448  for (line = pg_authid_setup; *line != NULL; line++)
1449  PG_CMD_PUTS(*line);
1450 
1451  if (superuser_password)
1452  PG_CMD_PRINTF("ALTER USER \"%s\" WITH PASSWORD E'%s';\n\n",
1454 }
#define PG_CMD_PRINTF(fmt,...)
Definition: initdb.c:314
#define PG_CMD_PUTS(line)
Definition: initdb.c:308
static char * username
Definition: initdb.c:134
static char * superuser_password
Definition: initdb.c:137
static char * escape_quotes(const char *src)
Definition: initdb.c:325

◆ setup_bin_paths()

void setup_bin_paths ( const char *  argv0)

Definition at line 2301 of file initdb.c.

References backend_exec, bin_path, canonicalize_path(), find_my_exec(), find_other_exec(), get_share_path(), is_absolute_path, last_dir_separator(), MAXPGPATH, PG_BACKEND_VERSIONSTR, pg_log_error, pg_malloc(), progname, share_path, and strlcpy().

Referenced by main().

2302 {
2303  int ret;
2304 
2305  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2306  backend_exec)) < 0)
2307  {
2308  char full_path[MAXPGPATH];
2309 
2310  if (find_my_exec(argv0, full_path) < 0)
2311  strlcpy(full_path, progname, sizeof(full_path));
2312 
2313  if (ret == -1)
2314  pg_log_error("The program \"%s\" is needed by %s but was not found in the\n"
2315  "same directory as \"%s\".\n"
2316  "Check your installation.",
2317  "postgres", progname, full_path);
2318  else
2319  pg_log_error("The program \"%s\" was found by \"%s\"\n"
2320  "but was not the same version as %s.\n"
2321  "Check your installation.",
2322  "postgres", full_path, progname);
2323  exit(1);
2324  }
2325 
2326  /* store binary directory */
2327  strcpy(bin_path, backend_exec);
2328  *last_dir_separator(bin_path) = '\0';
2330 
2331  if (!share_path)
2332  {
2335  }
2336  else if (!is_absolute_path(share_path))
2337  {
2338  pg_log_error("input file location must be an absolute path");
2339  exit(1);
2340  }
2341 
2343 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:322
static char * argv0
Definition: pg_ctl.c:97
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define pg_log_error(...)
Definition: logging.h:80
void canonicalize_path(char *path)
Definition: path.c:254
static char * share_path
Definition: initdb.c:121
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:127
#define is_absolute_path(filename)
Definition: port.h:86
static const char * progname
Definition: initdb.c:153
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define PG_BACKEND_VERSIONSTR
Definition: port.h:136
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static char bin_path[MAXPGPATH]
Definition: initdb.c:235
static char backend_exec[MAXPGPATH]
Definition: initdb.c:236
void get_share_path(const char *my_exec_path, char *ret_path)
Definition: path.c:704

◆ setup_collation()

static void setup_collation ( FILE *  cmdfd)
static

Definition at line 1585 of file initdb.c.

References PG_CMD_PRINTF, PG_CMD_PUTS, and PG_UTF8.

Referenced by initialize_data_directory().

1586 {
1587  /*
1588  * Add an SQL-standard name. We don't want to pin this, so it doesn't go
1589  * in pg_collation.h. But add it before reading system collations, so
1590  * that it wins if libc defines a locale named ucs_basic.
1591  */
1592  PG_CMD_PRINTF("INSERT INTO pg_collation (oid, collname, collnamespace, collowner, collprovider, collisdeterministic, collencoding, collcollate, collctype)"
1593  "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",
1594  BOOTSTRAP_SUPERUSERID, COLLPROVIDER_LIBC, PG_UTF8);
1595 
1596  /* Now import all collations we can find in the operating system */
1597  PG_CMD_PUTS("SELECT pg_import_system_collations('pg_catalog');\n\n");
1598 }
#define PG_CMD_PRINTF(fmt,...)
Definition: initdb.c:314
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ setup_config()

static void setup_config ( void  )
static

Definition at line 1051 of file initdb.c.

References _, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_canonname, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_NUMERICHOST, addrinfo::ai_protocol, addrinfo::ai_socktype, authmethodhost, authmethodlocal, AUTHTRUST_WARNING, check_ok(), conf_file, DATEORDER_DMY, DATEORDER_MDY, DATEORDER_YMD, DEFAULT_BACKEND_FLUSH_AFTER, DEFAULT_BGWRITER_FLUSH_AFTER, DEFAULT_CHECKPOINT_FLUSH_AFTER, DEFAULT_MAX_WAL_SEGS, DEFAULT_MIN_WAL_SEGS, DEFAULT_PGSOCKET_DIR, default_text_search_config, default_timezone, dynamic_shared_memory_type, escape_quotes(), filter_lines_with_token(), free, getaddrinfo, hba_file, ident_file, lc_messages, lc_monetary, lc_numeric, lc_time, locale_date_order(), MAXPGPATH, n_buffers, n_connections, pg_data, pg_dir_create_mode, PG_DIR_MODE_GROUP, pg_file_create_mode, pg_log_error, pg_strdup(), pretty_wal_size(), readfile(), replace_token(), snprintf, sprintf, generate_unaccent_rules::stdout, and writefile().

Referenced by initialize_data_directory().

1052 {
1053  char **conflines;
1054  char repltok[MAXPGPATH];
1055  char path[MAXPGPATH];
1056  char *autoconflines[3];
1057 
1058  fputs(_("creating configuration files ... "), stdout);
1059  fflush(stdout);
1060 
1061  /* postgresql.conf */
1062 
1063  conflines = readfile(conf_file);
1064 
1065  snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1066  conflines = replace_token(conflines, "#max_connections = 100", repltok);
1067 
1068  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1069  snprintf(repltok, sizeof(repltok), "shared_buffers = %dMB",
1070  (n_buffers * (BLCKSZ / 1024)) / 1024);
1071  else
1072  snprintf(repltok, sizeof(repltok), "shared_buffers = %dkB",
1073  n_buffers * (BLCKSZ / 1024));
1074  conflines = replace_token(conflines, "#shared_buffers = 128MB", repltok);
1075 
1076 #ifdef HAVE_UNIX_SOCKETS
1077  snprintf(repltok, sizeof(repltok), "#unix_socket_directories = '%s'",
1079 #else
1080  snprintf(repltok, sizeof(repltok), "#unix_socket_directories = ''");
1081 #endif
1082  conflines = replace_token(conflines, "#unix_socket_directories = '/tmp'",
1083  repltok);
1084 
1085 #if DEF_PGPORT != 5432
1086  snprintf(repltok, sizeof(repltok), "#port = %d", DEF_PGPORT);
1087  conflines = replace_token(conflines, "#port = 5432", repltok);
1088 #endif
1089 
1090  /* set default max_wal_size and min_wal_size */
1091  snprintf(repltok, sizeof(repltok), "min_wal_size = %s",
1093  conflines = replace_token(conflines, "#min_wal_size = 80MB", repltok);
1094 
1095  snprintf(repltok, sizeof(repltok), "max_wal_size = %s",
1097  conflines = replace_token(conflines, "#max_wal_size = 1GB", repltok);
1098 
1099  snprintf(repltok, sizeof(repltok), "lc_messages = '%s'",
1101  conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1102 
1103  snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'",
1105  conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1106 
1107  snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'",
1109  conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1110 
1111  snprintf(repltok, sizeof(repltok), "lc_time = '%s'",
1113  conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1114 
1115  switch (locale_date_order(lc_time))
1116  {
1117  case DATEORDER_YMD:
1118  strcpy(repltok, "datestyle = 'iso, ymd'");
1119  break;
1120  case DATEORDER_DMY:
1121  strcpy(repltok, "datestyle = 'iso, dmy'");
1122  break;
1123  case DATEORDER_MDY:
1124  default:
1125  strcpy(repltok, "datestyle = 'iso, mdy'");
1126  break;
1127  }
1128  conflines = replace_token(conflines, "#datestyle = 'iso, mdy'", repltok);
1129 
1130  snprintf(repltok, sizeof(repltok),
1131  "default_text_search_config = 'pg_catalog.%s'",
1133  conflines = replace_token(conflines,
1134  "#default_text_search_config = 'pg_catalog.simple'",
1135  repltok);
1136 
1137  if (default_timezone)
1138  {
1139  snprintf(repltok, sizeof(repltok), "timezone = '%s'",
1141  conflines = replace_token(conflines, "#timezone = 'GMT'", repltok);
1142  snprintf(repltok, sizeof(repltok), "log_timezone = '%s'",
1144  conflines = replace_token(conflines, "#log_timezone = 'GMT'", repltok);
1145  }
1146 
1147  snprintf(repltok, sizeof(repltok), "dynamic_shared_memory_type = %s",
1149  conflines = replace_token(conflines, "#dynamic_shared_memory_type = posix",
1150  repltok);
1151 
1152 #if DEFAULT_BACKEND_FLUSH_AFTER > 0
1153  snprintf(repltok, sizeof(repltok), "#backend_flush_after = %dkB",
1154  DEFAULT_BACKEND_FLUSH_AFTER * (BLCKSZ / 1024));
1155  conflines = replace_token(conflines, "#backend_flush_after = 0",
1156  repltok);
1157 #endif
1158 
1159 #if DEFAULT_BGWRITER_FLUSH_AFTER > 0
1160  snprintf(repltok, sizeof(repltok), "#bgwriter_flush_after = %dkB",
1161  DEFAULT_BGWRITER_FLUSH_AFTER * (BLCKSZ / 1024));
1162  conflines = replace_token(conflines, "#bgwriter_flush_after = 0",
1163  repltok);
1164 #endif
1165 
1166 #if DEFAULT_CHECKPOINT_FLUSH_AFTER > 0
1167  snprintf(repltok, sizeof(repltok), "#checkpoint_flush_after = %dkB",
1168  DEFAULT_CHECKPOINT_FLUSH_AFTER * (BLCKSZ / 1024));
1169  conflines = replace_token(conflines, "#checkpoint_flush_after = 0",
1170  repltok);
1171 #endif
1172 
1173 #ifndef USE_PREFETCH
1174  conflines = replace_token(conflines,
1175  "#effective_io_concurrency = 1",
1176  "#effective_io_concurrency = 0");
1177 #endif
1178 
1179 #ifdef WIN32
1180  conflines = replace_token(conflines,
1181  "#update_process_title = on",
1182  "#update_process_title = off");
1183 #endif
1184 
1185  /*
1186  * Change password_encryption setting to md5 if md5 was chosen as an
1187  * authentication method, unless scram-sha-256 was also chosen.
1188  */
1189  if ((strcmp(authmethodlocal, "md5") == 0 &&
1190  strcmp(authmethodhost, "scram-sha-256") != 0) ||
1191  (strcmp(authmethodhost, "md5") == 0 &&
1192  strcmp(authmethodlocal, "scram-sha-256") != 0))
1193  {
1194  conflines = replace_token(conflines,
1195  "#password_encryption = scram-sha-256",
1196  "password_encryption = md5");
1197  }
1198 
1199  /*
1200  * If group access has been enabled for the cluster then it makes sense to
1201  * ensure that the log files also allow group access. Otherwise a backup
1202  * from a user in the group would fail if the log files were not
1203  * relocated.
1204  */
1206  {
1207  conflines = replace_token(conflines,
1208  "#log_file_mode = 0600",
1209  "log_file_mode = 0640");
1210  }
1211 
1212  snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1213 
1214  writefile(path, conflines);
1215  if (chmod(path, pg_file_create_mode) != 0)
1216  {
1217  pg_log_error("could not change permissions of \"%s\": %m", path);
1218  exit(1);
1219  }
1220 
1221  /*
1222  * create the automatic configuration file to store the configuration
1223  * parameters set by ALTER SYSTEM command. The parameters present in this
1224  * file will override the value of parameters that exists before parse of
1225  * this file.
1226  */
1227  autoconflines[0] = pg_strdup("# Do not edit this file manually!\n");
1228  autoconflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
1229  autoconflines[2] = NULL;
1230 
1231  sprintf(path, "%s/postgresql.auto.conf", pg_data);
1232 
1233  writefile(path, autoconflines);
1234  if (chmod(path, pg_file_create_mode) != 0)
1235  {
1236  pg_log_error("could not change permissions of \"%s\": %m", path);
1237  exit(1);
1238  }
1239 
1240  free(conflines);
1241 
1242 
1243  /* pg_hba.conf */
1244 
1245  conflines = readfile(hba_file);
1246 
1247 #ifndef HAVE_UNIX_SOCKETS
1248  conflines = filter_lines_with_token(conflines, "@remove-line-for-nolocal@");
1249 #else
1250  conflines = replace_token(conflines, "@remove-line-for-nolocal@", "");
1251 #endif
1252 
1253 #ifdef HAVE_IPV6
1254 
1255  /*
1256  * Probe to see if there is really any platform support for IPv6, and
1257  * comment out the relevant pg_hba line if not. This avoids runtime
1258  * warnings if getaddrinfo doesn't actually cope with IPv6. Particularly
1259  * useful on Windows, where executables built on a machine with IPv6 may
1260  * have to run on a machine without.
1261  */
1262  {
1263  struct addrinfo *gai_result;
1264  struct addrinfo hints;
1265  int err = 0;
1266 
1267 #ifdef WIN32
1268  /* need to call WSAStartup before calling getaddrinfo */
1269  WSADATA wsaData;
1270 
1271  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
1272 #endif
1273 
1274  /* for best results, this code should match parse_hba_line() */
1275  hints.ai_flags = AI_NUMERICHOST;
1276  hints.ai_family = AF_UNSPEC;
1277  hints.ai_socktype = 0;
1278  hints.ai_protocol = 0;
1279  hints.ai_addrlen = 0;
1280  hints.ai_canonname = NULL;
1281  hints.ai_addr = NULL;
1282  hints.ai_next = NULL;
1283 
1284  if (err != 0 ||
1285  getaddrinfo("::1", NULL, &hints, &gai_result) != 0)
1286  {
1287  conflines = replace_token(conflines,
1288  "host all all ::1",
1289  "#host all all ::1");
1290  conflines = replace_token(conflines,
1291  "host replication all ::1",
1292  "#host replication all ::1");
1293  }
1294  }
1295 #else /* !HAVE_IPV6 */
1296  /* If we didn't compile IPV6 support at all, always comment it out */
1297  conflines = replace_token(conflines,
1298  "host all all ::1",
1299  "#host all all ::1");
1300  conflines = replace_token(conflines,
1301  "host replication all ::1",
1302  "#host replication all ::1");
1303 #endif /* HAVE_IPV6 */
1304 
1305  /* Replace default authentication methods */
1306  conflines = replace_token(conflines,
1307  "@authmethodhost@",
1308  authmethodhost);
1309  conflines = replace_token(conflines,
1310  "@authmethodlocal@",
1311  authmethodlocal);
1312 
1313  conflines = replace_token(conflines,
1314  "@authcomment@",
1315  (strcmp(authmethodlocal, "trust") == 0 || strcmp(authmethodhost, "trust") == 0) ? AUTHTRUST_WARNING : "");
1316 
1317  snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1318 
1319  writefile(path, conflines);
1320  if (chmod(path, pg_file_create_mode) != 0)
1321  {
1322  pg_log_error("could not change permissions of \"%s\": %m", path);
1323  exit(1);
1324  }
1325 
1326  free(conflines);
1327 
1328  /* pg_ident.conf */
1329 
1330  conflines = readfile(ident_file);
1331 
1332  snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1333 
1334  writefile(path, conflines);
1335  if (chmod(path, pg_file_create_mode) != 0)
1336  {
1337  pg_log_error("could not change permissions of \"%s\": %m", path);
1338  exit(1);
1339  }
1340 
1341  free(conflines);
1342 
1343  check_ok();
1344 }
static const char * default_timezone
Definition: initdb.c:180
static char * lc_monetary
Definition: initdb.c:129
#define getaddrinfo
Definition: getaddrinfo.h:136
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:371
int pg_file_create_mode
Definition: file_perm.c:19
#define DEFAULT_CHECKPOINT_FLUSH_AFTER
static char * conf_file
Definition: initdb.c:158
#define pg_log_error(...)
Definition: logging.h:80
#define DEFAULT_BGWRITER_FLUSH_AFTER
#define AUTHTRUST_WARNING
Definition: initdb.c:185
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
static const char * authmethodlocal
Definition: initdb.c:139
static char * lc_time
Definition: initdb.c:131
#define sprintf
Definition: port.h:219
static int n_connections
Definition: initdb.c:177
static char * lc_messages
Definition: initdb.c:132
#define MAXPGPATH
static const char * default_text_search_config
Definition: initdb.c:133
static char * lc_numeric
Definition: initdb.c:130
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * pg_data
Definition: initdb.c:124
static void check_ok(void)
Definition: initdb.c:1920
#define DEFAULT_MAX_WAL_SEGS
Definition: xlog_internal.h:92
#define DATEORDER_YMD
Definition: miscadmin.h:235
int pg_dir_create_mode
Definition: file_perm.c:18
#define PG_DIR_MODE_GROUP
Definition: file_perm.h:35
static int locale_date_order(const char *locale)
Definition: initdb.c:1954
#define DATEORDER_DMY
Definition: miscadmin.h:236
static char * pretty_wal_size(int segment_count)
Definition: initdb.c:1034
#define DATEORDER_MDY
Definition: miscadmin.h:237
#define free(a)
Definition: header.h:65
static char ** filter_lines_with_token(char **lines, const char *token)
Definition: initdb.c:427
static int n_buffers
Definition: initdb.c:178
static char * escape_quotes(const char *src)
Definition: initdb.c:325
static const char * dynamic_shared_memory_type
Definition: initdb.c:179
static void writefile(char *path, char **lines)
Definition: initdb.c:501
static char * ident_file
Definition: initdb.c:157
static char ** readfile(const char *path)
Definition: initdb.c:454
static const char * authmethodhost
Definition: initdb.c:138
#define snprintf
Definition: port.h:217
#define _(x)
Definition: elog.c:89
#define DEFAULT_MIN_WAL_SEGS
Definition: xlog_internal.h:91
static char * hba_file
Definition: initdb.c:156
#define DEFAULT_BACKEND_FLUSH_AFTER
#define DEFAULT_PGSOCKET_DIR

◆ setup_data_file_paths()

void setup_data_file_paths ( void  )

Definition at line 2430 of file initdb.c.

References bin_path, bki_file, check_input(), conf_file, debug, dictionary_file, features_file, fprintf, hba_file, ident_file, info_schema_file, pg_data, set_input(), share_path, show_setting, system_constraints_file, system_functions_file, system_views_file, and username.

Referenced by main().

2431 {
2432  set_input(&bki_file, "postgres.bki");
2433  set_input(&hba_file, "pg_hba.conf.sample");
2434  set_input(&ident_file, "pg_ident.conf.sample");
2435  set_input(&conf_file, "postgresql.conf.sample");
2436  set_input(&dictionary_file, "snowball_create.sql");
2437  set_input(&info_schema_file, "information_schema.sql");
2438  set_input(&features_file, "sql_features.txt");
2439  set_input(&system_constraints_file, "system_constraints.sql");
2440  set_input(&system_functions_file, "system_functions.sql");
2441  set_input(&system_views_file, "system_views.sql");
2442 
2443  if (show_setting || debug)
2444  {
2445  fprintf(stderr,
2446  "VERSION=%s\n"
2447  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2448  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2449  "POSTGRESQL_CONF_SAMPLE=%s\n"
2450  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2451  PG_VERSION,
2453  username, bki_file,
2454  conf_file,
2455  hba_file, ident_file);
2456  if (show_setting)
2457  exit(0);
2458  }
2459 
2470 }
static char * system_constraints_file
Definition: initdb.c:162
static bool debug
Definition: initdb.c:140
static char * system_views_file
Definition: initdb.c:164
static char * conf_file
Definition: initdb.c:158
static char * features_file
Definition: initdb.c:161
static char * system_functions_file
Definition: initdb.c:163
#define fprintf
Definition: port.h:221
static char * share_path
Definition: initdb.c:121
static void check_input(char *path)
Definition: initdb.c:781
static char * pg_data
Definition: initdb.c:124
static char * dictionary_file
Definition: initdb.c:159
static char * info_schema_file
Definition: initdb.c:160
static char * username
Definition: initdb.c:134
static char bin_path[MAXPGPATH]
Definition: initdb.c:235
static char * ident_file
Definition: initdb.c:157
static char * bki_file
Definition: initdb.c:155
static char * hba_file
Definition: initdb.c:156
static bool show_setting
Definition: initdb.c:145
static void set_input(char **dest, const char *filename)
Definition: initdb.c:772

◆ setup_depend()

static void setup_depend ( FILE *  cmdfd)
static

Definition at line 1523 of file initdb.c.

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

1524 {
1525  const char *const *line;
1526  static const char *const pg_depend_setup[] = {
1527  /*
1528  * Advance the OID counter so that subsequently-created objects aren't
1529  * pinned.
1530  */
1531  "SELECT pg_stop_making_pinned_objects();\n\n",
1532  NULL
1533  };
1534 
1535  for (line = pg_depend_setup; *line != NULL; line++)
1536  PG_CMD_PUTS(*line);
1537 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ setup_description()

static void setup_description ( FILE *  cmdfd)
static

Definition at line 1564 of file initdb.c.

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

1565 {
1566  /* Create default descriptions for operator implementation functions */
1567  PG_CMD_PUTS("WITH funcdescs AS ( "
1568  "SELECT p.oid as p_oid, o.oid as o_oid, oprname "
1569  "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
1570  "INSERT INTO pg_description "
1571  " SELECT p_oid, 'pg_proc'::regclass, 0, "
1572  " 'implementation of ' || oprname || ' operator' "
1573  " FROM funcdescs "
1574  " WHERE NOT EXISTS (SELECT 1 FROM pg_description "
1575  " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass) "
1576  " AND NOT EXISTS (SELECT 1 FROM pg_description "
1577  " WHERE objoid = o_oid AND classoid = 'pg_operator'::regclass"
1578  " AND description LIKE 'deprecated%');\n\n");
1579 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ setup_locale_encoding()

void setup_locale_encoding ( void  )

Definition at line 2346 of file initdb.c.

References _, check_locale_encoding(), encoding, encodingid, fprintf, get_encoding_id(), lc_collate, lc_ctype, lc_messages, lc_monetary, lc_numeric, lc_time, pg_encoding_to_char(), pg_get_encoding_from_locale(), pg_log_error, PG_UTF8, pg_valid_server_encoding_id(), printf, progname, and setlocales().

Referenced by main().

2347 {
2348  setlocales();
2349 
2350  if (strcmp(lc_ctype, lc_collate) == 0 &&
2351  strcmp(lc_ctype, lc_time) == 0 &&
2352  strcmp(lc_ctype, lc_numeric) == 0 &&
2353  strcmp(lc_ctype, lc_monetary) == 0 &&
2354  strcmp(lc_ctype, lc_messages) == 0)
2355  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2356  else
2357  {
2358  printf(_("The database cluster will be initialized with locales\n"
2359  " COLLATE: %s\n"
2360  " CTYPE: %s\n"
2361  " MESSAGES: %s\n"
2362  " MONETARY: %s\n"
2363  " NUMERIC: %s\n"
2364  " TIME: %s\n"),
2365  lc_collate,
2366  lc_ctype,
2367  lc_messages,
2368  lc_monetary,
2369  lc_numeric,
2370  lc_time);
2371  }
2372 
2373  if (!encoding)
2374  {
2375  int ctype_enc;
2376 
2377  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2378 
2379  if (ctype_enc == -1)
2380  {
2381  /* Couldn't recognize the locale's codeset */
2382  pg_log_error("could not find suitable encoding for locale \"%s\"",
2383  lc_ctype);
2384  fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2385  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2386  progname);
2387  exit(1);
2388  }
2389  else if (!pg_valid_server_encoding_id(ctype_enc))
2390  {
2391  /*
2392  * We recognized it, but it's not a legal server encoding. On
2393  * Windows, UTF-8 works with any locale, so we can fall back to
2394  * UTF-8.
2395  */
2396 #ifdef WIN32
2397  encodingid = PG_UTF8;
2398  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2399  "The default database encoding will be set to \"%s\" instead.\n"),
2400  pg_encoding_to_char(ctype_enc),
2402 #else
2403  pg_log_error("locale \"%s\" requires unsupported encoding \"%s\"",
2404  lc_ctype, pg_encoding_to_char(ctype_enc));
2405  fprintf(stderr,
2406  _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
2407  "Rerun %s with a different locale selection.\n"),
2408  pg_encoding_to_char(ctype_enc), progname);
2409  exit(1);
2410 #endif
2411  }
2412  else
2413  {
2414  encodingid = ctype_enc;
2415  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2417  }
2418  }
2419  else
2421 
2424  exit(1); /* check_locale_encoding printed the error */
2425 
2426 }
static int encodingid
Definition: initdb.c:154
static char * lc_monetary
Definition: initdb.c:129
static char * lc_collate
Definition: initdb.c:127
#define pg_log_error(...)
Definition: logging.h:80
int pg_valid_server_encoding_id(int encoding)
Definition: encnames.c:514
#define printf(...)
Definition: port.h:223
#define fprintf
Definition: port.h:221
static int get_encoding_id(const char *encoding_name)
Definition: initdb.c:635
static char * lc_time
Definition: initdb.c:131
static char * lc_messages
Definition: initdb.c:132
static bool check_locale_encoding(const char *locale, int encoding)
Definition: initdb.c:2081
static char * lc_ctype
Definition: initdb.c:128
static char * lc_numeric
Definition: initdb.c:130
static const char * progname
Definition: initdb.c:153
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:452
static char * encoding
Definition: initdb.c:125
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
static void setlocales(void)
Definition: initdb.c:2117
#define _(x)
Definition: elog.c:89

◆ setup_pgdata()

void setup_pgdata ( void  )

Definition at line 2260 of file initdb.c.

References _, canonicalize_path(), fprintf, pg_data, pg_log_error, pg_strdup(), pgdata_native, and setenv.

Referenced by main().

2261 {
2262  char *pgdata_get_env;
2263 
2264  if (!pg_data)
2265  {
2266  pgdata_get_env = getenv("PGDATA");
2267  if (pgdata_get_env && strlen(pgdata_get_env))
2268  {
2269  /* PGDATA found */
2270  pg_data = pg_strdup(pgdata_get_env);
2271  }
2272  else
2273  {
2274  pg_log_error("no data directory specified");
2275  fprintf(stderr,
2276  _("You must identify the directory where the data for this database system\n"
2277  "will reside. Do this with either the invocation option -D or the\n"
2278  "environment variable PGDATA.\n"));
2279  exit(1);
2280  }
2281  }
2282 
2285 
2286  /*
2287  * we have to set PGDATA for postgres rather than pass it on the command
2288  * line to avoid dumb quoting problems on Windows, and we would especially
2289  * need quotes otherwise on Windows because paths there are most likely to
2290  * have embedded spaces.
2291  */
2292  if (setenv("PGDATA", pg_data, 1) != 0)
2293  {
2294  pg_log_error("could not set environment");
2295  exit(1);
2296  }
2297 }
#define pg_log_error(...)
Definition: logging.h:80
void canonicalize_path(char *path)
Definition: path.c:254
static char * pgdata_native
Definition: initdb.c:174
#define fprintf
Definition: port.h:221
#define setenv(x, y, z)
Definition: win32_port.h:507
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * pg_data
Definition: initdb.c:124
#define _(x)
Definition: elog.c:89

◆ setup_privileges()

static void setup_privileges ( FILE *  cmdfd)
static

Definition at line 1620 of file initdb.c.

References CppAsString2, escape_quotes(), PG_CMD_PUTS, replace_token(), and username.

Referenced by initialize_data_directory().

1621 {
1622  char **line;
1623  char **priv_lines;
1624  static char *privileges_setup[] = {
1625  "UPDATE pg_class "
1626  " SET relacl = (SELECT array_agg(a.acl) FROM "
1627  " (SELECT E'=r/\"$POSTGRES_SUPERUSERNAME\"' as acl "
1628  " UNION SELECT unnest(pg_catalog.acldefault("
1629  " CASE WHEN relkind = " CppAsString2(RELKIND_SEQUENCE) " THEN 's' "
1630  " ELSE 'r' END::\"char\"," CppAsString2(BOOTSTRAP_SUPERUSERID) "::oid))"
1631  " ) as a) "
1632  " WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1633  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1634  CppAsString2(RELKIND_SEQUENCE) ")"
1635  " AND relacl IS NULL;\n\n",
1636  "GRANT USAGE ON SCHEMA pg_catalog, public TO PUBLIC;\n\n",
1637  "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n",
1638  "INSERT INTO pg_init_privs "
1639  " (objoid, classoid, objsubid, initprivs, privtype)"
1640  " SELECT"
1641  " oid,"
1642  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1643  " 0,"
1644  " relacl,"
1645  " 'i'"
1646  " FROM"
1647  " pg_class"
1648  " WHERE"
1649  " relacl IS NOT NULL"
1650  " AND relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1651  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1652  CppAsString2(RELKIND_SEQUENCE) ");\n\n",
1653  "INSERT INTO pg_init_privs "
1654  " (objoid, classoid, objsubid, initprivs, privtype)"
1655  " SELECT"
1656  " pg_class.oid,"
1657  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1658  " pg_attribute.attnum,"
1659  " pg_attribute.attacl,"
1660  " 'i'"
1661  " FROM"
1662  " pg_class"
1663  " JOIN pg_attribute ON (pg_class.oid = pg_attribute.attrelid)"
1664  " WHERE"
1665  " pg_attribute.attacl IS NOT NULL"
1666  " AND pg_class.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1667  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1668  CppAsString2(RELKIND_SEQUENCE) ");\n\n",
1669  "INSERT INTO pg_init_privs "
1670  " (objoid, classoid, objsubid, initprivs, privtype)"
1671  " SELECT"
1672  " oid,"
1673  " (SELECT oid FROM pg_class WHERE relname = 'pg_proc'),"
1674  " 0,"
1675  " proacl,"
1676  " 'i'"
1677  " FROM"
1678  " pg_proc"
1679  " WHERE"
1680  " proacl IS NOT NULL;\n\n",
1681  "INSERT INTO pg_init_privs "
1682  " (objoid, classoid, objsubid, initprivs, privtype)"
1683  " SELECT"
1684  " oid,"
1685  " (SELECT oid FROM pg_class WHERE relname = 'pg_type'),"
1686  " 0,"
1687  " typacl,"
1688  " 'i'"
1689  " FROM"
1690  " pg_type"
1691  " WHERE"
1692  " typacl IS NOT NULL;\n\n",
1693  "INSERT INTO pg_init_privs "
1694  " (objoid, classoid, objsubid, initprivs, privtype)"
1695  " SELECT"
1696  " oid,"
1697  " (SELECT oid FROM pg_class WHERE relname = 'pg_language'),"
1698  " 0,"
1699  " lanacl,"
1700  " 'i'"
1701  " FROM"
1702  " pg_language"
1703  " WHERE"
1704  " lanacl IS NOT NULL;\n\n",
1705  "INSERT INTO pg_init_privs "
1706  " (objoid, classoid, objsubid, initprivs, privtype)"
1707  " SELECT"
1708  " oid,"
1709  " (SELECT oid FROM pg_class WHERE "
1710  " relname = 'pg_largeobject_metadata'),"
1711  " 0,"
1712  " lomacl,"
1713  " 'i'"
1714  " FROM"
1715  " pg_largeobject_metadata"
1716  " WHERE"
1717  " lomacl IS NOT NULL;\n\n",
1718  "INSERT INTO pg_init_privs "
1719  " (objoid, classoid, objsubid, initprivs, privtype)"
1720  " SELECT"
1721  " oid,"
1722  " (SELECT oid FROM pg_class WHERE relname = 'pg_namespace'),"
1723  " 0,"
1724  " nspacl,"
1725  " 'i'"
1726  " FROM"
1727  " pg_namespace"
1728  " WHERE"
1729  " nspacl IS NOT NULL;\n\n",
1730  "INSERT INTO pg_init_privs "
1731  " (objoid, classoid, objsubid, initprivs, privtype)"
1732  " SELECT"
1733  " oid,"
1734  " (SELECT oid FROM pg_class WHERE "
1735  " relname = 'pg_foreign_data_wrapper'),"
1736  " 0,"
1737  " fdwacl,"
1738  " 'i'"
1739  " FROM"
1740  " pg_foreign_data_wrapper"
1741  " WHERE"
1742  " fdwacl IS NOT NULL;\n\n",
1743  "INSERT INTO pg_init_privs "
1744  " (objoid, classoid, objsubid, initprivs, privtype)"
1745  " SELECT"
1746  " oid,"
1747  " (SELECT oid FROM pg_class "
1748  " WHERE relname = 'pg_foreign_server'),"
1749  " 0,"
1750  " srvacl,"
1751  " 'i'"
1752  " FROM"
1753  " pg_foreign_server"
1754  " WHERE"
1755  " srvacl IS NOT NULL;\n\n",
1756  NULL
1757  };
1758 
1759  priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
1761  for (line = priv_lines; *line != NULL; line++)
1762  PG_CMD_PUTS(*line);
1763 }
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:371
#define PG_CMD_PUTS(line)
Definition: initdb.c:308
#define CppAsString2(x)
Definition: c.h:289
static char * username
Definition: initdb.c:134
static char * escape_quotes(const char *src)
Definition: initdb.c:325

◆ setup_run_file()

static void setup_run_file ( FILE *  cmdfd,
const char *  filename 
)
static

Definition at line 1543 of file initdb.c.

References free, PG_CMD_PUTS, and readfile().

Referenced by initialize_data_directory(), and setup_schema().

1544 {
1545  char **lines;
1546 
1547  lines = readfile(filename);
1548 
1549  for (char **line = lines; *line != NULL; line++)
1550  {
1551  PG_CMD_PUTS(*line);
1552  free(*line);
1553  }
1554 
1555  PG_CMD_PUTS("\n\n");
1556 
1557  free(lines);
1558 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308
#define free(a)
Definition: header.h:65
static char * filename
Definition: pg_dumpall.c:92
static char ** readfile(const char *path)
Definition: initdb.c:454

◆ setup_schema()

static void setup_schema ( FILE *  cmdfd)
static

Definition at line 1797 of file initdb.c.

References escape_quotes(), features_file, info_schema_file, infoversion, PG_CMD_PRINTF, and setup_run_file().

Referenced by initialize_data_directory().

1798 {
1800 
1801  PG_CMD_PRINTF("UPDATE information_schema.sql_implementation_info "
1802  " SET character_value = '%s' "
1803  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
1804  infoversion);
1805 
1806  PG_CMD_PRINTF("COPY information_schema.sql_features "
1807  " (feature_id, feature_name, sub_feature_id, "
1808  " sub_feature_name, is_supported, comments) "
1809  " FROM E'%s';\n\n",
1811 }
static char infoversion[100]
Definition: initdb.c:170
static char * features_file
Definition: initdb.c:161
#define PG_CMD_PRINTF(fmt,...)
Definition: initdb.c:314
static void setup_run_file(FILE *cmdfd, const char *filename)
Definition: initdb.c:1543
static char * info_schema_file
Definition: initdb.c:160
static char * escape_quotes(const char *src)
Definition: initdb.c:325

◆ setup_signals()

void setup_signals ( void  )

Definition at line 2509 of file initdb.c.

References pqsignal(), SIG_IGN, SIGHUP, SIGPIPE, SIGQUIT, and trapsig().

Referenced by initialize_data_directory().

2510 {
2511  /* some of these are not valid on Windows */
2512 #ifdef SIGHUP
2514 #endif
2515 #ifdef SIGINT
2516  pqsignal(SIGINT, trapsig);
2517 #endif
2518 #ifdef SIGQUIT
2520 #endif
2521 #ifdef SIGTERM
2522  pqsignal(SIGTERM, trapsig);
2523 #endif
2524 
2525  /* Ignore SIGPIPE when writing to backend, so we can clean up */
2526 #ifdef SIGPIPE
2528 #endif
2529 
2530  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
2531 #ifdef SIGSYS
2532  pqsignal(SIGSYS, SIG_IGN);
2533 #endif
2534 }
#define SIGQUIT
Definition: win32_port.h:168
#define SIGPIPE
Definition: win32_port.h:172
#define SIGHUP
Definition: win32_port.h:167
#define SIG_IGN
Definition: win32_port.h:164
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static void trapsig(int signum)
Definition: initdb.c:1909

◆ setup_text_search()

void setup_text_search ( void  )

Definition at line 2474 of file initdb.c.

References _, default_text_search_config, find_matching_ts_config(), lc_ctype, pg_log_info, pg_log_warning, and printf.

Referenced by main().

2475 {
2477  {
2480  {
2481  pg_log_info("could not find suitable text search configuration for locale \"%s\"",
2482  lc_ctype);
2483  default_text_search_config = "simple";
2484  }
2485  }
2486  else
2487  {
2488  const char *checkmatch = find_matching_ts_config(lc_ctype);
2489 
2490  if (checkmatch == NULL)
2491  {
2492  pg_log_warning("suitable text search configuration for locale \"%s\" is unknown",
2493  lc_ctype);
2494  }
2495  else if (strcmp(checkmatch, default_text_search_config) != 0)
2496  {
2497  pg_log_warning("specified text search configuration \"%s\" might not match locale \"%s\"",
2499  }
2500  }
2501 
2502  printf(_("The default text search configuration will be set to \"%s\".\n"),
2504 
2505 }
static const char * find_matching_ts_config(const char *lc_type)
Definition: initdb.c:726
#define printf(...)
Definition: port.h:223
static const char * default_text_search_config
Definition: initdb.c:133
static char * lc_ctype
Definition: initdb.c:128
#define pg_log_warning(...)
Definition: pgfnames.c:24
#define _(x)
Definition: elog.c:89
#define pg_log_info(...)
Definition: logging.h:88

◆ test_config_settings()

static void test_config_settings ( void  )
static

Definition at line 920 of file initdb.c.

References _, backend_exec, boot_options, choose_dsm_implementation(), default_timezone, DEVNULL, dynamic_shared_memory_type, extra_options, i, MAXPGPATH, MIN_BUFS_FOR_CONNS, n_buffers, n_connections, printf, select_default_timezone(), share_path, snprintf, status(), and generate_unaccent_rules::stdout.

Referenced by initialize_data_directory().

921 {
922  /*
923  * This macro defines the minimum shared_buffers we want for a given
924  * max_connections value. The arrays show the settings to try.
925  */
926 #define MIN_BUFS_FOR_CONNS(nconns) ((nconns) * 10)
927 
928  static const int trial_conns[] = {
929  100, 50, 40, 30, 20
930  };
931  static const int trial_bufs[] = {
932  16384, 8192, 4096, 3584, 3072, 2560, 2048, 1536,
933  1000, 900, 800, 700, 600, 500,
934  400, 300, 200, 100, 50
935  };
936 
937  char cmd[MAXPGPATH];
938  const int connslen = sizeof(trial_conns) / sizeof(int);
939  const int bufslen = sizeof(trial_bufs) / sizeof(int);
940  int i,
941  status,
942  test_conns,
943  test_buffs,
944  ok_buffers = 0;
945 
946  /*
947  * Need to determine working DSM implementation first so that subsequent
948  * tests don't fail because DSM setting doesn't work.
949  */
950  printf(_("selecting dynamic shared memory implementation ... "));
951  fflush(stdout);
954 
955  /*
956  * Probe for max_connections before shared_buffers, since it is subject to
957  * more constraints than shared_buffers.
958  */
959  printf(_("selecting default max_connections ... "));
960  fflush(stdout);
961 
962  for (i = 0; i < connslen; i++)
963  {
964  test_conns = trial_conns[i];
965  test_buffs = MIN_BUFS_FOR_CONNS(test_conns);
966 
967  snprintf(cmd, sizeof(cmd),
968  "\"%s\" --check %s %s "
969  "-c max_connections=%d "
970  "-c shared_buffers=%d "
971  "-c dynamic_shared_memory_type=%s "
972  "< \"%s\" > \"%s\" 2>&1",
974  test_conns, test_buffs,
976  DEVNULL, DEVNULL);
977  status = system(cmd);
978  if (status == 0)
979  {
980  ok_buffers = test_buffs;
981  break;
982  }
983  }
984  if (i >= connslen)
985  i = connslen - 1;
986  n_connections = trial_conns[i];
987 
988  printf("%d\n", n_connections);
989 
990  printf(_("selecting default shared_buffers ... "));
991  fflush(stdout);
992 
993  for (i = 0; i < bufslen; i++)
994  {
995  /* Use same amount of memory, independent of BLCKSZ */
996  test_buffs = (trial_bufs[i] * 8192) / BLCKSZ;
997  if (test_buffs <= ok_buffers)
998  {
999  test_buffs = ok_buffers;
1000  break;
1001  }
1002 
1003  snprintf(cmd, sizeof(cmd),
1004  "\"%s\" --check %s %s "
1005  "-c max_connections=%d "
1006  "-c shared_buffers=%d "
1007  "-c dynamic_shared_memory_type=%s "
1008  "< \"%s\" > \"%s\" 2>&1",
1010  n_connections, test_buffs,
1012  DEVNULL, DEVNULL);
1013  status = system(cmd);
1014  if (status == 0)
1015  break;
1016  }
1017  n_buffers = test_buffs;
1018 
1019  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1020  printf("%dMB\n", (n_buffers * (BLCKSZ / 1024)) / 1024);
1021  else
1022  printf("%dkB\n", n_buffers * (BLCKSZ / 1024));
1023 
1024  printf(_("selecting default time zone ... "));
1025  fflush(stdout);
1027  printf("%s\n", default_timezone ? default_timezone : "GMT");
1028 }
static const char * default_timezone
Definition: initdb.c:180
#define MIN_BUFS_FOR_CONNS(nconns)
#define printf(...)
Definition: port.h:223
static const char * choose_dsm_implementation(void)
Definition: initdb.c:879
static char * share_path
Definition: initdb.c:121
static int n_connections
Definition: initdb.c:177
#define MAXPGPATH
#define DEVNULL
Definition: port.h:148
const char * select_default_timezone(const char *share_path)
static char * extra_options
Definition: initdb.c:206
static const char * boot_options
Definition: initdb.c:202
static int n_buffers
Definition: initdb.c:178
static const char * dynamic_shared_memory_type
Definition: initdb.c:179
int i
static char backend_exec[MAXPGPATH]
Definition: initdb.c:236
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
#define snprintf
Definition: port.h:217
#define _(x)
Definition: elog.c:89

◆ trapsig()

static void trapsig ( int  signum)
static

Definition at line 1909 of file initdb.c.

References caught_signal, and pqsignal().

Referenced by setup_signals().

1910 {
1911  /* handle systems that reset the handler, like Windows (grr) */
1912  pqsignal(signum, trapsig);
1913  caught_signal = true;
1914 }
static bool caught_signal
Definition: initdb.c:171
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static void trapsig(int signum)
Definition: initdb.c:1909

◆ usage()

static void usage ( const char *  progname)
static

Definition at line 2168 of file initdb.c.

References _, and printf.

Referenced by main().

2169 {
2170  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2171  printf(_("Usage:\n"));
2172  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2173  printf(_("\nOptions:\n"));
2174  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2175  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2176  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2177  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2178  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2179  printf(_(" -g, --allow-group-access allow group read/execute on data directory\n"));
2180  printf(_(" -k, --data-checksums use data page checksums\n"));
2181  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2182  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2183  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2184  " set default locale in the respective category for\n"
2185  " new databases (default taken from environment)\n"));
2186  printf(_(" --no-locale equivalent to --locale=C\n"));
2187  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2188  printf(_(" -T, --text-search-config=CFG\n"
2189  " default text search configuration\n"));
2190  printf(_(" -U, --username=NAME database superuser name\n"));
2191  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2192  printf(_(" -X, --waldir=WALDIR location for the write-ahead log directory\n"));
2193  printf(_(" --wal-segsize=SIZE size of WAL segments, in megabytes\n"));
2194  printf(_("\nLess commonly used options:\n"));
2195  printf(_(" -d, --debug generate lots of debugging output\n"));
2196  printf(_(" --discard-caches set debug_discard_caches=1\n"));
2197  printf(_(" -L DIRECTORY where to find the input files\n"));
2198  printf(_(" -n, --no-clean do not clean up after errors\n"));
2199  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
2200  printf(_(" --no-instructions do not print instructions for next steps\n"));
2201  printf(_(" -s, --show show internal settings\n"));
2202  printf(_(" -S, --sync-only only sync database files to disk, then exit\n"));
2203  printf(_("\nOther options:\n"));
2204  printf(_(" -V, --version output version information, then exit\n"));
2205  printf(_(" -?, --help show this help, then exit\n"));
2206  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2207  "is used.\n"));
2208  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2209  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2210 }
#define printf(...)
Definition: port.h:223
static const char * progname
Definition: initdb.c:153
#define _(x)
Definition: elog.c:89

◆ vacuum_db()

static void vacuum_db ( FILE *  cmdfd)
static

Definition at line 1826 of file initdb.c.

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

1827 {
1828  /* Run analyze before VACUUM so the statistics are frozen. */
1829  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
1830 }
#define PG_CMD_PUTS(line)
Definition: initdb.c:308

◆ warn_on_mount_point()

void warn_on_mount_point ( int  error)

Definition at line 2710 of file initdb.c.

References _, and fprintf.

Referenced by create_data_directory(), and create_xlog_or_symlink().

2711 {
2712  if (error == 2)
2713  fprintf(stderr,
2714  _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
2715  else if (error == 3)
2716  fprintf(stderr,
2717  _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
2718 
2719  fprintf(stderr,
2720  _("Using a mount point directly as the data directory is not recommended.\n"
2721  "Create a subdirectory under the mount point.\n"));
2722 }
static void error(void)
Definition: sql-dyntest.c:147
#define fprintf
Definition: port.h:221
#define _(x)
Definition: elog.c:89

◆ write_version_file()

static void write_version_file ( const char *  extrapath)
static

Definition at line 818 of file initdb.c.

References fprintf, free, PG_BINARY_W, pg_data, pg_log_error, psprintf(), and version_file.

Referenced by initialize_data_directory().

819 {
820  FILE *version_file;
821  char *path;
822 
823  if (extrapath == NULL)
824  path = psprintf("%s/PG_VERSION", pg_data);
825  else
826  path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
827 
828  if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
829  {
830  pg_log_error("could not open file \"%s\" for writing: %m", path);
831  exit(1);
832  }
833  if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
834  fclose(version_file))
835  {
836  pg_log_error("could not write file \"%s\": %m", path);
837  exit(1);
838  }
839  free(path);
840 }
#define pg_log_error(...)
Definition: logging.h:80
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define PG_BINARY_W
Definition: c.h:1274
#define fprintf
Definition: port.h:221
static char * pg_data
Definition: initdb.c:124
#define free(a)
Definition: header.h:65
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:102

◆ writefile()

static void writefile ( char *  path,
char **  lines 
)
static

Definition at line 501 of file initdb.c.

References free, and pg_log_error.

Referenced by setup_config().

502 {
503  FILE *out_file;
504  char **line;
505 
506  if ((out_file = fopen(path, "w")) == NULL)
507  {
508  pg_log_error("could not open file \"%s\" for writing: %m", path);
509  exit(1);
510  }
511  for (line = lines; *line != NULL; line++)
512  {
513  if (fputs(*line, out_file) < 0)
514  {
515  pg_log_error("could not write file \"%s\": %m", path);
516  exit(1);
517  }
518  free(*line);
519  }
520  if (fclose(out_file))
521  {
522  pg_log_error("could not write file \"%s\": %m", path);
523  exit(1);
524  }
525 }
#define pg_log_error(...)
Definition: logging.h:80
#define free(a)
Definition: header.h:65

Variable Documentation

◆ auth_methods_host

const char* const auth_methods_host[]
static
Initial value:
= {
"trust", "reject", "scram-sha-256", "md5", "password", "ident", "radius",
NULL
}

Definition at line 82 of file initdb.c.

Referenced by main().

◆ auth_methods_local

const char* const auth_methods_local[]
static
Initial value:
= {
"trust", "reject", "scram-sha-256", "md5", "password", "peer", "radius",
NULL
}

Definition at line 104 of file initdb.c.

Referenced by main().

◆ authmethodhost

const char* authmethodhost = NULL
static

Definition at line 138 of file initdb.c.

Referenced by main(), and setup_config().

◆ authmethodlocal

const char* authmethodlocal = NULL
static

Definition at line 139 of file initdb.c.

Referenced by main(), and setup_config().

◆ authwarning

bool authwarning = false
static

Definition at line 190 of file initdb.c.

Referenced by check_authmethod_unspecified(), and main().

◆ backend_exec

char backend_exec[MAXPGPATH]
static

◆ backend_options

const char* backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true"
static

Definition at line 203 of file initdb.c.

Referenced by initialize_data_directory().

◆ bin_path

char bin_path[MAXPGPATH]
static

Definition at line 235 of file initdb.c.

Referenced by setup_bin_paths(), and setup_data_file_paths().

◆ bki_file

char* bki_file
static

Definition at line 155 of file initdb.c.

Referenced by bootstrap_template1(), and setup_data_file_paths().

◆ boot_options

const char* boot_options = "-F"
static

Definition at line 202 of file initdb.c.

Referenced by bootstrap_template1(), and test_config_settings().

◆ caught_signal

bool caught_signal = false
static

Definition at line 171 of file initdb.c.

Referenced by check_ok(), and trapsig().

◆ conf_file

char* conf_file
static

Definition at line 158 of file initdb.c.

Referenced by set_null_conf(), setup_config(), and setup_data_file_paths().

◆ data_checksums

bool data_checksums = false
static

Definition at line 146 of file initdb.c.

Referenced by bootstrap_template1(), and main().

◆ debug

bool debug = false
static

◆ default_text_search_config

const char* default_text_search_config = NULL
static

Definition at line 133 of file initdb.c.

Referenced by main(), setup_config(), and setup_text_search().

◆ default_timezone

const char* default_timezone = NULL
static

Definition at line 180 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ dictionary_file

char* dictionary_file
static

Definition at line 159 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ do_sync

bool do_sync = true
static

Definition at line 143 of file initdb.c.

Referenced by main(), and sync_target_dir().

◆ dynamic_shared_memory_type

const char* dynamic_shared_memory_type = NULL
static

Definition at line 179 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ encoding

char* encoding = NULL
static

Definition at line 125 of file initdb.c.

Referenced by main(), and setup_locale_encoding().

◆ encodingid

int encodingid
static

Definition at line 154 of file initdb.c.

Referenced by bootstrap_template1(), and setup_locale_encoding().

◆ extra_options

char* extra_options = ""
static

◆ features_file

char* features_file
static

Definition at line 161 of file initdb.c.

Referenced by setup_data_file_paths(), and setup_schema().

◆ found_existing_pgdata

bool found_existing_pgdata = false
static

Definition at line 167 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_data_directory().

◆ found_existing_xlogdir

bool found_existing_xlogdir = false
static

Definition at line 169 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_xlog_or_symlink().

◆ hba_file

char* hba_file
static

Definition at line 156 of file initdb.c.

Referenced by setup_config(), and setup_data_file_paths().

◆ ident_file

char* ident_file
static

Definition at line 157 of file initdb.c.

Referenced by setup_config(), and setup_data_file_paths().

◆ info_schema_file

char* info_schema_file
static

Definition at line 160 of file initdb.c.

Referenced by setup_data_file_paths(), and setup_schema().

◆ infoversion

char infoversion[100]
static

Definition at line 170 of file initdb.c.

Referenced by set_info_version(), and setup_schema().

◆ lc_collate

char* lc_collate = NULL
static

◆ lc_ctype

char* lc_ctype = NULL
static

◆ lc_messages

char* lc_messages = NULL
static

Definition at line 132 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ lc_monetary

char* lc_monetary = NULL
static

Definition at line 129 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ lc_numeric

char* lc_numeric = NULL
static

Definition at line 130 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ lc_time

char* lc_time = NULL
static

Definition at line 131 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ locale

◆ made_new_pgdata

bool made_new_pgdata = false
static

Definition at line 166 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_data_directory().

◆ made_new_xlogdir

bool made_new_xlogdir = false
static

Definition at line 168 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_xlog_or_symlink().

◆ n_buffers

int n_buffers = 50
static

Definition at line 178 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ n_connections

int n_connections = 10
static

Definition at line 177 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ noclean

bool noclean = false
static

Definition at line 141 of file initdb.c.

Referenced by cleanup_directories_atexit(), and main().

◆ noinstructions

bool noinstructions = false
static

Definition at line 142 of file initdb.c.

Referenced by main().

◆ output_errno

int output_errno = 0
static

Definition at line 173 of file initdb.c.

Referenced by check_ok().

◆ output_failed

bool output_failed = false
static

Definition at line 172 of file initdb.c.

Referenced by check_ok().

◆ pg_data

◆ pgdata_native

char* pgdata_native
static

Definition at line 174 of file initdb.c.

Referenced by main(), and setup_pgdata().

◆ progname

const char* progname
static

◆ pwfilename

char* pwfilename = NULL
static

Definition at line 136 of file initdb.c.

Referenced by check_need_password(), get_su_pwd(), and main().

◆ pwprompt

bool pwprompt = false
static

Definition at line 135 of file initdb.c.

Referenced by check_need_password(), get_su_pwd(), and main().

◆ share_path

char* share_path = NULL
static

◆ show_setting

bool show_setting = false
static

Definition at line 145 of file initdb.c.

Referenced by main(), and setup_data_file_paths().

◆ str_wal_segment_size_mb

char* str_wal_segment_size_mb = NULL
static

Definition at line 148 of file initdb.c.

Referenced by main().

◆ subdirs

const char* const subdirs[]
static
Initial value:
= {
"global",
"pg_wal/archive_status",
"pg_commit_ts",
"pg_dynshmem",
"pg_notify",
"pg_serial",
"pg_snapshots",
"pg_subtrans",
"pg_twophase",
"pg_multixact",
"pg_multixact/members",
"pg_multixact/offsets",
"base",
"base/1",
"pg_replslot",
"pg_tblspc",
"pg_stat",
"pg_stat_tmp",
"pg_xact",
"pg_logical",
"pg_logical/snapshots",
"pg_logical/mappings"
}

Definition at line 208 of file initdb.c.

Referenced by initialize_data_directory().

◆ success

◆ superuser_password

char* superuser_password = NULL
static

Definition at line 137 of file initdb.c.

Referenced by get_su_pwd(), and setup_auth().

◆ sync_only

bool sync_only = false
static

Definition at line 144 of file initdb.c.

Referenced by main().

◆ system_constraints_file

char* system_constraints_file
static

Definition at line 162 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ system_functions_file

char* system_functions_file
static

Definition at line 163 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ system_views_file

char* system_views_file
static

Definition at line 164 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ tsearch_config_languages

const struct tsearch_config_match tsearch_config_languages[]
static

Definition at line 659 of file initdb.c.

◆ username

char* username = NULL
static

◆ wal_segment_size_mb

int wal_segment_size_mb
static

Definition at line 149 of file initdb.c.

Referenced by bootstrap_template1(), main(), and pretty_wal_size().

◆ xlog_dir

char* xlog_dir = NULL
static

Definition at line 147 of file initdb.c.

Referenced by cleanup_directories_atexit(), create_xlog_or_symlink(), and main().