forked from postgres/postgres
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinitdb.c
3492 lines (3042 loc) · 93.5 KB
/
initdb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* initdb --- initialize a PostgreSQL installation
*
* initdb creates (initializes) a PostgreSQL database cluster (site,
* instance, installation, whatever). A database cluster is a
* collection of PostgreSQL databases all managed by the same server.
*
* To create the database cluster, we create the directory that contains
* all its data, create the files that hold the global tables, create
* a few other control files for it, and create three databases: the
* template databases "template0" and "template1", and a default user
* database "postgres".
*
* The template databases are ordinary PostgreSQL databases. template0
* is never supposed to change after initdb, whereas template1 can be
* changed to add site-local standard data. Either one can be copied
* to produce a new database.
*
* For largely-historical reasons, the template1 database is the one built
* by the basic bootstrap process. After it is complete, template0 and
* the default database, postgres, are made just by copying template1.
*
* To create template1, we run the postgres (backend) program in bootstrap
* mode and feed it data from the postgres.bki library file. After this
* initial bootstrap phase, some additional stuff is created by normal
* SQL commands fed to a standalone backend. Some of those commands are
* just embedded into this program (yeah, it's ugly), but larger chunks
* are taken from script files.
*
*
* Note:
* The program has some memory leakage - it isn't worth cleaning it up.
*
* This is a C implementation of the previous shell script for setting up a
* PostgreSQL cluster location, and should be highly compatible with it.
* author of C translation: Andrew Dunstan mailto:andrew@dunslane.net
*
* This code is released under the terms of the PostgreSQL License.
*
* Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/bin/initdb/initdb.c
*
*-------------------------------------------------------------------------
*/
#include "postgres_fe.h"
#include <dirent.h>
#include <fcntl.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/stat.h>
#ifdef USE_ICU
#include <unicode/ucol.h>
#endif
#include <unistd.h>
#include <signal.h>
#include <time.h>
#ifdef HAVE_SHM_OPEN
#include "sys/mman.h"
#endif
#include "access/xlog_internal.h"
#include "catalog/pg_authid_d.h"
#include "catalog/pg_class_d.h" /* pgrminclude ignore */
#include "catalog/pg_collation_d.h"
#include "catalog/pg_database_d.h" /* pgrminclude ignore */
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/logging.h"
#include "common/pg_prng.h"
#include "common/restricted_token.h"
#include "common/string.h"
#include "common/username.h"
#include "fe_utils/option_utils.h"
#include "fe_utils/string_utils.h"
#include "getopt_long.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
/* Ideally this would be in a .h file, but it hardly seems worth the trouble */
extern const char *select_default_timezone(const char *share_path);
/* simple list of strings */
typedef struct _stringlist
{
char *str;
struct _stringlist *next;
} _stringlist;
static const char *const auth_methods_host[] = {
"trust", "reject", "scram-sha-256", "md5", "password", "ident", "radius",
#ifdef ENABLE_GSS
"gss",
#endif
#ifdef ENABLE_SSPI
"sspi",
#endif
#ifdef USE_PAM
"pam", "pam ",
#endif
#ifdef USE_BSD_AUTH
"bsd",
#endif
#ifdef USE_LDAP
"ldap",
#endif
#ifdef USE_SSL
"cert",
#endif
NULL
};
static const char *const auth_methods_local[] = {
"trust", "reject", "scram-sha-256", "md5", "password", "peer", "radius",
#ifdef USE_PAM
"pam", "pam ",
#endif
#ifdef USE_BSD_AUTH
"bsd",
#endif
#ifdef USE_LDAP
"ldap",
#endif
NULL
};
/*
* these values are passed in by makefile defines
*/
static char *share_path = NULL;
/* values to be obtained from arguments */
static char *pg_data = NULL;
static char *encoding = NULL;
static char *locale = NULL;
static char *lc_collate = NULL;
static char *lc_ctype = NULL;
static char *lc_monetary = NULL;
static char *lc_numeric = NULL;
static char *lc_time = NULL;
static char *lc_messages = NULL;
static char locale_provider = COLLPROVIDER_LIBC;
static bool builtin_locale_specified = false;
static char *datlocale = NULL;
static bool icu_locale_specified = false;
static char *icu_rules = NULL;
static const char *default_text_search_config = NULL;
static char *username = NULL;
static bool pwprompt = false;
static char *pwfilename = NULL;
static char *superuser_password = NULL;
static const char *authmethodhost = NULL;
static const char *authmethodlocal = NULL;
static _stringlist *extra_guc_names = NULL;
static _stringlist *extra_guc_values = NULL;
static bool debug = false;
static bool noclean = false;
static bool noinstructions = false;
static bool do_sync = true;
static bool sync_only = false;
static bool show_setting = false;
static bool data_checksums = false;
static char *xlog_dir = NULL;
static int wal_segment_size_mb = (DEFAULT_XLOG_SEG_SIZE) / (1024 * 1024);
static DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC;
/* internal vars */
static const char *progname;
static int encodingid;
static char *bki_file;
static char *hba_file;
static char *ident_file;
static char *conf_file;
static char *dictionary_file;
static char *info_schema_file;
static char *features_file;
static char *system_constraints_file;
static char *system_functions_file;
static char *system_views_file;
static bool success = false;
static bool made_new_pgdata = false;
static bool found_existing_pgdata = false;
static bool made_new_xlogdir = false;
static bool found_existing_xlogdir = false;
static char infoversion[100];
static bool caught_signal = false;
static bool output_failed = false;
static int output_errno = 0;
static char *pgdata_native;
/* defaults */
static int n_connections = 10;
static int n_buffers = 50;
static const char *dynamic_shared_memory_type = NULL;
static const char *default_timezone = NULL;
/*
* Warning messages for authentication methods
*/
#define AUTHTRUST_WARNING \
"# CAUTION: Configuring the system for local \"trust\" authentication\n" \
"# allows any local user to connect as any PostgreSQL user, including\n" \
"# the database superuser. If you do not trust all your local users,\n" \
"# use another authentication method.\n"
static bool authwarning = false;
/*
* Centralized knowledge of switches to pass to backend
*
* Note: we run the backend with -F (fsync disabled) and then do a single
* pass of fsync'ing at the end. This is faster than fsync'ing each step.
*
* Note: in the shell-script version, we also passed PGDATA as a -D switch,
* but here it is more convenient to pass it as an environment variable
* (no quoting to worry about).
*/
static const char *const boot_options = "-F -c log_checkpoints=false";
static const char *const backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true -c log_checkpoints=false";
/* Additional switches to pass to backend (either boot or standalone) */
static char *extra_options = "";
static const char *const subdirs[] = {
"global",
"pg_wal/archive_status",
"pg_wal/summaries",
"pg_commit_ts",
"pg_dynshmem",
"pg_notify",
"pg_serial",
"pg_snapshots",
"pg_subtrans",
"pg_twophase",
"pg_multixact",
"pg_multixact/members",
"pg_multixact/offsets",
"base",
"base/1",
"pg_replslot",
"pg_tblspc",
"pg_stat",
"pg_stat_tmp",
"pg_xact",
"pg_logical",
"pg_logical/snapshots",
"pg_logical/mappings"
};
/* path to 'initdb' binary directory */
static char bin_path[MAXPGPATH];
static char backend_exec[MAXPGPATH];
static char **replace_token(char **lines,
const char *token, const char *replacement);
static char **replace_guc_value(char **lines,
const char *guc_name, const char *guc_value,
bool mark_as_comment);
static bool guc_value_requires_quotes(const char *guc_value);
static char **readfile(const char *path);
static void writefile(char *path, char **lines);
static FILE *popen_check(const char *command, const char *mode);
static char *get_id(void);
static int get_encoding_id(const char *encoding_name);
static void set_input(char **dest, const char *filename);
static void check_input(char *path);
static void write_version_file(const char *extrapath);
static void set_null_conf(void);
static void test_config_settings(void);
static bool test_specific_config_settings(int test_conns, int test_buffs);
static void setup_config(void);
static void bootstrap_template1(void);
static void setup_auth(FILE *cmdfd);
static void get_su_pwd(void);
static void setup_depend(FILE *cmdfd);
static void setup_run_file(FILE *cmdfd, const char *filename);
static void setup_description(FILE *cmdfd);
static void setup_collation(FILE *cmdfd);
static void setup_privileges(FILE *cmdfd);
static void set_info_version(void);
static void setup_schema(FILE *cmdfd);
static void load_plpgsql(FILE *cmdfd);
static void vacuum_db(FILE *cmdfd);
static void make_template0(FILE *cmdfd);
static void make_postgres(FILE *cmdfd);
static void trapsig(SIGNAL_ARGS);
static void check_ok(void);
static char *escape_quotes(const char *src);
static char *escape_quotes_bki(const char *src);
static int locale_date_order(const char *locale);
static void check_locale_name(int category, const char *locale,
char **canonname);
static bool check_locale_encoding(const char *locale, int user_enc);
static void setlocales(void);
static void usage(const char *progname);
void setup_pgdata(void);
void setup_bin_paths(const char *argv0);
void setup_data_file_paths(void);
void setup_locale_encoding(void);
void setup_signals(void);
void setup_text_search(void);
void create_data_directory(void);
void create_xlog_or_symlink(void);
void warn_on_mount_point(int error);
void initialize_data_directory(void);
/*
* macros for running pipes to postgres
*/
#define PG_CMD_DECL FILE *cmdfd
#define PG_CMD_OPEN(cmd) \
do { \
cmdfd = popen_check(cmd, "w"); \
if (cmdfd == NULL) \
exit(1); /* message already printed by popen_check */ \
} while (0)
#define PG_CMD_CLOSE() \
do { \
if (pclose_check(cmdfd)) \
exit(1); /* message already printed by pclose_check */ \
} while (0)
#define PG_CMD_PUTS(line) \
do { \
if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
output_failed = true, output_errno = errno; \
} while (0)
#define PG_CMD_PRINTF(fmt, ...) \
do { \
if (fprintf(cmdfd, fmt, __VA_ARGS__) < 0 || fflush(cmdfd) < 0) \
output_failed = true, output_errno = errno; \
} while (0)
/*
* Escape single quotes and backslashes, suitably for insertions into
* configuration files or SQL E'' strings.
*/
static char *
escape_quotes(const char *src)
{
char *result = escape_single_quotes_ascii(src);
if (!result)
pg_fatal("out of memory");
return result;
}
/*
* Escape a field value to be inserted into the BKI data.
* Run the value through escape_quotes (which will be inverted
* by the backend's DeescapeQuotedString() function), then wrap
* the value in single quotes, even if that isn't strictly necessary.
*/
static char *
escape_quotes_bki(const char *src)
{
char *result;
char *data = escape_quotes(src);
char *resultp;
char *datap;
result = (char *) pg_malloc(strlen(data) + 3);
resultp = result;
*resultp++ = '\'';
for (datap = data; *datap; datap++)
*resultp++ = *datap;
*resultp++ = '\'';
*resultp = '\0';
free(data);
return result;
}
/*
* Add an item at the end of a stringlist.
*/
static void
add_stringlist_item(_stringlist **listhead, const char *str)
{
_stringlist *newentry = pg_malloc(sizeof(_stringlist));
_stringlist *oldentry;
newentry->str = pg_strdup(str);
newentry->next = NULL;
if (*listhead == NULL)
*listhead = newentry;
else
{
for (oldentry = *listhead; oldentry->next; oldentry = oldentry->next)
/* skip */ ;
oldentry->next = newentry;
}
}
/*
* Modify the array of lines, replacing "token" by "replacement"
* the first time it occurs on each line.
*
* The array must be a malloc'd array of individually malloc'd strings.
* We free any discarded strings.
*
* This does most of what sed was used for in the shell script, but
* doesn't need any regexp stuff.
*/
static char **
replace_token(char **lines, const char *token, const char *replacement)
{
int toklen,
replen,
diff;
toklen = strlen(token);
replen = strlen(replacement);
diff = replen - toklen;
for (int i = 0; lines[i]; i++)
{
char *where;
char *newline;
int pre;
/* nothing to do if no change needed */
if ((where = strstr(lines[i], token)) == NULL)
continue;
/* if we get here a change is needed - set up new line */
newline = (char *) pg_malloc(strlen(lines[i]) + diff + 1);
pre = where - lines[i];
memcpy(newline, lines[i], pre);
memcpy(newline + pre, replacement, replen);
strcpy(newline + pre + replen, lines[i] + pre + toklen);
free(lines[i]);
lines[i] = newline;
}
return lines;
}
/*
* Modify the array of lines, replacing the possibly-commented-out
* assignment of parameter guc_name with a live assignment of guc_value.
* The value will be suitably quoted.
*
* If mark_as_comment is true, the replacement line is prefixed with '#'.
* This is used for fixing up cases where the effective default might not
* match what is in postgresql.conf.sample.
*
* We assume there's at most one matching assignment. If we find no match,
* append a new line with the desired assignment.
*
* The array must be a malloc'd array of individually malloc'd strings.
* We free any discarded strings.
*/
static char **
replace_guc_value(char **lines, const char *guc_name, const char *guc_value,
bool mark_as_comment)
{
int namelen = strlen(guc_name);
PQExpBuffer newline = createPQExpBuffer();
int i;
/* prepare the replacement line, except for possible comment and newline */
if (mark_as_comment)
appendPQExpBufferChar(newline, '#');
appendPQExpBuffer(newline, "%s = ", guc_name);
if (guc_value_requires_quotes(guc_value))
appendPQExpBuffer(newline, "'%s'", escape_quotes(guc_value));
else
appendPQExpBufferStr(newline, guc_value);
for (i = 0; lines[i]; i++)
{
const char *where;
const char *namestart;
/*
* Look for a line assigning to guc_name. Typically it will be
* preceded by '#', but that might not be the case if a -c switch
* overrides a previous assignment. We allow leading whitespace too,
* although normally there wouldn't be any.
*/
where = lines[i];
while (*where == '#' || isspace((unsigned char) *where))
where++;
if (pg_strncasecmp(where, guc_name, namelen) != 0)
continue;
namestart = where;
where += namelen;
while (isspace((unsigned char) *where))
where++;
if (*where != '=')
continue;
/* found it -- let's use the canonical casing shown in the file */
memcpy(&newline->data[mark_as_comment ? 1 : 0], namestart, namelen);
/* now append the original comment if any */
where = strrchr(where, '#');
if (where)
{
/*
* We try to preserve original indentation, which is tedious.
* oldindent and newindent are measured in de-tab-ified columns.
*/
const char *ptr;
int oldindent = 0;
int newindent;
for (ptr = lines[i]; ptr < where; ptr++)
{
if (*ptr == '\t')
oldindent += 8 - (oldindent % 8);
else
oldindent++;
}
/* ignore the possibility of tabs in guc_value */
newindent = newline->len;
/* append appropriate tabs and spaces, forcing at least one */
oldindent = Max(oldindent, newindent + 1);
while (newindent < oldindent)
{
int newindent_if_tab = newindent + 8 - (newindent % 8);
if (newindent_if_tab <= oldindent)
{
appendPQExpBufferChar(newline, '\t');
newindent = newindent_if_tab;
}
else
{
appendPQExpBufferChar(newline, ' ');
newindent++;
}
}
/* and finally append the old comment */
appendPQExpBufferStr(newline, where);
/* we'll have appended the original newline; don't add another */
}
else
appendPQExpBufferChar(newline, '\n');
free(lines[i]);
lines[i] = newline->data;
break; /* assume there's only one match */
}
if (lines[i] == NULL)
{
/*
* No match, so append a new entry. (We rely on the bootstrap server
* to complain if it's not a valid GUC name.)
*/
appendPQExpBufferChar(newline, '\n');
lines = pg_realloc_array(lines, char *, i + 2);
lines[i++] = newline->data;
lines[i] = NULL; /* keep the array null-terminated */
}
free(newline); /* but don't free newline->data */
return lines;
}
/*
* Decide if we should quote a replacement GUC value. We aren't too tense
* here, but we'd like to avoid quoting simple identifiers and numbers
* with units, which are common cases.
*/
static bool
guc_value_requires_quotes(const char *guc_value)
{
/* Don't use <ctype.h> macros here, they might accept too much */
#define LETTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define DIGITS "0123456789"
if (*guc_value == '\0')
return true; /* empty string must be quoted */
if (strchr(LETTERS, *guc_value))
{
if (strspn(guc_value, LETTERS DIGITS) == strlen(guc_value))
return false; /* it's an identifier */
return true; /* nope */
}
if (strchr(DIGITS, *guc_value))
{
/* skip over digits */
guc_value += strspn(guc_value, DIGITS);
/* there can be zero or more unit letters after the digits */
if (strspn(guc_value, LETTERS) == strlen(guc_value))
return false; /* it's a number, possibly with units */
return true; /* nope */
}
return true; /* all else must be quoted */
}
/*
* get the lines from a text file
*
* The result is a malloc'd array of individually malloc'd strings.
*/
static char **
readfile(const char *path)
{
char **result;
FILE *infile;
StringInfoData line;
int maxlines;
int n;
if ((infile = fopen(path, "r")) == NULL)
pg_fatal("could not open file \"%s\" for reading: %m", path);
initStringInfo(&line);
maxlines = 1024;
result = (char **) pg_malloc(maxlines * sizeof(char *));
n = 0;
while (pg_get_line_buf(infile, &line))
{
/* make sure there will be room for a trailing NULL pointer */
if (n >= maxlines - 1)
{
maxlines *= 2;
result = (char **) pg_realloc(result, maxlines * sizeof(char *));
}
result[n++] = pg_strdup(line.data);
}
result[n] = NULL;
pfree(line.data);
fclose(infile);
return result;
}
/*
* write an array of lines to a file
*
* "lines" must be a malloc'd array of individually malloc'd strings.
* All that data is freed here.
*
* This is only used to write text files. Use fopen "w" not PG_BINARY_W
* so that the resulting configuration files are nicely editable on Windows.
*/
static void
writefile(char *path, char **lines)
{
FILE *out_file;
char **line;
if ((out_file = fopen(path, "w")) == NULL)
pg_fatal("could not open file \"%s\" for writing: %m", path);
for (line = lines; *line != NULL; line++)
{
if (fputs(*line, out_file) < 0)
pg_fatal("could not write file \"%s\": %m", path);
free(*line);
}
if (fclose(out_file))
pg_fatal("could not close file \"%s\": %m", path);
free(lines);
}
/*
* Open a subcommand with suitable error messaging
*/
static FILE *
popen_check(const char *command, const char *mode)
{
FILE *cmdfd;
fflush(NULL);
errno = 0;
cmdfd = popen(command, mode);
if (cmdfd == NULL)
pg_log_error("could not execute command \"%s\": %m", command);
return cmdfd;
}
/*
* clean up any files we created on failure
* if we created the data directory remove it too
*/
static void
cleanup_directories_atexit(void)
{
if (success)
return;
if (!noclean)
{
if (made_new_pgdata)
{
pg_log_info("removing data directory \"%s\"", pg_data);
if (!rmtree(pg_data, true))
pg_log_error("failed to remove data directory");
}
else if (found_existing_pgdata)
{
pg_log_info("removing contents of data directory \"%s\"",
pg_data);
if (!rmtree(pg_data, false))
pg_log_error("failed to remove contents of data directory");
}
if (made_new_xlogdir)
{
pg_log_info("removing WAL directory \"%s\"", xlog_dir);
if (!rmtree(xlog_dir, true))
pg_log_error("failed to remove WAL directory");
}
else if (found_existing_xlogdir)
{
pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
if (!rmtree(xlog_dir, false))
pg_log_error("failed to remove contents of WAL directory");
}
/* otherwise died during startup, do nothing! */
}
else
{
if (made_new_pgdata || found_existing_pgdata)
pg_log_info("data directory \"%s\" not removed at user's request",
pg_data);
if (made_new_xlogdir || found_existing_xlogdir)
pg_log_info("WAL directory \"%s\" not removed at user's request",
xlog_dir);
}
}
/*
* find the current user
*
* on unix make sure it isn't root
*/
static char *
get_id(void)
{
const char *username;
#ifndef WIN32
if (geteuid() == 0) /* 0 is root's uid */
{
pg_log_error("cannot be run as root");
pg_log_error_hint("Please log in (using, e.g., \"su\") as the (unprivileged) user that will own the server process.");
exit(1);
}
#endif
username = get_user_name_or_exit(progname);
return pg_strdup(username);
}
static char *
encodingid_to_string(int enc)
{
char result[20];
sprintf(result, "%d", enc);
return pg_strdup(result);
}
/*
* get the encoding id for a given encoding name
*/
static int
get_encoding_id(const char *encoding_name)
{
int enc;
if (encoding_name && *encoding_name)
{
if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
return enc;
}
pg_fatal("\"%s\" is not a valid server encoding name",
encoding_name ? encoding_name : "(null)");
}
/*
* Support for determining the best default text search configuration.
* We key this off the first part of LC_CTYPE (ie, the language name).
*/
struct tsearch_config_match
{
const char *tsconfname;
const char *langname;
};
static const struct tsearch_config_match tsearch_config_languages[] =
{
{"arabic", "ar"},
{"arabic", "Arabic"},
{"armenian", "hy"},
{"armenian", "Armenian"},
{"basque", "eu"},
{"basque", "Basque"},
{"catalan", "ca"},
{"catalan", "Catalan"},
{"danish", "da"},
{"danish", "Danish"},
{"dutch", "nl"},
{"dutch", "Dutch"},
{"english", "C"},
{"english", "POSIX"},
{"english", "en"},
{"english", "English"},
{"finnish", "fi"},
{"finnish", "Finnish"},
{"french", "fr"},
{"french", "French"},
{"german", "de"},
{"german", "German"},
{"greek", "el"},
{"greek", "Greek"},
{"hindi", "hi"},
{"hindi", "Hindi"},
{"hungarian", "hu"},
{"hungarian", "Hungarian"},
{"indonesian", "id"},
{"indonesian", "Indonesian"},
{"irish", "ga"},
{"irish", "Irish"},
{"italian", "it"},
{"italian", "Italian"},
{"lithuanian", "lt"},
{"lithuanian", "Lithuanian"},
{"nepali", "ne"},
{"nepali", "Nepali"},
{"norwegian", "no"},
{"norwegian", "Norwegian"},
{"portuguese", "pt"},
{"portuguese", "Portuguese"},
{"romanian", "ro"},
{"russian", "ru"},
{"russian", "Russian"},
{"serbian", "sr"},
{"serbian", "Serbian"},
{"spanish", "es"},
{"spanish", "Spanish"},
{"swedish", "sv"},
{"swedish", "Swedish"},
{"tamil", "ta"},
{"tamil", "Tamil"},
{"turkish", "tr"},
{"turkish", "Turkish"},
{"yiddish", "yi"},
{"yiddish", "Yiddish"},
{NULL, NULL} /* end marker */
};
/*
* Look for a text search configuration matching lc_ctype, and return its
* name; return NULL if no match.
*/
static const char *
find_matching_ts_config(const char *lc_type)
{
int i;
char *langname,
*ptr;
/*
* Convert lc_ctype to a language name by stripping everything after an
* underscore (usual case) or a hyphen (Windows "locale name"; see
* comments at IsoLocaleName()).
*
* XXX Should ' ' be a stop character? This would select "norwegian" for
* the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
* should also accept the "nn" and "nb" Unix locales.
*
* Just for paranoia, we also stop at '.' or '@'.
*/
if (lc_type == NULL)
langname = pg_strdup("");
else
{
ptr = langname = pg_strdup(lc_type);
while (*ptr &&
*ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
ptr++;
*ptr = '\0';
}
for (i = 0; tsearch_config_languages[i].tsconfname; i++)
{
if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
{
free(langname);
return tsearch_config_languages[i].tsconfname;
}
}
free(langname);
return NULL;
}
/*
* set name of given input file variable under data directory
*/
static void
set_input(char **dest, const char *filename)
{
*dest = psprintf("%s/%s", share_path, filename);
}
/*
* check that given input file exists
*/
static void
check_input(char *path)
{
struct stat statbuf;
if (stat(path, &statbuf) != 0)
{
if (errno == ENOENT)
{
pg_log_error("file \"%s\" does not exist", path);
pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
}
else
{
pg_log_error("could not access file \"%s\": %m", path);
pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
}
exit(1);
}
if (!S_ISREG(statbuf.st_mode))
{
pg_log_error("file \"%s\" is not a regular file", path);
pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
exit(1);
}
}
/*
* write out the PG_VERSION file in the data dir, or its subdirectory
* if extrapath is not NULL
*/
static void
write_version_file(const char *extrapath)
{
FILE *version_file;
char *path;
if (extrapath == NULL)
path = psprintf("%s/PG_VERSION", pg_data);
else
path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
pg_fatal("could not open file \"%s\" for writing: %m", path);
if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
fclose(version_file))
pg_fatal("could not write file \"%s\": %m", path);
free(path);
}
/*
* set up an empty config file so we can check config settings by launching
* a test backend
*/
static void
set_null_conf(void)
{
FILE *conf_file;
char *path;
path = psprintf("%s/postgresql.conf", pg_data);
conf_file = fopen(path, PG_BINARY_W);
if (conf_file == NULL)
pg_fatal("could not open file \"%s\" for writing: %m", path);
if (fclose(conf_file))
pg_fatal("could not write file \"%s\": %m", path);
free(path);
}