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