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