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