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