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