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