LCOV - code coverage report
Current view: top level - src/bin/initdb - initdb.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 788 1058 74.5 %
Date: 2021-12-05 02:08:31 Functions: 53 55 96.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14