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