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

Generated by: LCOV version 1.13