PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/bin/initdb/initdb.c

https://github.com/matheusoliveira/postgres
C | 3747 lines | 3647 code | 29 blank | 71 comment | 47 complexity | 2d22945f8e972c2770d7b1390b057063 MD5 | raw file
Possible License(s): AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  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-2014, 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. #include "postgres_fe.h"
  49. #include <dirent.h>
  50. #include <fcntl.h>
  51. #include <sys/stat.h>
  52. #include <unistd.h>
  53. #include <locale.h>
  54. #include <signal.h>
  55. #include <time.h>
  56. #ifdef HAVE_SHM_OPEN
  57. #include "sys/mman.h"
  58. #endif
  59. #include "common/username.h"
  60. #include "mb/pg_wchar.h"
  61. #include "getaddrinfo.h"
  62. #include "getopt_long.h"
  63. #include "miscadmin.h"
  64. /* Ideally this would be in a .h file, but it hardly seems worth the trouble */
  65. extern const char *select_default_timezone(const char *share_path);
  66. static const char *auth_methods_host[] = {"trust", "reject", "md5", "password", "ident", "radius",
  67. #ifdef ENABLE_GSS
  68. "gss",
  69. #endif
  70. #ifdef ENABLE_SSPI
  71. "sspi",
  72. #endif
  73. #ifdef USE_PAM
  74. "pam", "pam ",
  75. #endif
  76. #ifdef USE_LDAP
  77. "ldap",
  78. #endif
  79. #ifdef USE_SSL
  80. "cert",
  81. #endif
  82. NULL};
  83. static const char *auth_methods_local[] = {"trust", "reject", "md5", "password", "peer", "radius",
  84. #ifdef USE_PAM
  85. "pam", "pam ",
  86. #endif
  87. #ifdef USE_LDAP
  88. "ldap",
  89. #endif
  90. NULL};
  91. /*
  92. * these values are passed in by makefile defines
  93. */
  94. static char *share_path = NULL;
  95. /* values to be obtained from arguments */
  96. static char *pg_data = "";
  97. static char *encoding = "";
  98. static char *locale = "";
  99. static char *lc_collate = "";
  100. static char *lc_ctype = "";
  101. static char *lc_monetary = "";
  102. static char *lc_numeric = "";
  103. static char *lc_time = "";
  104. static char *lc_messages = "";
  105. static const char *default_text_search_config = "";
  106. static char *username = "";
  107. static bool pwprompt = false;
  108. static char *pwfilename = NULL;
  109. static const char *authmethodhost = "";
  110. static const char *authmethodlocal = "";
  111. static bool debug = false;
  112. static bool noclean = false;
  113. static bool do_sync = true;
  114. static bool sync_only = false;
  115. static bool show_setting = false;
  116. static bool data_checksums = false;
  117. static char *xlog_dir = "";
  118. /* internal vars */
  119. static const char *progname;
  120. static char *encodingid = "0";
  121. static char *bki_file;
  122. static char *desc_file;
  123. static char *shdesc_file;
  124. static char *hba_file;
  125. static char *ident_file;
  126. static char *conf_file;
  127. static char *conversion_file;
  128. static char *dictionary_file;
  129. static char *info_schema_file;
  130. static char *features_file;
  131. static char *system_views_file;
  132. static bool made_new_pgdata = false;
  133. static bool found_existing_pgdata = false;
  134. static bool made_new_xlogdir = false;
  135. static bool found_existing_xlogdir = false;
  136. static char infoversion[100];
  137. static bool caught_signal = false;
  138. static bool output_failed = false;
  139. static int output_errno = 0;
  140. static char *pgdata_native;
  141. /* defaults */
  142. static int n_connections = 10;
  143. static int n_buffers = 50;
  144. static char *dynamic_shared_memory_type = NULL;
  145. /*
  146. * Warning messages for authentication methods
  147. */
  148. #define AUTHTRUST_WARNING \
  149. "# CAUTION: Configuring the system for local \"trust\" authentication\n" \
  150. "# allows any local user to connect as any PostgreSQL user, including\n" \
  151. "# the database superuser. If you do not trust all your local users,\n" \
  152. "# use another authentication method.\n"
  153. static char *authwarning = NULL;
  154. /*
  155. * Centralized knowledge of switches to pass to backend
  156. *
  157. * Note: we run the backend with -F (fsync disabled) and then do a single
  158. * pass of fsync'ing at the end. This is faster than fsync'ing each step.
  159. *
  160. * Note: in the shell-script version, we also passed PGDATA as a -D switch,
  161. * but here it is more convenient to pass it as an environment variable
  162. * (no quoting to worry about).
  163. */
  164. static const char *boot_options = "-F";
  165. static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true";
  166. #ifdef WIN32
  167. char *restrict_env;
  168. #endif
  169. static const char *subdirs[] = {
  170. "global",
  171. "pg_xlog",
  172. "pg_xlog/archive_status",
  173. "pg_clog",
  174. "pg_dynshmem",
  175. "pg_notify",
  176. "pg_serial",
  177. "pg_snapshots",
  178. "pg_subtrans",
  179. "pg_twophase",
  180. "pg_multixact/members",
  181. "pg_multixact/offsets",
  182. "base",
  183. "base/1",
  184. "pg_replslot",
  185. "pg_tblspc",
  186. "pg_stat",
  187. "pg_stat_tmp",
  188. "pg_logical",
  189. "pg_logical/snapshots",
  190. "pg_logical/mappings"
  191. };
  192. /* path to 'initdb' binary directory */
  193. static char bin_path[MAXPGPATH];
  194. static char backend_exec[MAXPGPATH];
  195. static char **replace_token(char **lines,
  196. const char *token, const char *replacement);
  197. #ifndef HAVE_UNIX_SOCKETS
  198. static char **filter_lines_with_token(char **lines, const char *token);
  199. #endif
  200. static char **readfile(const char *path);
  201. static void writefile(char *path, char **lines);
  202. static void walkdir(char *path, void (*action) (char *fname, bool isdir));
  203. static void pre_sync_fname(char *fname, bool isdir);
  204. static void fsync_fname(char *fname, bool isdir);
  205. static FILE *popen_check(const char *command, const char *mode);
  206. static void exit_nicely(void);
  207. static char *get_id(void);
  208. static char *get_encoding_id(char *encoding_name);
  209. static bool mkdatadir(const char *subdir);
  210. static void set_input(char **dest, char *filename);
  211. static void check_input(char *path);
  212. static void write_version_file(char *extrapath);
  213. static void set_null_conf(void);
  214. static void test_config_settings(void);
  215. static void setup_config(void);
  216. static void bootstrap_template1(void);
  217. static void setup_auth(void);
  218. static void get_set_pwd(void);
  219. static void setup_depend(void);
  220. static void setup_sysviews(void);
  221. static void setup_description(void);
  222. static void setup_collation(void);
  223. static void setup_conversion(void);
  224. static void setup_dictionary(void);
  225. static void setup_privileges(void);
  226. static void set_info_version(void);
  227. static void setup_schema(void);
  228. static void load_plpgsql(void);
  229. static void vacuum_db(void);
  230. static void make_template0(void);
  231. static void make_postgres(void);
  232. static void perform_fsync(void);
  233. static void trapsig(int signum);
  234. static void check_ok(void);
  235. static char *escape_quotes(const char *src);
  236. static int locale_date_order(const char *locale);
  237. static void check_locale_name(int category, const char *locale,
  238. char **canonname);
  239. static bool check_locale_encoding(const char *locale, int encoding);
  240. static void setlocales(void);
  241. static void usage(const char *progname);
  242. void get_restricted_token(void);
  243. void setup_pgdata(void);
  244. void setup_bin_paths(const char *argv0);
  245. void setup_data_file_paths(void);
  246. void setup_locale_encoding(void);
  247. void setup_signals(void);
  248. void setup_text_search(void);
  249. void create_data_directory(void);
  250. void create_xlog_symlink(void);
  251. void warn_on_mount_point(int error);
  252. void initialize_data_directory(void);
  253. #ifdef WIN32
  254. static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo);
  255. #endif
  256. /*
  257. * macros for running pipes to postgres
  258. */
  259. #define PG_CMD_DECL char cmd[MAXPGPATH]; FILE *cmdfd
  260. #define PG_CMD_OPEN \
  261. do { \
  262. cmdfd = popen_check(cmd, "w"); \
  263. if (cmdfd == NULL) \
  264. exit_nicely(); /* message already printed by popen_check */ \
  265. } while (0)
  266. #define PG_CMD_CLOSE \
  267. do { \
  268. if (pclose_check(cmdfd)) \
  269. exit_nicely(); /* message already printed by pclose_check */ \
  270. } while (0)
  271. #define PG_CMD_PUTS(line) \
  272. do { \
  273. if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
  274. output_failed = true, output_errno = errno; \
  275. } while (0)
  276. #define PG_CMD_PRINTF1(fmt, arg1) \
  277. do { \
  278. if (fprintf(cmdfd, fmt, arg1) < 0 || fflush(cmdfd) < 0) \
  279. output_failed = true, output_errno = errno; \
  280. } while (0)
  281. #define PG_CMD_PRINTF2(fmt, arg1, arg2) \
  282. do { \
  283. if (fprintf(cmdfd, fmt, arg1, arg2) < 0 || fflush(cmdfd) < 0) \
  284. output_failed = true, output_errno = errno; \
  285. } while (0)
  286. #define PG_CMD_PRINTF3(fmt, arg1, arg2, arg3) \
  287. do { \
  288. if (fprintf(cmdfd, fmt, arg1, arg2, arg3) < 0 || fflush(cmdfd) < 0) \
  289. output_failed = true, output_errno = errno; \
  290. } while (0)
  291. #ifndef WIN32
  292. #define QUOTE_PATH ""
  293. #define DIR_SEP "/"
  294. #else
  295. #define QUOTE_PATH "\""
  296. #define DIR_SEP "\\"
  297. #endif
  298. static char *
  299. escape_quotes(const char *src)
  300. {
  301. char *result = escape_single_quotes_ascii(src);
  302. if (!result)
  303. {
  304. fprintf(stderr, _("%s: out of memory\n"), progname);
  305. exit(1);
  306. }
  307. return result;
  308. }
  309. /*
  310. * make a copy of the array of lines, with token replaced by replacement
  311. * the first time it occurs on each line.
  312. *
  313. * This does most of what sed was used for in the shell script, but
  314. * doesn't need any regexp stuff.
  315. */
  316. static char **
  317. replace_token(char **lines, const char *token, const char *replacement)
  318. {
  319. int numlines = 1;
  320. int i;
  321. char **result;
  322. int toklen,
  323. replen,
  324. diff;
  325. for (i = 0; lines[i]; i++)
  326. numlines++;
  327. result = (char **) pg_malloc(numlines * sizeof(char *));
  328. toklen = strlen(token);
  329. replen = strlen(replacement);
  330. diff = replen - toklen;
  331. for (i = 0; i < numlines; i++)
  332. {
  333. char *where;
  334. char *newline;
  335. int pre;
  336. /* just copy pointer if NULL or no change needed */
  337. if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
  338. {
  339. result[i] = lines[i];
  340. continue;
  341. }
  342. /* if we get here a change is needed - set up new line */
  343. newline = (char *) pg_malloc(strlen(lines[i]) + diff + 1);
  344. pre = where - lines[i];
  345. strncpy(newline, lines[i], pre);
  346. strcpy(newline + pre, replacement);
  347. strcpy(newline + pre + replen, lines[i] + pre + toklen);
  348. result[i] = newline;
  349. }
  350. return result;
  351. }
  352. /*
  353. * make a copy of lines without any that contain the token
  354. *
  355. * a sort of poor man's grep -v
  356. */
  357. #ifndef HAVE_UNIX_SOCKETS
  358. static char **
  359. filter_lines_with_token(char **lines, const char *token)
  360. {
  361. int numlines = 1;
  362. int i,
  363. src,
  364. dst;
  365. char **result;
  366. for (i = 0; lines[i]; i++)
  367. numlines++;
  368. result = (char **) pg_malloc(numlines * sizeof(char *));
  369. for (src = 0, dst = 0; src < numlines; src++)
  370. {
  371. if (lines[src] == NULL || strstr(lines[src], token) == NULL)
  372. result[dst++] = lines[src];
  373. }
  374. return result;
  375. }
  376. #endif
  377. /*
  378. * get the lines from a text file
  379. */
  380. static char **
  381. readfile(const char *path)
  382. {
  383. FILE *infile;
  384. int maxlength = 1,
  385. linelen = 0;
  386. int nlines = 0;
  387. int n;
  388. char **result;
  389. char *buffer;
  390. int c;
  391. if ((infile = fopen(path, "r")) == NULL)
  392. {
  393. fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
  394. progname, path, strerror(errno));
  395. exit_nicely();
  396. }
  397. /* pass over the file twice - the first time to size the result */
  398. while ((c = fgetc(infile)) != EOF)
  399. {
  400. linelen++;
  401. if (c == '\n')
  402. {
  403. nlines++;
  404. if (linelen > maxlength)
  405. maxlength = linelen;
  406. linelen = 0;
  407. }
  408. }
  409. /* handle last line without a terminating newline (yuck) */
  410. if (linelen)
  411. nlines++;
  412. if (linelen > maxlength)
  413. maxlength = linelen;
  414. /* set up the result and the line buffer */
  415. result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
  416. buffer = (char *) pg_malloc(maxlength + 1);
  417. /* now reprocess the file and store the lines */
  418. rewind(infile);
  419. n = 0;
  420. while (fgets(buffer, maxlength + 1, infile) != NULL && n < nlines)
  421. result[n++] = pg_strdup(buffer);
  422. fclose(infile);
  423. free(buffer);
  424. result[n] = NULL;
  425. return result;
  426. }
  427. /*
  428. * write an array of lines to a file
  429. *
  430. * This is only used to write text files. Use fopen "w" not PG_BINARY_W
  431. * so that the resulting configuration files are nicely editable on Windows.
  432. */
  433. static void
  434. writefile(char *path, char **lines)
  435. {
  436. FILE *out_file;
  437. char **line;
  438. if ((out_file = fopen(path, "w")) == NULL)
  439. {
  440. fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
  441. progname, path, strerror(errno));
  442. exit_nicely();
  443. }
  444. for (line = lines; *line != NULL; line++)
  445. {
  446. if (fputs(*line, out_file) < 0)
  447. {
  448. fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
  449. progname, path, strerror(errno));
  450. exit_nicely();
  451. }
  452. free(*line);
  453. }
  454. if (fclose(out_file))
  455. {
  456. fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
  457. progname, path, strerror(errno));
  458. exit_nicely();
  459. }
  460. }
  461. /*
  462. * walkdir: recursively walk a directory, applying the action to each
  463. * regular file and directory (including the named directory itself).
  464. *
  465. * Adapted from copydir() in copydir.c.
  466. */
  467. static void
  468. walkdir(char *path, void (*action) (char *fname, bool isdir))
  469. {
  470. DIR *dir;
  471. struct dirent *direntry;
  472. char subpath[MAXPGPATH];
  473. dir = opendir(path);
  474. if (dir == NULL)
  475. {
  476. fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
  477. progname, path, strerror(errno));
  478. exit_nicely();
  479. }
  480. while (errno = 0, (direntry = readdir(dir)) != NULL)
  481. {
  482. struct stat fst;
  483. if (strcmp(direntry->d_name, ".") == 0 ||
  484. strcmp(direntry->d_name, "..") == 0)
  485. continue;
  486. snprintf(subpath, MAXPGPATH, "%s/%s", path, direntry->d_name);
  487. if (lstat(subpath, &fst) < 0)
  488. {
  489. fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
  490. progname, subpath, strerror(errno));
  491. exit_nicely();
  492. }
  493. if (S_ISDIR(fst.st_mode))
  494. walkdir(subpath, action);
  495. else if (S_ISREG(fst.st_mode))
  496. (*action) (subpath, false);
  497. }
  498. if (errno)
  499. {
  500. fprintf(stderr, _("%s: could not read directory \"%s\": %s\n"),
  501. progname, path, strerror(errno));
  502. exit_nicely();
  503. }
  504. if (closedir(dir))
  505. {
  506. fprintf(stderr, _("%s: could not close directory \"%s\": %s\n"),
  507. progname, path, strerror(errno));
  508. exit_nicely();
  509. }
  510. /*
  511. * It's important to fsync the destination directory itself as individual
  512. * file fsyncs don't guarantee that the directory entry for the file is
  513. * synced. Recent versions of ext4 have made the window much wider but
  514. * it's been an issue for ext3 and other filesystems in the past.
  515. */
  516. (*action) (path, true);
  517. }
  518. /*
  519. * Hint to the OS that it should get ready to fsync() this file.
  520. */
  521. static void
  522. pre_sync_fname(char *fname, bool isdir)
  523. {
  524. #if defined(HAVE_SYNC_FILE_RANGE) || \
  525. (defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED))
  526. int fd;
  527. fd = open(fname, O_RDONLY | PG_BINARY);
  528. /*
  529. * Some OSs don't allow us to open directories at all (Windows returns
  530. * EACCES)
  531. */
  532. if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
  533. return;
  534. if (fd < 0)
  535. {
  536. fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
  537. progname, fname, strerror(errno));
  538. exit_nicely();
  539. }
  540. /*
  541. * Prefer sync_file_range, else use posix_fadvise. We ignore any error
  542. * here since this operation is only a hint anyway.
  543. */
  544. #if defined(HAVE_SYNC_FILE_RANGE)
  545. sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WRITE);
  546. #elif defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
  547. posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
  548. #endif
  549. close(fd);
  550. #endif
  551. }
  552. /*
  553. * fsync a file or directory
  554. *
  555. * Try to fsync directories but ignore errors that indicate the OS
  556. * just doesn't allow/require fsyncing directories.
  557. *
  558. * Adapted from fsync_fname() in copydir.c.
  559. */
  560. static void
  561. fsync_fname(char *fname, bool isdir)
  562. {
  563. int fd;
  564. int returncode;
  565. /*
  566. * Some OSs require directories to be opened read-only whereas other
  567. * systems don't allow us to fsync files opened read-only; so we need both
  568. * cases here
  569. */
  570. if (!isdir)
  571. fd = open(fname, O_RDWR | PG_BINARY);
  572. else
  573. fd = open(fname, O_RDONLY | PG_BINARY);
  574. /*
  575. * Some OSs don't allow us to open directories at all (Windows returns
  576. * EACCES)
  577. */
  578. if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
  579. return;
  580. else if (fd < 0)
  581. {
  582. fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
  583. progname, fname, strerror(errno));
  584. exit_nicely();
  585. }
  586. returncode = fsync(fd);
  587. /* Some OSs don't allow us to fsync directories at all */
  588. if (returncode != 0 && isdir && errno == EBADF)
  589. {
  590. close(fd);
  591. return;
  592. }
  593. if (returncode != 0)
  594. {
  595. fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
  596. progname, fname, strerror(errno));
  597. exit_nicely();
  598. }
  599. close(fd);
  600. }
  601. /*
  602. * Open a subcommand with suitable error messaging
  603. */
  604. static FILE *
  605. popen_check(const char *command, const char *mode)
  606. {
  607. FILE *cmdfd;
  608. fflush(stdout);
  609. fflush(stderr);
  610. errno = 0;
  611. cmdfd = popen(command, mode);
  612. if (cmdfd == NULL)
  613. fprintf(stderr, _("%s: could not execute command \"%s\": %s\n"),
  614. progname, command, strerror(errno));
  615. return cmdfd;
  616. }
  617. /*
  618. * clean up any files we created on failure
  619. * if we created the data directory remove it too
  620. */
  621. static void
  622. exit_nicely(void)
  623. {
  624. if (!noclean)
  625. {
  626. if (made_new_pgdata)
  627. {
  628. fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
  629. progname, pg_data);
  630. if (!rmtree(pg_data, true))
  631. fprintf(stderr, _("%s: failed to remove data directory\n"),
  632. progname);
  633. }
  634. else if (found_existing_pgdata)
  635. {
  636. fprintf(stderr,
  637. _("%s: removing contents of data directory \"%s\"\n"),
  638. progname, pg_data);
  639. if (!rmtree(pg_data, false))
  640. fprintf(stderr, _("%s: failed to remove contents of data directory\n"),
  641. progname);
  642. }
  643. if (made_new_xlogdir)
  644. {
  645. fprintf(stderr, _("%s: removing transaction log directory \"%s\"\n"),
  646. progname, xlog_dir);
  647. if (!rmtree(xlog_dir, true))
  648. fprintf(stderr, _("%s: failed to remove transaction log directory\n"),
  649. progname);
  650. }
  651. else if (found_existing_xlogdir)
  652. {
  653. fprintf(stderr,
  654. _("%s: removing contents of transaction log directory \"%s\"\n"),
  655. progname, xlog_dir);
  656. if (!rmtree(xlog_dir, false))
  657. fprintf(stderr, _("%s: failed to remove contents of transaction log directory\n"),
  658. progname);
  659. }
  660. /* otherwise died during startup, do nothing! */
  661. }
  662. else
  663. {
  664. if (made_new_pgdata || found_existing_pgdata)
  665. fprintf(stderr,
  666. _("%s: data directory \"%s\" not removed at user's request\n"),
  667. progname, pg_data);
  668. if (made_new_xlogdir || found_existing_xlogdir)
  669. fprintf(stderr,
  670. _("%s: transaction log directory \"%s\" not removed at user's request\n"),
  671. progname, xlog_dir);
  672. }
  673. exit(1);
  674. }
  675. /*
  676. * find the current user
  677. *
  678. * on unix make sure it isn't root
  679. */
  680. static char *
  681. get_id(void)
  682. {
  683. const char *username;
  684. #ifndef WIN32
  685. if (geteuid() == 0) /* 0 is root's uid */
  686. {
  687. fprintf(stderr,
  688. _("%s: cannot be run as root\n"
  689. "Please log in (using, e.g., \"su\") as the "
  690. "(unprivileged) user that will\n"
  691. "own the server process.\n"),
  692. progname);
  693. exit(1);
  694. }
  695. #endif
  696. username = get_user_name_or_exit(progname);
  697. return pg_strdup(username);
  698. }
  699. static char *
  700. encodingid_to_string(int enc)
  701. {
  702. char result[20];
  703. sprintf(result, "%d", enc);
  704. return pg_strdup(result);
  705. }
  706. /*
  707. * get the encoding id for a given encoding name
  708. */
  709. static char *
  710. get_encoding_id(char *encoding_name)
  711. {
  712. int enc;
  713. if (encoding_name && *encoding_name)
  714. {
  715. if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
  716. return encodingid_to_string(enc);
  717. }
  718. fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
  719. progname, encoding_name ? encoding_name : "(null)");
  720. exit(1);
  721. }
  722. /*
  723. * Support for determining the best default text search configuration.
  724. * We key this off the first part of LC_CTYPE (ie, the language name).
  725. */
  726. struct tsearch_config_match
  727. {
  728. const char *tsconfname;
  729. const char *langname;
  730. };
  731. static const struct tsearch_config_match tsearch_config_languages[] =
  732. {
  733. {"danish", "da"},
  734. {"danish", "Danish"},
  735. {"dutch", "nl"},
  736. {"dutch", "Dutch"},
  737. {"english", "C"},
  738. {"english", "POSIX"},
  739. {"english", "en"},
  740. {"english", "English"},
  741. {"finnish", "fi"},
  742. {"finnish", "Finnish"},
  743. {"french", "fr"},
  744. {"french", "French"},
  745. {"german", "de"},
  746. {"german", "German"},
  747. {"hungarian", "hu"},
  748. {"hungarian", "Hungarian"},
  749. {"italian", "it"},
  750. {"italian", "Italian"},
  751. {"norwegian", "no"},
  752. {"norwegian", "Norwegian"},
  753. {"portuguese", "pt"},
  754. {"portuguese", "Portuguese"},
  755. {"romanian", "ro"},
  756. {"russian", "ru"},
  757. {"russian", "Russian"},
  758. {"spanish", "es"},
  759. {"spanish", "Spanish"},
  760. {"swedish", "sv"},
  761. {"swedish", "Swedish"},
  762. {"turkish", "tr"},
  763. {"turkish", "Turkish"},
  764. {NULL, NULL} /* end marker */
  765. };
  766. /*
  767. * Look for a text search configuration matching lc_ctype, and return its
  768. * name; return NULL if no match.
  769. */
  770. static const char *
  771. find_matching_ts_config(const char *lc_type)
  772. {
  773. int i;
  774. char *langname,
  775. *ptr;
  776. /*
  777. * Convert lc_ctype to a language name by stripping everything after an
  778. * underscore (usual case) or a hyphen (Windows "locale name"; see
  779. * comments at IsoLocaleName()).
  780. *
  781. * XXX Should ' ' be a stop character? This would select "norwegian" for
  782. * the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
  783. * should also accept the "nn" and "nb" Unix locales.
  784. *
  785. * Just for paranoia, we also stop at '.' or '@'.
  786. */
  787. if (lc_type == NULL)
  788. langname = pg_strdup("");
  789. else
  790. {
  791. ptr = langname = pg_strdup(lc_type);
  792. while (*ptr &&
  793. *ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
  794. ptr++;
  795. *ptr = '\0';
  796. }
  797. for (i = 0; tsearch_config_languages[i].tsconfname; i++)
  798. {
  799. if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
  800. {
  801. free(langname);
  802. return tsearch_config_languages[i].tsconfname;
  803. }
  804. }
  805. free(langname);
  806. return NULL;
  807. }
  808. /*
  809. * make the data directory (or one of its subdirectories if subdir is not NULL)
  810. */
  811. static bool
  812. mkdatadir(const char *subdir)
  813. {
  814. char *path;
  815. if (subdir)
  816. path = psprintf("%s/%s", pg_data, subdir);
  817. else
  818. path = pg_strdup(pg_data);
  819. if (pg_mkdir_p(path, S_IRWXU) == 0)
  820. return true;
  821. fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
  822. progname, path, strerror(errno));
  823. return false;
  824. }
  825. /*
  826. * set name of given input file variable under data directory
  827. */
  828. static void
  829. set_input(char **dest, char *filename)
  830. {
  831. *dest = psprintf("%s/%s", share_path, filename);
  832. }
  833. /*
  834. * check that given input file exists
  835. */
  836. static void
  837. check_input(char *path)
  838. {
  839. struct stat statbuf;
  840. if (stat(path, &statbuf) != 0)
  841. {
  842. if (errno == ENOENT)
  843. {
  844. fprintf(stderr,
  845. _("%s: file \"%s\" does not exist\n"), progname, path);
  846. fprintf(stderr,
  847. _("This might mean you have a corrupted installation or identified\n"
  848. "the wrong directory with the invocation option -L.\n"));
  849. }
  850. else
  851. {
  852. fprintf(stderr,
  853. _("%s: could not access file \"%s\": %s\n"), progname, path,
  854. strerror(errno));
  855. fprintf(stderr,
  856. _("This might mean you have a corrupted installation or identified\n"
  857. "the wrong directory with the invocation option -L.\n"));
  858. }
  859. exit(1);
  860. }
  861. if (!S_ISREG(statbuf.st_mode))
  862. {
  863. fprintf(stderr,
  864. _("%s: file \"%s\" is not a regular file\n"), progname, path);
  865. fprintf(stderr,
  866. _("This might mean you have a corrupted installation or identified\n"
  867. "the wrong directory with the invocation option -L.\n"));
  868. exit(1);
  869. }
  870. }
  871. /*
  872. * write out the PG_VERSION file in the data dir, or its subdirectory
  873. * if extrapath is not NULL
  874. */
  875. static void
  876. write_version_file(char *extrapath)
  877. {
  878. FILE *version_file;
  879. char *path;
  880. if (extrapath == NULL)
  881. path = psprintf("%s/PG_VERSION", pg_data);
  882. else
  883. path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
  884. if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
  885. {
  886. fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
  887. progname, path, strerror(errno));
  888. exit_nicely();
  889. }
  890. if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
  891. fclose(version_file))
  892. {
  893. fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
  894. progname, path, strerror(errno));
  895. exit_nicely();
  896. }
  897. free(path);
  898. }
  899. /*
  900. * set up an empty config file so we can check config settings by launching
  901. * a test backend
  902. */
  903. static void
  904. set_null_conf(void)
  905. {
  906. FILE *conf_file;
  907. char *path;
  908. path = psprintf("%s/postgresql.conf", pg_data);
  909. conf_file = fopen(path, PG_BINARY_W);
  910. if (conf_file == NULL)
  911. {
  912. fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
  913. progname, path, strerror(errno));
  914. exit_nicely();
  915. }
  916. if (fclose(conf_file))
  917. {
  918. fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
  919. progname, path, strerror(errno));
  920. exit_nicely();
  921. }
  922. free(path);
  923. }
  924. /*
  925. * Determine which dynamic shared memory implementation should be used on
  926. * this platform. POSIX shared memory is preferable because the default
  927. * allocation limits are much higher than the limits for System V on most
  928. * systems that support both, but the fact that a platform has shm_open
  929. * doesn't guarantee that that call will succeed when attempted. So, we
  930. * attempt to reproduce what the postmaster will do when allocating a POSIX
  931. * segment in dsm_impl.c; if it doesn't work, we assume it won't work for
  932. * the postmaster either, and configure the cluster for System V shared
  933. * memory instead.
  934. */
  935. static char *
  936. choose_dsm_implementation(void)
  937. {
  938. #ifdef HAVE_SHM_OPEN
  939. int ntries = 10;
  940. while (ntries > 0)
  941. {
  942. uint32 handle;
  943. char name[64];
  944. int fd;
  945. handle = random();
  946. snprintf(name, 64, "/PostgreSQL.%u", handle);
  947. if ((fd = shm_open(name, O_CREAT | O_RDWR | O_EXCL, 0600)) != -1)
  948. {
  949. close(fd);
  950. shm_unlink(name);
  951. return "posix";
  952. }
  953. if (errno != EEXIST)
  954. break;
  955. --ntries;
  956. }
  957. #endif
  958. #ifdef WIN32
  959. return "windows";
  960. #else
  961. return "sysv";
  962. #endif
  963. }
  964. /*
  965. * Determine platform-specific config settings
  966. *
  967. * Use reasonable values if kernel will let us, else scale back. Probe
  968. * for max_connections first since it is subject to more constraints than
  969. * shared_buffers.
  970. */
  971. static void
  972. test_config_settings(void)
  973. {
  974. /*
  975. * This macro defines the minimum shared_buffers we want for a given
  976. * max_connections value. The arrays show the settings to try.
  977. */
  978. #define MIN_BUFS_FOR_CONNS(nconns) ((nconns) * 10)
  979. static const int trial_conns[] = {
  980. 100, 50, 40, 30, 20, 10
  981. };
  982. static const int trial_bufs[] = {
  983. 16384, 8192, 4096, 3584, 3072, 2560, 2048, 1536,
  984. 1000, 900, 800, 700, 600, 500,
  985. 400, 300, 200, 100, 50
  986. };
  987. char cmd[MAXPGPATH];
  988. const int connslen = sizeof(trial_conns) / sizeof(int);
  989. const int bufslen = sizeof(trial_bufs) / sizeof(int);
  990. int i,
  991. status,
  992. test_conns,
  993. test_buffs,
  994. ok_buffers = 0;
  995. printf(_("selecting default max_connections ... "));
  996. fflush(stdout);
  997. for (i = 0; i < connslen; i++)
  998. {
  999. test_conns = trial_conns[i];
  1000. test_buffs = MIN_BUFS_FOR_CONNS(test_conns);
  1001. snprintf(cmd, sizeof(cmd),
  1002. "\"%s\" --boot -x0 %s "
  1003. "-c max_connections=%d "
  1004. "-c shared_buffers=%d "
  1005. "-c dynamic_shared_memory_type=none "
  1006. "< \"%s\" > \"%s\" 2>&1",
  1007. backend_exec, boot_options,
  1008. test_conns, test_buffs,
  1009. DEVNULL, DEVNULL);
  1010. status = system(cmd);
  1011. if (status == 0)
  1012. {
  1013. ok_buffers = test_buffs;
  1014. break;
  1015. }
  1016. }
  1017. if (i >= connslen)
  1018. i = connslen - 1;
  1019. n_connections = trial_conns[i];
  1020. printf("%d\n", n_connections);
  1021. printf(_("selecting default shared_buffers ... "));
  1022. fflush(stdout);
  1023. for (i = 0; i < bufslen; i++)
  1024. {
  1025. /* Use same amount of memory, independent of BLCKSZ */
  1026. test_buffs = (trial_bufs[i] * 8192) / BLCKSZ;
  1027. if (test_buffs <= ok_buffers)
  1028. {
  1029. test_buffs = ok_buffers;
  1030. break;
  1031. }
  1032. snprintf(cmd, sizeof(cmd),
  1033. "\"%s\" --boot -x0 %s "
  1034. "-c max_connections=%d "
  1035. "-c shared_buffers=%d "
  1036. "-c dynamic_shared_memory_type=none "
  1037. "< \"%s\" > \"%s\" 2>&1",
  1038. backend_exec, boot_options,
  1039. n_connections, test_buffs,
  1040. DEVNULL, DEVNULL);
  1041. status = system(cmd);
  1042. if (status == 0)
  1043. break;
  1044. }
  1045. n_buffers = test_buffs;
  1046. if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
  1047. printf("%dMB\n", (n_buffers * (BLCKSZ / 1024)) / 1024);
  1048. else
  1049. printf("%dkB\n", n_buffers * (BLCKSZ / 1024));
  1050. printf(_("selecting dynamic shared memory implementation ... "));
  1051. fflush(stdout);
  1052. dynamic_shared_memory_type = choose_dsm_implementation();
  1053. printf("%s\n", dynamic_shared_memory_type);
  1054. }
  1055. /*
  1056. * set up all the config files
  1057. */
  1058. static void
  1059. setup_config(void)
  1060. {
  1061. char **conflines;
  1062. char repltok[MAXPGPATH];
  1063. char path[MAXPGPATH];
  1064. const char *default_timezone;
  1065. char *autoconflines[3];
  1066. fputs(_("creating configuration files ... "), stdout);
  1067. fflush(stdout);
  1068. /* postgresql.conf */
  1069. conflines = readfile(conf_file);
  1070. snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
  1071. conflines = replace_token(conflines, "#max_connections = 100", repltok);
  1072. if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
  1073. snprintf(repltok, sizeof(repltok), "shared_buffers = %dMB",
  1074. (n_buffers * (BLCKSZ / 1024)) / 1024);
  1075. else
  1076. snprintf(repltok, sizeof(repltok), "shared_buffers = %dkB",
  1077. n_buffers * (BLCKSZ / 1024));
  1078. conflines = replace_token(conflines, "#shared_buffers = 32MB", repltok);
  1079. #ifdef HAVE_UNIX_SOCKETS
  1080. snprintf(repltok, sizeof(repltok), "#unix_socket_directories = '%s'",
  1081. DEFAULT_PGSOCKET_DIR);
  1082. #else
  1083. snprintf(repltok, sizeof(repltok), "#unix_socket_directories = ''");
  1084. #endif
  1085. conflines = replace_token(conflines, "#unix_socket_directories = '/tmp'",
  1086. repltok);
  1087. #if DEF_PGPORT != 5432
  1088. snprintf(repltok, sizeof(repltok), "#port = %d", DEF_PGPORT);
  1089. conflines = replace_token(conflines, "#port = 5432", repltok);
  1090. #endif
  1091. snprintf(repltok, sizeof(repltok), "lc_messages = '%s'",
  1092. escape_quotes(lc_messages));
  1093. conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
  1094. snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'",
  1095. escape_quotes(lc_monetary));
  1096. conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
  1097. snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'",
  1098. escape_quotes(lc_numeric));
  1099. conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
  1100. snprintf(repltok, sizeof(repltok), "lc_time = '%s'",
  1101. escape_quotes(lc_time));
  1102. conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
  1103. switch (locale_date_order(lc_time))
  1104. {
  1105. case DATEORDER_YMD:
  1106. strcpy(repltok, "datestyle = 'iso, ymd'");
  1107. break;
  1108. case DATEORDER_DMY:
  1109. strcpy(repltok, "datestyle = 'iso, dmy'");
  1110. break;
  1111. case DATEORDER_MDY:
  1112. default:
  1113. strcpy(repltok, "datestyle = 'iso, mdy'");
  1114. break;
  1115. }
  1116. conflines = replace_token(conflines, "#datestyle = 'iso, mdy'", repltok);
  1117. snprintf(repltok, sizeof(repltok),
  1118. "default_text_search_config = 'pg_catalog.%s'",
  1119. escape_quotes(default_text_search_config));
  1120. conflines = replace_token(conflines,
  1121. "#default_text_search_config = 'pg_catalog.simple'",
  1122. repltok);
  1123. default_timezone = select_default_timezone(share_path);
  1124. if (default_timezone)
  1125. {
  1126. snprintf(repltok, sizeof(repltok), "timezone = '%s'",
  1127. escape_quotes(default_timezone));
  1128. conflines = replace_token(conflines, "#timezone = 'GMT'", repltok);
  1129. snprintf(repltok, sizeof(repltok), "log_timezone = '%s'",
  1130. escape_quotes(default_timezone));
  1131. conflines = replace_token(conflines, "#log_timezone = 'GMT'", repltok);
  1132. }
  1133. snprintf(repltok, sizeof(repltok), "dynamic_shared_memory_type = %s",
  1134. dynamic_shared_memory_type);
  1135. conflines = replace_token(conflines, "#dynamic_shared_memory_type = posix",
  1136. repltok);
  1137. snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
  1138. writefile(path, conflines);
  1139. if (chmod(path, S_IRUSR | S_IWUSR) != 0)
  1140. {
  1141. fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
  1142. progname, path, strerror(errno));
  1143. exit_nicely();
  1144. }
  1145. /*
  1146. * create the automatic configuration file to store the configuration
  1147. * parameters set by ALTER SYSTEM command. The parameters present in this
  1148. * file will override the value of parameters that exists before parse of
  1149. * this file.
  1150. */
  1151. autoconflines[0] = pg_strdup("# Do not edit this file manually!\n");
  1152. autoconflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
  1153. autoconflines[2] = NULL;
  1154. sprintf(path, "%s/%s", pg_data, PG_AUTOCONF_FILENAME);
  1155. writefile(path, autoconflines);
  1156. if (chmod(path, S_IRUSR | S_IWUSR) != 0)
  1157. {
  1158. fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
  1159. progname, path, strerror(errno));
  1160. exit_nicely();
  1161. }
  1162. free(conflines);
  1163. /* pg_hba.conf */
  1164. conflines = readfile(hba_file);
  1165. #ifndef HAVE_UNIX_SOCKETS
  1166. conflines = filter_lines_with_token(conflines, "@remove-line-for-nolocal@");
  1167. #else
  1168. conflines = replace_token(conflines, "@remove-line-for-nolocal@", "");
  1169. #endif
  1170. #ifdef HAVE_IPV6
  1171. /*
  1172. * Probe to see if there is really any platform support for IPv6, and
  1173. * comment out the relevant pg_hba line if not. This avoids runtime
  1174. * warnings if getaddrinfo doesn't actually cope with IPv6. Particularly
  1175. * useful on Windows, where executables built on a machine with IPv6 may
  1176. * have to run on a machine without.
  1177. */
  1178. {
  1179. struct addrinfo *gai_result;
  1180. struct addrinfo hints;
  1181. int err = 0;
  1182. #ifdef WIN32
  1183. /* need to call WSAStartup before calling getaddrinfo */
  1184. WSADATA wsaData;
  1185. err = WSAStartup(MAKEWORD(2, 2), &wsaData);
  1186. #endif
  1187. /* for best results, this code should match parse_hba() */
  1188. hints.ai_flags = AI_NUMERICHOST;
  1189. hints.ai_family = AF_UNSPEC;
  1190. hints.ai_socktype = 0;
  1191. hints.ai_protocol = 0;
  1192. hints.ai_addrlen = 0;
  1193. hints.ai_canonname = NULL;
  1194. hints.ai_addr = NULL;
  1195. hints.ai_next = NULL;
  1196. if (err != 0 ||
  1197. getaddrinfo("::1", NULL, &hints, &gai_result) != 0)
  1198. conflines = replace_token(conflines,
  1199. "host all all ::1",
  1200. "#host all all ::1");
  1201. }
  1202. #else /* !HAVE_IPV6 */
  1203. /* If we didn't compile IPV6 support at all, always comment it out */
  1204. conflines = replace_token(conflines,
  1205. "host all all ::1",
  1206. "#host all all ::1");
  1207. #endif /* HAVE_IPV6 */
  1208. /* Replace default authentication methods */
  1209. conflines = replace_token(conflines,
  1210. "@authmethodhost@",
  1211. authmethodhost);
  1212. conflines = replace_token(conflines,
  1213. "@authmethodlocal@",
  1214. authmethodlocal);
  1215. conflines = replace_token(conflines,
  1216. "@authcomment@",
  1217. (strcmp(authmethodlocal, "trust") == 0 || strcmp(authmethodhost, "trust") == 0) ? AUTHTRUST_WARNING : "");
  1218. /* Replace username for replication */
  1219. conflines = replace_token(conflines,
  1220. "@default_username@",
  1221. username);
  1222. snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
  1223. writefile(path, conflines);
  1224. if (chmod(path, S_IRUSR | S_IWUSR) != 0)
  1225. {
  1226. fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
  1227. progname, path, strerror(errno));
  1228. exit_nicely();
  1229. }
  1230. free(conflines);
  1231. /* pg_ident.conf */
  1232. conflines = readfile(ident_file);
  1233. snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
  1234. writefile(path, conflines);
  1235. if (chmod(path, S_IRUSR | S_IWUSR) != 0)
  1236. {
  1237. fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
  1238. progname, path, strerror(errno));
  1239. exit_nicely();
  1240. }
  1241. free(conflines);
  1242. check_ok();
  1243. }
  1244. /*
  1245. * run the BKI script in bootstrap mode to create template1
  1246. */
  1247. static void
  1248. bootstrap_template1(void)
  1249. {
  1250. PG_CMD_DECL;
  1251. char **line;
  1252. char *talkargs = "";
  1253. char **bki_lines;
  1254. char headerline[MAXPGPATH];
  1255. char buf[64];
  1256. printf(_("creating template1 database in %s/base/1 ... "), pg_data);
  1257. fflush(stdout);
  1258. if (debug)
  1259. talkargs = "-d 5";
  1260. bki_lines = readfile(bki_file);
  1261. /* Check that bki file appears to be of the right version */
  1262. snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
  1263. PG_MAJORVERSION);
  1264. if (strcmp(headerline, *bki_lines) != 0)
  1265. {
  1266. fprintf(stderr,
  1267. _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
  1268. "Check your installation or specify the correct path "
  1269. "using the option -L.\n"),
  1270. progname, bki_file, PG_VERSION);
  1271. exit_nicely();
  1272. }
  1273. /* Substitute for various symbols used in the BKI file */
  1274. sprintf(buf, "%d", NAMEDATALEN);
  1275. bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
  1276. sprintf(buf, "%d", (int) sizeof(Pointer));
  1277. bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
  1278. bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
  1279. (sizeof(Pointer) == 4) ? "i" : "d");
  1280. bki_lines = replace_token(bki_lines, "FLOAT4PASSBYVAL",
  1281. FLOAT4PASSBYVAL ? "true" : "false");
  1282. bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
  1283. FLOAT8PASSBYVAL ? "true" : "false");
  1284. bki_lines = replace_token(bki_lines, "POSTGRES", escape_quotes(username));
  1285. bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
  1286. bki_lines = replace_token(bki_lines, "LC_COLLATE", escape_quotes(lc_collate));
  1287. bki_lines = replace_token(bki_lines, "LC_CTYPE", escape_quotes(lc_ctype));
  1288. /*
  1289. * Pass correct LC_xxx environment to bootstrap.
  1290. *
  1291. * The shell script arranged to restore the LC settings afterwards, but
  1292. * there doesn't seem to be any compelling reason to do that.
  1293. */
  1294. snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
  1295. putenv(pg_strdup(cmd));
  1296. snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
  1297. putenv(pg_strdup(cmd));
  1298. unsetenv("LC_ALL");
  1299. /* Also ensure backend isn't confused by this environment var: */
  1300. unsetenv("PGCLIENTENCODING");
  1301. snprintf(cmd, sizeof(cmd),
  1302. "\"%s\" --boot -x1 %s %s %s",
  1303. backend_exec,
  1304. data_checksums ? "-k" : "",
  1305. boot_options, talkargs);
  1306. PG_CMD_OPEN;
  1307. for (line = bki_lines; *line != NULL; line++)
  1308. {
  1309. PG_CMD_PUTS(*line);
  1310. free(*line);
  1311. }
  1312. PG_CMD_CLOSE;
  1313. free(bki_lines);
  1314. check_ok();
  1315. }
  1316. /*
  1317. * set up the shadow password table
  1318. */
  1319. static void
  1320. setup_auth(void)
  1321. {
  1322. PG_CMD_DECL;
  1323. const char **line;
  1324. static const char *pg_authid_setup[] = {
  1325. /*
  1326. * The authid table shouldn't be readable except through views, to
  1327. * ensure passwords are not publicly visible.
  1328. */
  1329. "REVOKE ALL on pg_authid FROM public;\n",
  1330. NULL
  1331. };
  1332. fputs(_("initializing pg_authid ... "), stdout);
  1333. fflush(stdout);
  1334. snprintf(cmd, sizeof(cmd),
  1335. "\"%s\" %s template1 >%s",
  1336. backend_exec, backend_options,
  1337. DEVNULL);
  1338. PG_CMD_OPEN;
  1339. for (line = pg_authid_setup; *line != NULL; line++)
  1340. PG_CMD_PUTS(*line);
  1341. PG_CMD_CLOSE;
  1342. check_ok();
  1343. }
  1344. /*
  1345. * get the superuser password if required, and call postgres to set it
  1346. */
  1347. static void
  1348. get_set_pwd(void)
  1349. {
  1350. PG_CMD_DECL;
  1351. char *pwd1,
  1352. *pwd2;
  1353. if (pwprompt)
  1354. {
  1355. /*
  1356. * Read password from terminal
  1357. */
  1358. pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
  1359. pwd2 = simple_prompt("Enter it again: ", 100, false);
  1360. if (strcmp(pwd1, pwd2) != 0)
  1361. {
  1362. fprintf(stderr, _("Passwords didn't match.\n"));
  1363. exit_nicely();
  1364. }
  1365. free(pwd2);
  1366. }
  1367. else
  1368. {
  1369. /*
  1370. * Read password from file
  1371. *
  1372. * Ideally this should insist that the file not be world-readable.
  1373. * However, this option is mainly intended for use on Windows where
  1374. * file permissions may not exist at all, so we'll skip the paranoia
  1375. * for now.
  1376. */
  1377. FILE *pwf = fopen(pwfilename, "r");
  1378. char pwdbuf[MAXPGPATH];
  1379. int i;
  1380. if (!pwf)
  1381. {
  1382. fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
  1383. progname, pwfilename, strerror(errno));
  1384. exit_nicely();
  1385. }
  1386. if (!fgets(pwdbuf, sizeof(pwdbuf), pwf))
  1387. {
  1388. fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
  1389. progname, pwfilename, strerror(errno));
  1390. exit_nicely();
  1391. }
  1392. fclose(pwf);
  1393. i = strlen(pwdbuf);
  1394. while (i > 0 && (pwdbuf[i - 1] == '\r' || pwdbuf[i - 1] == '\n'))
  1395. pwdbuf[--i] = '\0';
  1396. pwd1 = pg_strdup(pwdbuf);
  1397. }
  1398. printf(_("setting password ... "));
  1399. fflush(stdout);
  1400. snprintf(cmd, sizeof(cmd),
  1401. "\"%s\" %s template1 >%s",
  1402. backend_exec, backend_options,
  1403. DEVNULL);
  1404. PG_CMD_OPEN;
  1405. PG_CMD_PRINTF2("ALTER USER \"%s\" WITH PASSWORD E'%s';\n",
  1406. username, escape_quotes(pwd1));
  1407. /* MM: pwd1 is no longer needed, freeing it */
  1408. free(pwd1);
  1409. PG_CMD_CLOSE;
  1410. check_ok();
  1411. }
  1412. /*
  1413. * set up pg_depend
  1414. */
  1415. static void
  1416. setup_depend(void)
  1417. {
  1418. PG_CMD_DECL;
  1419. const char **line;
  1420. static const char *pg_depend_setup[] = {
  1421. /*
  1422. * Make PIN entries in pg_depend for all objects made so far in the
  1423. * tables that the dependency code handles. This is overkill (the
  1424. * system doesn't really depend on having every last weird datatype,
  1425. * for instance) but generating only the minimum required set of
  1426. * dependencies seems hard.
  1427. *
  1428. * Note that we deliberately do not pin the system views, which
  1429. * haven't been created yet. Also, no conversions, databases, or
  1430. * tablespaces are pinned.
  1431. *
  1432. * First delete any already-made entries; PINs override all else, and
  1433. * must be the only entries for their objects.
  1434. */
  1435. "DELETE FROM pg_depend;\n",
  1436. "VACUUM pg_depend;\n",
  1437. "DELETE FROM pg_shdepend;\n",
  1438. "VACUUM pg_shdepend;\n",
  1439. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1440. " FROM pg_class;\n",
  1441. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1442. " FROM pg_proc;\n",
  1443. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1444. " FROM pg_type;\n",
  1445. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1446. " FROM pg_cast;\n",
  1447. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1448. " FROM pg_constraint;\n",
  1449. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1450. " FROM pg_attrdef;\n",
  1451. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1452. " FROM pg_language;\n",
  1453. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1454. " FROM pg_operator;\n",
  1455. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1456. " FROM pg_opclass;\n",
  1457. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1458. " FROM pg_opfamily;\n",
  1459. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1460. " FROM pg_amop;\n",
  1461. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1462. " FROM pg_amproc;\n",
  1463. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1464. " FROM pg_rewrite;\n",
  1465. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1466. " FROM pg_trigger;\n",
  1467. /*
  1468. * restriction here to avoid pinning the public namespace
  1469. */
  1470. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1471. " FROM pg_namespace "
  1472. " WHERE nspname LIKE 'pg%';\n",
  1473. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1474. " FROM pg_ts_parser;\n",
  1475. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1476. " FROM pg_ts_dict;\n",
  1477. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1478. " FROM pg_ts_template;\n",
  1479. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1480. " FROM pg_ts_config;\n",
  1481. "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
  1482. " FROM pg_collation;\n",
  1483. "INSERT INTO pg_shdepend SELECT 0,0,0,0, tableoid,oid, 'p' "
  1484. " FROM pg_authid;\n",
  1485. NULL
  1486. };
  1487. fputs(_("initializing dependencies ... "), stdout);
  1488. fflush(stdout);
  1489. snprintf(cmd, sizeof(cmd),
  1490. "\"%s\" %s template1 >%s",
  1491. backend_exec, backend_options,
  1492. DEVNULL);
  1493. PG_CMD_OPEN;
  1494. for (line = pg_depend_setup; *line != NULL; line++)
  1495. PG_CMD_PUTS(*line);
  1496. PG_CMD_CLOSE;
  1497. check_ok();
  1498. }
  1499. /*
  1500. * set up system views
  1501. */
  1502. static void
  1503. setup_sysviews(void)
  1504. {
  1505. PG_CMD_DECL;
  1506. char **line;
  1507. char **sysviews_setup;
  1508. fputs(_("creating system views ... "), stdout);
  1509. fflush(stdout);
  1510. sysviews_setup = readfile(system_views_file);
  1511. /*
  1512. * We use -j here to avoid backslashing stuff in system_views.sql
  1513. */
  1514. snprintf(cmd, sizeof(cmd),
  1515. "\"%s\" %s -j template1 >%s",
  1516. backend_exec, backend_options,
  1517. DEVNULL);
  1518. PG_CMD_OPEN;
  1519. for (line = sysviews_setup; *line != NULL; line++)
  1520. {
  1521. PG_CMD_PUTS(*line);
  1522. free(*line);
  1523. }
  1524. PG_CMD_CLOSE;
  1525. free(sysviews_setup);
  1526. check_ok();
  1527. }
  1528. /*
  1529. * load description data
  1530. */
  1531. static void
  1532. setup_description(void)
  1533. {
  1534. PG_CMD_DECL;
  1535. fputs(_("loading system objects' descriptions ... "), stdout);
  1536. fflush(stdout);
  1537. snprintf(cmd, sizeof(cmd),
  1538. "\"%s\" %s template1 >%s",
  1539. backend_exec, backend_options,
  1540. DEVNULL);
  1541. PG_CMD_OPEN;
  1542. PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_description ( "
  1543. " objoid oid, "
  1544. " classname name, "
  1545. " objsubid int4, "
  1546. " description text) WITHOUT OIDS;\n");
  1547. PG_CMD_PRINTF1("COPY tmp_pg_description FROM E'%s';\n",
  1548. escape_quotes(desc_file));
  1549. PG_CMD_PUTS("INSERT INTO pg_description "
  1550. " SELECT t.objoid, c.oid, t.objsubid, t.description "
  1551. " FROM tmp_pg_description t, pg_class c "
  1552. " WHERE c.relname = t.classname;\n");
  1553. PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_shdescription ( "
  1554. " objoid oid, "
  1555. " classname name, "
  1556. " description text) WITHOUT OIDS;\n");
  1557. PG_CMD_PRINTF1("COPY tmp_pg_shdescription FROM E'%s';\n",
  1558. escape_quotes(shdesc_file));
  1559. PG_CMD_PUTS("INSERT INTO pg_shdescription "
  1560. " SELECT t.objoid, c.oid, t.description "
  1561. " FROM tmp_pg_shdescription t, pg_class c "
  1562. " WHERE c.relname = t.classname;\n");
  1563. /* Create default descriptions for operator implementation functions */
  1564. PG_CMD_PUTS("WITH funcdescs AS ( "
  1565. "SELECT p.oid as p_oid, oprname, "
  1566. "coalesce(obj_description(o.oid, 'pg_operator'),'') as opdesc "
  1567. "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
  1568. "INSERT INTO pg_description "
  1569. " SELECT p_oid, 'pg_proc'::regclass, 0, "
  1570. " 'implementation of ' || oprname || ' operator' "
  1571. " FROM funcdescs "
  1572. " WHERE opdesc NOT LIKE 'deprecated%' AND "
  1573. " NOT EXISTS (SELECT 1 FROM pg_description "
  1574. " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass);\n");
  1575. PG_CMD_CLOSE;
  1576. check_ok();
  1577. }
  1578. #ifdef HAVE_LOCALE_T
  1579. /*
  1580. * "Normalize" a locale name, stripping off encoding tags such as
  1581. * ".utf8" (e.g., "en_US.utf8" -> "en_US", but "br_FR.iso885915@euro"
  1582. * -> "br_FR@euro"). Return true if a new, different name was
  1583. * generated.
  1584. */
  1585. static bool
  1586. normalize_locale_name(char *new, const char *old)
  1587. {
  1588. char *n = new;
  1589. const char *o = old;
  1590. bool changed = false;
  1591. while (*o)
  1592. {
  1593. if (*o == '.')
  1594. {
  1595. /* skip over encoding tag such as ".utf8" or ".UTF-8" */
  1596. o++;
  1597. while ((*o >= 'A' && *o <= 'Z')
  1598. || (*o >= 'a' && *o <= 'z')
  1599. || (*o >= '0' && *o <= '9')
  1600. || (*o == '-'))
  1601. o++;
  1602. changed = true;
  1603. }
  1604. else
  1605. *n++ = *o++;
  1606. }
  1607. *n = '\0';
  1608. return changed;
  1609. }
  1610. #endif /* HAVE_LOCALE_T */
  1611. /*
  1612. * populate pg_collation
  1613. */
  1614. static void
  1615. setup_collation(void)
  1616. {
  1617. #if defined(HAVE_LOCALE_T) && !defined(WIN32)
  1618. int i;
  1619. FILE *locale_a_handle;
  1620. char localebuf[NAMEDATALEN]; /* we assume ASCII so this is fine */
  1621. int count = 0;
  1622. PG_CMD_DECL;
  1623. #endif
  1624. fputs(_("creating collations ... "), stdout);
  1625. fflush(stdout);
  1626. #if defined(HAVE_LOCALE_T) && !defined(WIN32)
  1627. snprintf(cmd, sizeof(cmd),
  1628. "\"%s\" %s template1 >%s",
  1629. backend_exec, backend_options,
  1630. DEVNULL);
  1631. locale_a_handle = popen_check("locale -a", "r");
  1632. if (!locale_a_handle)
  1633. return; /* complaint already printed */
  1634. PG_CMD_OPEN;
  1635. PG_CMD_PUTS("CREATE TEMP TABLE tmp_pg_collation ( "
  1636. " collname name, "
  1637. " locale name, "
  1638. " encoding int) WITHOUT OIDS;\n");
  1639. while (fgets(localebuf, sizeof(localebuf), locale_a_handle))
  1640. {
  1641. size_t len;
  1642. int enc;
  1643. bool skip;
  1644. char *quoted_locale;
  1645. char alias[NAMEDATALEN];
  1646. len = strlen(localebuf);
  1647. if (len == 0 || localebuf[len - 1] != '\n')
  1648. {
  1649. if (debug)
  1650. fprintf(stderr, _("%s: locale name too long, skipped: \"%s\"\n"),
  1651. progname, localebuf);
  1652. continue;
  1653. }
  1654. localebuf[len - 1] = '\0';
  1655. /*
  1656. * Some systems have locale names that don't consist entirely of ASCII
  1657. * letters (such as "bokm&aring;l" or "fran&ccedil;ais"). This is
  1658. * pretty silly, since we need the locale itself to interpret the
  1659. * non-ASCII characters. We can't do much with those, so we filter
  1660. * them out.
  1661. */
  1662. skip = false;
  1663. for (i = 0; i < len; i++)
  1664. {
  1665. if (IS_HIGHBIT_SET(localebuf[i]))
  1666. {
  1667. skip = true;
  1668. break;
  1669. }
  1670. }
  1671. if (skip)
  1672. {
  1673. if (debug)
  1674. fprintf(stderr, _("%s: locale name has non-ASCII characters, skipped: \"%s\"\n"),
  1675. progname, localebuf);
  1676. continue;
  1677. }
  1678. enc = pg_get_encoding_from_locale(localebuf, debug);
  1679. if (enc < 0)
  1680. {
  1681. /* error message printed by pg_get_encoding_from_locale() */
  1682. continue;
  1683. }
  1684. if (!PG_VALID_BE_ENCODING(enc))
  1685. continue; /* ignore locales for client-only encodings */
  1686. if (enc == PG_SQL_ASCII)
  1687. continue; /* C/POSIX are already in the catalog */
  1688. count++;
  1689. quoted_locale = escape_quotes(localebuf);
  1690. PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n",
  1691. quoted_locale, quoted_locale, enc);
  1692. /*
  1693. * Generate aliases such as "en_US" in addition to "en_US.utf8" for
  1694. * ease of use. Note that collation names are unique per encoding
  1695. * only, so this doesn't clash with "en_US" for LATIN1, say.
  1696. */
  1697. if (normalize_locale_name(alias, localebuf))
  1698. {
  1699. char *quoted_alias = escape_quotes(alias);
  1700. PG_CMD_PRINTF3("INSERT INTO tmp_pg_collation VALUES (E'%s', E'%s', %d);\n",
  1701. quoted_alias, quoted_locale, enc);
  1702. free(quoted_alias);
  1703. }
  1704. free(quoted_locale);
  1705. }
  1706. /* Add an SQL-standard name */
  1707. PG_CMD_PRINTF1("INSERT INTO tm…

Large files files are truncated, but you can click here to view the full file