LCOV - differential code coverage report
Current view: top level - src/bin/initdb - initdb.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 79.0 % 1216 961 33 64 137 21 62 479 218 202 136 609 36 86
Current Date: 2023-04-08 15:15:32 Functions: 96.8 % 63 61 1 1 54 7 1 52 1 9
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a