PageRenderTime 44ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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 tmp_pg_collation VALUES ('ucs_basic', 'C', %d);\n", PG_UTF8);
  1708. /*
  1709. * When copying collations to the final location, eliminate aliases that
  1710. * conflict with an existing locale name for the same encoding. For
  1711. * example, "br_FR.iso88591" is normalized to "br_FR", both for encoding
  1712. * LATIN1. But the unnormalized locale "br_FR" already exists for LATIN1.
  1713. * Prefer the alias that matches the OS locale name, else the first locale
  1714. * name by sort order (arbitrary choice to be deterministic).
  1715. *
  1716. * Also, eliminate any aliases that conflict with pg_collation's
  1717. * hard-wired entries for "C" etc.
  1718. */
  1719. PG_CMD_PUTS("INSERT INTO pg_collation (collname, collnamespace, collowner, collencoding, collcollate, collctype) "
  1720. " SELECT DISTINCT ON (collname, encoding)"
  1721. " collname, "
  1722. " (SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog') AS collnamespace, "
  1723. " (SELECT relowner FROM pg_class WHERE relname = 'pg_collation') AS collowner, "
  1724. " encoding, locale, locale "
  1725. " FROM tmp_pg_collation"
  1726. " WHERE NOT EXISTS (SELECT 1 FROM pg_collation WHERE collname = tmp_pg_collation.collname)"
  1727. " ORDER BY collname, encoding, (collname = locale) DESC, locale;\n");
  1728. pclose(locale_a_handle);
  1729. PG_CMD_CLOSE;
  1730. check_ok();
  1731. if (count == 0 && !debug)
  1732. {
  1733. printf(_("No usable system locales were found.\n"));
  1734. printf(_("Use the option \"--debug\" to see details.\n"));
  1735. }
  1736. #else /* not HAVE_LOCALE_T && not WIN32 */
  1737. printf(_("not supported on this platform\n"));
  1738. fflush(stdout);
  1739. #endif /* not HAVE_LOCALE_T && not WIN32 */
  1740. }
  1741. /*
  1742. * load conversion functions
  1743. */
  1744. static void
  1745. setup_conversion(void)
  1746. {
  1747. PG_CMD_DECL;
  1748. char **line;
  1749. char **conv_lines;
  1750. fputs(_("creating conversions ... "), stdout);
  1751. fflush(stdout);
  1752. snprintf(cmd, sizeof(cmd),
  1753. "\"%s\" %s template1 >%s",
  1754. backend_exec, backend_options,
  1755. DEVNULL);
  1756. PG_CMD_OPEN;
  1757. conv_lines = readfile(conversion_file);
  1758. for (line = conv_lines; *line != NULL; line++)
  1759. {
  1760. if (strstr(*line, "DROP CONVERSION") != *line)
  1761. PG_CMD_PUTS(*line);
  1762. free(*line);
  1763. }
  1764. free(conv_lines);
  1765. PG_CMD_CLOSE;
  1766. check_ok();
  1767. }
  1768. /*
  1769. * load extra dictionaries (Snowball stemmers)
  1770. */
  1771. static void
  1772. setup_dictionary(void)
  1773. {
  1774. PG_CMD_DECL;
  1775. char **line;
  1776. char **conv_lines;
  1777. fputs(_("creating dictionaries ... "), stdout);
  1778. fflush(stdout);
  1779. /*
  1780. * We use -j here to avoid backslashing stuff
  1781. */
  1782. snprintf(cmd, sizeof(cmd),
  1783. "\"%s\" %s -j template1 >%s",
  1784. backend_exec, backend_options,
  1785. DEVNULL);
  1786. PG_CMD_OPEN;
  1787. conv_lines = readfile(dictionary_file);
  1788. for (line = conv_lines; *line != NULL; line++)
  1789. {
  1790. PG_CMD_PUTS(*line);
  1791. free(*line);
  1792. }
  1793. free(conv_lines);
  1794. PG_CMD_CLOSE;
  1795. check_ok();
  1796. }
  1797. /*
  1798. * Set up privileges
  1799. *
  1800. * We mark most system catalogs as world-readable. We don't currently have
  1801. * to touch functions, languages, or databases, because their default
  1802. * permissions are OK.
  1803. *
  1804. * Some objects may require different permissions by default, so we
  1805. * make sure we don't overwrite privilege sets that have already been
  1806. * set (NOT NULL).
  1807. */
  1808. static void
  1809. setup_privileges(void)
  1810. {
  1811. PG_CMD_DECL;
  1812. char **line;
  1813. char **priv_lines;
  1814. static char *privileges_setup[] = {
  1815. "UPDATE pg_class "
  1816. " SET relacl = E'{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
  1817. " WHERE relkind IN ('r', 'v', 'm', 'S') AND relacl IS NULL;\n",
  1818. "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
  1819. "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
  1820. "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n",
  1821. NULL
  1822. };
  1823. fputs(_("setting privileges on built-in objects ... "), stdout);
  1824. fflush(stdout);
  1825. snprintf(cmd, sizeof(cmd),
  1826. "\"%s\" %s template1 >%s",
  1827. backend_exec, backend_options,
  1828. DEVNULL);
  1829. PG_CMD_OPEN;
  1830. priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
  1831. escape_quotes(username));
  1832. for (line = priv_lines; *line != NULL; line++)
  1833. PG_CMD_PUTS(*line);
  1834. PG_CMD_CLOSE;
  1835. check_ok();
  1836. }
  1837. /*
  1838. * extract the strange version of version required for information schema
  1839. * (09.08.0007abc)
  1840. */
  1841. static void
  1842. set_info_version(void)
  1843. {
  1844. char *letterversion;
  1845. long major = 0,
  1846. minor = 0,
  1847. micro = 0;
  1848. char *endptr;
  1849. char *vstr = pg_strdup(PG_VERSION);
  1850. char *ptr;
  1851. ptr = vstr + (strlen(vstr) - 1);
  1852. while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
  1853. ptr--;
  1854. letterversion = ptr + 1;
  1855. major = strtol(vstr, &endptr, 10);
  1856. if (*endptr)
  1857. minor = strtol(endptr + 1, &endptr, 10);
  1858. if (*endptr)
  1859. micro = strtol(endptr + 1, &endptr, 10);
  1860. snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
  1861. major, minor, micro, letterversion);
  1862. }
  1863. /*
  1864. * load info schema and populate from features file
  1865. */
  1866. static void
  1867. setup_schema(void)
  1868. {
  1869. PG_CMD_DECL;
  1870. char **line;
  1871. char **lines;
  1872. fputs(_("creating information schema ... "), stdout);
  1873. fflush(stdout);
  1874. lines = readfile(info_schema_file);
  1875. /*
  1876. * We use -j here to avoid backslashing stuff in information_schema.sql
  1877. */
  1878. snprintf(cmd, sizeof(cmd),
  1879. "\"%s\" %s -j template1 >%s",
  1880. backend_exec, backend_options,
  1881. DEVNULL);
  1882. PG_CMD_OPEN;
  1883. for (line = lines; *line != NULL; line++)
  1884. {
  1885. PG_CMD_PUTS(*line);
  1886. free(*line);
  1887. }
  1888. free(lines);
  1889. PG_CMD_CLOSE;
  1890. snprintf(cmd, sizeof(cmd),
  1891. "\"%s\" %s template1 >%s",
  1892. backend_exec, backend_options,
  1893. DEVNULL);
  1894. PG_CMD_OPEN;
  1895. PG_CMD_PRINTF1("UPDATE information_schema.sql_implementation_info "
  1896. " SET character_value = '%s' "
  1897. " WHERE implementation_info_name = 'DBMS VERSION';\n",
  1898. infoversion);
  1899. PG_CMD_PRINTF1("COPY information_schema.sql_features "
  1900. " (feature_id, feature_name, sub_feature_id, "
  1901. " sub_feature_name, is_supported, comments) "
  1902. " FROM E'%s';\n",
  1903. escape_quotes(features_file));
  1904. PG_CMD_CLOSE;
  1905. check_ok();
  1906. }
  1907. /*
  1908. * load PL/pgsql server-side language
  1909. */
  1910. static void
  1911. load_plpgsql(void)
  1912. {
  1913. PG_CMD_DECL;
  1914. fputs(_("loading PL/pgSQL server-side language ... "), stdout);
  1915. fflush(stdout);
  1916. snprintf(cmd, sizeof(cmd),
  1917. "\"%s\" %s template1 >%s",
  1918. backend_exec, backend_options,
  1919. DEVNULL);
  1920. PG_CMD_OPEN;
  1921. PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n");
  1922. PG_CMD_CLOSE;
  1923. check_ok();
  1924. }
  1925. /*
  1926. * clean everything up in template1
  1927. */
  1928. static void
  1929. vacuum_db(void)
  1930. {
  1931. PG_CMD_DECL;
  1932. fputs(_("vacuuming database template1 ... "), stdout);
  1933. fflush(stdout);
  1934. snprintf(cmd, sizeof(cmd),
  1935. "\"%s\" %s template1 >%s",
  1936. backend_exec, backend_options,
  1937. DEVNULL);
  1938. PG_CMD_OPEN;
  1939. PG_CMD_PUTS("ANALYZE;\nVACUUM FULL;\nVACUUM FREEZE;\n");
  1940. PG_CMD_CLOSE;
  1941. check_ok();
  1942. }
  1943. /*
  1944. * copy template1 to template0
  1945. */
  1946. static void
  1947. make_template0(void)
  1948. {
  1949. PG_CMD_DECL;
  1950. const char **line;
  1951. static const char *template0_setup[] = {
  1952. "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false;\n",
  1953. /*
  1954. * We use the OID of template0 to determine lastsysoid
  1955. */
  1956. "UPDATE pg_database SET datlastsysoid = "
  1957. " (SELECT oid FROM pg_database "
  1958. " WHERE datname = 'template0');\n",
  1959. /*
  1960. * Explicitly revoke public create-schema and create-temp-table
  1961. * privileges in template1 and template0; else the latter would be on
  1962. * by default
  1963. */
  1964. "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
  1965. "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",
  1966. "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n",
  1967. /*
  1968. * Finally vacuum to clean up dead rows in pg_database
  1969. */
  1970. "VACUUM FULL pg_database;\n",
  1971. NULL
  1972. };
  1973. fputs(_("copying template1 to template0 ... "), stdout);
  1974. fflush(stdout);
  1975. snprintf(cmd, sizeof(cmd),
  1976. "\"%s\" %s template1 >%s",
  1977. backend_exec, backend_options,
  1978. DEVNULL);
  1979. PG_CMD_OPEN;
  1980. for (line = template0_setup; *line; line++)
  1981. PG_CMD_PUTS(*line);
  1982. PG_CMD_CLOSE;
  1983. check_ok();
  1984. }
  1985. /*
  1986. * copy template1 to postgres
  1987. */
  1988. static void
  1989. make_postgres(void)
  1990. {
  1991. PG_CMD_DECL;
  1992. const char **line;
  1993. static const char *postgres_setup[] = {
  1994. "CREATE DATABASE postgres;\n",
  1995. "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n",
  1996. NULL
  1997. };
  1998. fputs(_("copying template1 to postgres ... "), stdout);
  1999. fflush(stdout);
  2000. snprintf(cmd, sizeof(cmd),
  2001. "\"%s\" %s template1 >%s",
  2002. backend_exec, backend_options,
  2003. DEVNULL);
  2004. PG_CMD_OPEN;
  2005. for (line = postgres_setup; *line; line++)
  2006. PG_CMD_PUTS(*line);
  2007. PG_CMD_CLOSE;
  2008. check_ok();
  2009. }
  2010. /*
  2011. * fsync everything down to disk
  2012. */
  2013. static void
  2014. perform_fsync(void)
  2015. {
  2016. char pdir[MAXPGPATH];
  2017. fputs(_("syncing data to disk ... "), stdout);
  2018. fflush(stdout);
  2019. /*
  2020. * We need to name the parent of PGDATA. get_parent_directory() isn't
  2021. * enough here, because it can result in an empty string.
  2022. */
  2023. snprintf(pdir, MAXPGPATH, "%s/..", pg_data);
  2024. canonicalize_path(pdir);
  2025. /*
  2026. * Hint to the OS so that we're going to fsync each of these files soon.
  2027. */
  2028. /* first the parent of the PGDATA directory */
  2029. pre_sync_fname(pdir, true);
  2030. /* then recursively through the directory */
  2031. walkdir(pg_data, pre_sync_fname);
  2032. /*
  2033. * Now, do the fsync()s in the same order.
  2034. */
  2035. /* first the parent of the PGDATA directory */
  2036. fsync_fname(pdir, true);
  2037. /* then recursively through the directory */
  2038. walkdir(pg_data, fsync_fname);
  2039. check_ok();
  2040. }
  2041. /*
  2042. * signal handler in case we are interrupted.
  2043. *
  2044. * The Windows runtime docs at
  2045. * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
  2046. * specifically forbid a number of things being done from a signal handler,
  2047. * including IO, memory allocation and system calls, and only allow jmpbuf
  2048. * if you are handling SIGFPE.
  2049. *
  2050. * I avoided doing the forbidden things by setting a flag instead of calling
  2051. * exit_nicely() directly.
  2052. *
  2053. * Also note the behaviour of Windows with SIGINT, which says this:
  2054. * Note SIGINT is not supported for any Win32 application, including
  2055. * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
  2056. * Win32 operating systems generate a new thread to specifically handle
  2057. * that interrupt. This can cause a single-thread application such as UNIX,
  2058. * to become multithreaded, resulting in unexpected behavior.
  2059. *
  2060. * I have no idea how to handle this. (Strange they call UNIX an application!)
  2061. * So this will need some testing on Windows.
  2062. */
  2063. static void
  2064. trapsig(int signum)
  2065. {
  2066. /* handle systems that reset the handler, like Windows (grr) */
  2067. pqsignal(signum, trapsig);
  2068. caught_signal = true;
  2069. }
  2070. /*
  2071. * call exit_nicely() if we got a signal, or else output "ok".
  2072. */
  2073. static void
  2074. check_ok(void)
  2075. {
  2076. if (caught_signal)
  2077. {
  2078. printf(_("caught signal\n"));
  2079. fflush(stdout);
  2080. exit_nicely();
  2081. }
  2082. else if (output_failed)
  2083. {
  2084. printf(_("could not write to child process: %s\n"),
  2085. strerror(output_errno));
  2086. fflush(stdout);
  2087. exit_nicely();
  2088. }
  2089. else
  2090. {
  2091. /* all seems well */
  2092. printf(_("ok\n"));
  2093. fflush(stdout);
  2094. }
  2095. }
  2096. /* Hack to suppress a warning about %x from some versions of gcc */
  2097. static inline size_t
  2098. my_strftime(char *s, size_t max, const char *fmt, const struct tm * tm)
  2099. {
  2100. return strftime(s, max, fmt, tm);
  2101. }
  2102. /*
  2103. * Determine likely date order from locale
  2104. */
  2105. static int
  2106. locale_date_order(const char *locale)
  2107. {
  2108. struct tm testtime;
  2109. char buf[128];
  2110. char *posD;
  2111. char *posM;
  2112. char *posY;
  2113. char *save;
  2114. size_t res;
  2115. int result;
  2116. result = DATEORDER_MDY; /* default */
  2117. save = setlocale(LC_TIME, NULL);
  2118. if (!save)
  2119. return result;
  2120. save = pg_strdup(save);
  2121. setlocale(LC_TIME, locale);
  2122. memset(&testtime, 0, sizeof(testtime));
  2123. testtime.tm_mday = 22;
  2124. testtime.tm_mon = 10; /* November, should come out as "11" */
  2125. testtime.tm_year = 133; /* 2033 */
  2126. res = my_strftime(buf, sizeof(buf), "%x", &testtime);
  2127. setlocale(LC_TIME, save);
  2128. free(save);
  2129. if (res == 0)
  2130. return result;
  2131. posM = strstr(buf, "11");
  2132. posD = strstr(buf, "22");
  2133. posY = strstr(buf, "33");
  2134. if (!posM || !posD || !posY)
  2135. return result;
  2136. if (posY < posM && posM < posD)
  2137. result = DATEORDER_YMD;
  2138. else if (posD < posM)
  2139. result = DATEORDER_DMY;
  2140. else
  2141. result = DATEORDER_MDY;
  2142. return result;
  2143. }
  2144. /*
  2145. * Verify that locale name is valid for the locale category.
  2146. *
  2147. * If successful, and canonname isn't NULL, a malloc'd copy of the locale's
  2148. * canonical name is stored there. This is especially useful for figuring out
  2149. * what locale name "" means (ie, the environment value). (Actually,
  2150. * it seems that on most implementations that's the only thing it's good for;
  2151. * we could wish that setlocale gave back a canonically spelled version of
  2152. * the locale name, but typically it doesn't.)
  2153. *
  2154. * this should match the backend's check_locale() function
  2155. */
  2156. static void
  2157. check_locale_name(int category, const char *locale, char **canonname)
  2158. {
  2159. char *save;
  2160. char *res;
  2161. if (canonname)
  2162. *canonname = NULL; /* in case of failure */
  2163. save = setlocale(category, NULL);
  2164. if (!save)
  2165. {
  2166. fprintf(stderr, _("%s: setlocale() failed\n"),
  2167. progname);
  2168. exit(1);
  2169. }
  2170. /* save may be pointing at a modifiable scratch variable, so copy it. */
  2171. save = pg_strdup(save);
  2172. /* set the locale with setlocale, to see if it accepts it. */
  2173. res = setlocale(category, locale);
  2174. /* save canonical name if requested. */
  2175. if (res && canonname)
  2176. *canonname = pg_strdup(res);
  2177. /* restore old value. */
  2178. if (!setlocale(category, save))
  2179. {
  2180. fprintf(stderr, _("%s: failed to restore old locale \"%s\"\n"),
  2181. progname, save);
  2182. exit(1);
  2183. }
  2184. free(save);
  2185. /* complain if locale wasn't valid */
  2186. if (res == NULL)
  2187. {
  2188. if (*locale)
  2189. fprintf(stderr, _("%s: invalid locale name \"%s\"\n"),
  2190. progname, locale);
  2191. else
  2192. {
  2193. /*
  2194. * If no relevant switch was given on command line, locale is an
  2195. * empty string, which is not too helpful to report. Presumably
  2196. * setlocale() found something it did not like in the environment.
  2197. * Ideally we'd report the bad environment variable, but since
  2198. * setlocale's behavior is implementation-specific, it's hard to
  2199. * be sure what it didn't like. Print a safe generic message.
  2200. */
  2201. fprintf(stderr, _("%s: invalid locale settings; check LANG and LC_* environment variables\n"),
  2202. progname);
  2203. }
  2204. exit(1);
  2205. }
  2206. }
  2207. /*
  2208. * check if the chosen encoding matches the encoding required by the locale
  2209. *
  2210. * this should match the similar check in the backend createdb() function
  2211. */
  2212. static bool
  2213. check_locale_encoding(const char *locale, int user_enc)
  2214. {
  2215. int locale_enc;
  2216. locale_enc = pg_get_encoding_from_locale(locale, true);
  2217. /* See notes in createdb() to understand these tests */
  2218. if (!(locale_enc == user_enc ||
  2219. locale_enc == PG_SQL_ASCII ||
  2220. locale_enc == -1 ||
  2221. #ifdef WIN32
  2222. user_enc == PG_UTF8 ||
  2223. #endif
  2224. user_enc == PG_SQL_ASCII))
  2225. {
  2226. fprintf(stderr, _("%s: encoding mismatch\n"), progname);
  2227. fprintf(stderr,
  2228. _("The encoding you selected (%s) and the encoding that the\n"
  2229. "selected locale uses (%s) do not match. This would lead to\n"
  2230. "misbehavior in various character string processing functions.\n"
  2231. "Rerun %s and either do not specify an encoding explicitly,\n"
  2232. "or choose a matching combination.\n"),
  2233. pg_encoding_to_char(user_enc),
  2234. pg_encoding_to_char(locale_enc),
  2235. progname);
  2236. return false;
  2237. }
  2238. return true;
  2239. }
  2240. /*
  2241. * set up the locale variables
  2242. *
  2243. * assumes we have called setlocale(LC_ALL, "") -- see set_pglocale_pgservice
  2244. */
  2245. static void
  2246. setlocales(void)
  2247. {
  2248. char *canonname;
  2249. /* set empty lc_* values to locale config if set */
  2250. if (strlen(locale) > 0)
  2251. {
  2252. if (strlen(lc_ctype) == 0)
  2253. lc_ctype = locale;
  2254. if (strlen(lc_collate) == 0)
  2255. lc_collate = locale;
  2256. if (strlen(lc_numeric) == 0)
  2257. lc_numeric = locale;
  2258. if (strlen(lc_time) == 0)
  2259. lc_time = locale;
  2260. if (strlen(lc_monetary) == 0)
  2261. lc_monetary = locale;
  2262. if (strlen(lc_messages) == 0)
  2263. lc_messages = locale;
  2264. }
  2265. /*
  2266. * canonicalize locale names, and obtain any missing values from our
  2267. * current environment
  2268. */
  2269. check_locale_name(LC_CTYPE, lc_ctype, &canonname);
  2270. lc_ctype = canonname;
  2271. check_locale_name(LC_COLLATE, lc_collate, &canonname);
  2272. lc_collate = canonname;
  2273. check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
  2274. lc_numeric = canonname;
  2275. check_locale_name(LC_TIME, lc_time, &canonname);
  2276. lc_time = canonname;
  2277. check_locale_name(LC_MONETARY, lc_monetary, &canonname);
  2278. lc_monetary = canonname;
  2279. #if defined(LC_MESSAGES) && !defined(WIN32)
  2280. check_locale_name(LC_MESSAGES, lc_messages, &canonname);
  2281. lc_messages = canonname;
  2282. #else
  2283. /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
  2284. check_locale_name(LC_CTYPE, lc_messages, &canonname);
  2285. lc_messages = canonname;
  2286. #endif
  2287. }
  2288. #ifdef WIN32
  2289. typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
  2290. /* Windows API define missing from some versions of MingW headers */
  2291. #ifndef DISABLE_MAX_PRIVILEGE
  2292. #define DISABLE_MAX_PRIVILEGE 0x1
  2293. #endif
  2294. /*
  2295. * Create a restricted token and execute the specified process with it.
  2296. *
  2297. * Returns 0 on failure, non-zero on success, same as CreateProcess().
  2298. *
  2299. * On NT4, or any other system not containing the required functions, will
  2300. * NOT execute anything.
  2301. */
  2302. static int
  2303. CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo)
  2304. {
  2305. BOOL b;
  2306. STARTUPINFO si;
  2307. HANDLE origToken;
  2308. HANDLE restrictedToken;
  2309. SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
  2310. SID_AND_ATTRIBUTES dropSids[2];
  2311. __CreateRestrictedToken _CreateRestrictedToken = NULL;
  2312. HANDLE Advapi32Handle;
  2313. ZeroMemory(&si, sizeof(si));
  2314. si.cb = sizeof(si);
  2315. Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
  2316. if (Advapi32Handle != NULL)
  2317. {
  2318. _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
  2319. }
  2320. if (_CreateRestrictedToken == NULL)
  2321. {
  2322. fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
  2323. if (Advapi32Handle != NULL)
  2324. FreeLibrary(Advapi32Handle);
  2325. return 0;
  2326. }
  2327. /* Open the current token to use as a base for the restricted one */
  2328. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
  2329. {
  2330. fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError());
  2331. return 0;
  2332. }
  2333. /* Allocate list of SIDs to remove */
  2334. ZeroMemory(&dropSids, sizeof(dropSids));
  2335. if (!AllocateAndInitializeSid(&NtAuthority, 2,
  2336. SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
  2337. 0, &dropSids[0].Sid) ||
  2338. !AllocateAndInitializeSid(&NtAuthority, 2,
  2339. SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
  2340. 0, &dropSids[1].Sid))
  2341. {
  2342. fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError());
  2343. return 0;
  2344. }
  2345. b = _CreateRestrictedToken(origToken,
  2346. DISABLE_MAX_PRIVILEGE,
  2347. sizeof(dropSids) / sizeof(dropSids[0]),
  2348. dropSids,
  2349. 0, NULL,
  2350. 0, NULL,
  2351. &restrictedToken);
  2352. FreeSid(dropSids[1].Sid);
  2353. FreeSid(dropSids[0].Sid);
  2354. CloseHandle(origToken);
  2355. FreeLibrary(Advapi32Handle);
  2356. if (!b)
  2357. {
  2358. fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError());
  2359. return 0;
  2360. }
  2361. #ifndef __CYGWIN__
  2362. AddUserToTokenDacl(restrictedToken);
  2363. #endif
  2364. if (!CreateProcessAsUser(restrictedToken,
  2365. NULL,
  2366. cmd,
  2367. NULL,
  2368. NULL,
  2369. TRUE,
  2370. CREATE_SUSPENDED,
  2371. NULL,
  2372. NULL,
  2373. &si,
  2374. processInfo))
  2375. {
  2376. fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError());
  2377. return 0;
  2378. }
  2379. return ResumeThread(processInfo->hThread);
  2380. }
  2381. #endif
  2382. /*
  2383. * print help text
  2384. */
  2385. static void
  2386. usage(const char *progname)
  2387. {
  2388. printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
  2389. printf(_("Usage:\n"));
  2390. printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
  2391. printf(_("\nOptions:\n"));
  2392. printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
  2393. printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
  2394. printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
  2395. printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
  2396. printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
  2397. printf(_(" --locale=LOCALE set default locale for new databases\n"));
  2398. printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
  2399. " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
  2400. " set default locale in the respective category for\n"
  2401. " new databases (default taken from environment)\n"));
  2402. printf(_(" --no-locale equivalent to --locale=C\n"));
  2403. printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
  2404. printf(_(" -T, --text-search-config=CFG\n"
  2405. " default text search configuration\n"));
  2406. printf(_(" -U, --username=NAME database superuser name\n"));
  2407. printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
  2408. printf(_(" -X, --xlogdir=XLOGDIR location for the transaction log directory\n"));
  2409. printf(_("\nLess commonly used options:\n"));
  2410. printf(_(" -d, --debug generate lots of debugging output\n"));
  2411. printf(_(" -k, --data-checksums use data page checksums\n"));
  2412. printf(_(" -L DIRECTORY where to find the input files\n"));
  2413. printf(_(" -n, --noclean do not clean up after errors\n"));
  2414. printf(_(" -N, --nosync do not wait for changes to be written safely to disk\n"));
  2415. printf(_(" -s, --show show internal settings\n"));
  2416. printf(_(" -S, --sync-only only sync data directory\n"));
  2417. printf(_("\nOther options:\n"));
  2418. printf(_(" -V, --version output version information, then exit\n"));
  2419. printf(_(" -?, --help show this help, then exit\n"));
  2420. printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
  2421. "is used.\n"));
  2422. printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
  2423. }
  2424. static void
  2425. check_authmethod_unspecified(const char **authmethod)
  2426. {
  2427. if (*authmethod == NULL || strlen(*authmethod) == 0)
  2428. {
  2429. authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
  2430. "You can change this by editing pg_hba.conf or using the option -A, or\n"
  2431. "--auth-local and --auth-host, the next time you run initdb.\n");
  2432. *authmethod = "trust";
  2433. }
  2434. }
  2435. static void
  2436. check_authmethod_valid(const char *authmethod, const char **valid_methods, const char *conntype)
  2437. {
  2438. const char **p;
  2439. for (p = valid_methods; *p; p++)
  2440. {
  2441. if (strcmp(authmethod, *p) == 0)
  2442. return;
  2443. /* with space = param */
  2444. if (strchr(authmethod, ' '))
  2445. if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
  2446. return;
  2447. }
  2448. fprintf(stderr, _("%s: invalid authentication method \"%s\" for \"%s\" connections\n"),
  2449. progname, authmethod, conntype);
  2450. exit(1);
  2451. }
  2452. static void
  2453. check_need_password(const char *authmethodlocal, const char *authmethodhost)
  2454. {
  2455. if ((strcmp(authmethodlocal, "md5") == 0 ||
  2456. strcmp(authmethodlocal, "password") == 0) &&
  2457. (strcmp(authmethodhost, "md5") == 0 ||
  2458. strcmp(authmethodhost, "password") == 0) &&
  2459. !(pwprompt || pwfilename))
  2460. {
  2461. fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname,
  2462. (strcmp(authmethodlocal, "md5") == 0 ||
  2463. strcmp(authmethodlocal, "password") == 0)
  2464. ? authmethodlocal
  2465. : authmethodhost);
  2466. exit(1);
  2467. }
  2468. }
  2469. void
  2470. get_restricted_token(void)
  2471. {
  2472. #ifdef WIN32
  2473. /*
  2474. * Before we execute another program, make sure that we are running with a
  2475. * restricted token. If not, re-execute ourselves with one.
  2476. */
  2477. if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL
  2478. || strcmp(restrict_env, "1") != 0)
  2479. {
  2480. PROCESS_INFORMATION pi;
  2481. char *cmdline;
  2482. ZeroMemory(&pi, sizeof(pi));
  2483. cmdline = pg_strdup(GetCommandLine());
  2484. putenv("PG_RESTRICT_EXEC=1");
  2485. if (!CreateRestrictedProcess(cmdline, &pi))
  2486. {
  2487. fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError());
  2488. }
  2489. else
  2490. {
  2491. /*
  2492. * Successfully re-execed. Now wait for child process to capture
  2493. * exitcode.
  2494. */
  2495. DWORD x;
  2496. CloseHandle(pi.hThread);
  2497. WaitForSingleObject(pi.hProcess, INFINITE);
  2498. if (!GetExitCodeProcess(pi.hProcess, &x))
  2499. {
  2500. fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError());
  2501. exit(1);
  2502. }
  2503. exit(x);
  2504. }
  2505. }
  2506. #endif
  2507. }
  2508. void
  2509. setup_pgdata(void)
  2510. {
  2511. char *pgdata_get_env,
  2512. *pgdata_set_env;
  2513. if (strlen(pg_data) == 0)
  2514. {
  2515. pgdata_get_env = getenv("PGDATA");
  2516. if (pgdata_get_env && strlen(pgdata_get_env))
  2517. {
  2518. /* PGDATA found */
  2519. pg_data = pg_strdup(pgdata_get_env);
  2520. }
  2521. else
  2522. {
  2523. fprintf(stderr,
  2524. _("%s: no data directory specified\n"
  2525. "You must identify the directory where the data for this database system\n"
  2526. "will reside. Do this with either the invocation option -D or the\n"
  2527. "environment variable PGDATA.\n"),
  2528. progname);
  2529. exit(1);
  2530. }
  2531. }
  2532. pgdata_native = pg_strdup(pg_data);
  2533. canonicalize_path(pg_data);
  2534. /*
  2535. * we have to set PGDATA for postgres rather than pass it on the command
  2536. * line to avoid dumb quoting problems on Windows, and we would especially
  2537. * need quotes otherwise on Windows because paths there are most likely to
  2538. * have embedded spaces.
  2539. */
  2540. pgdata_set_env = psprintf("PGDATA=%s", pg_data);
  2541. putenv(pgdata_set_env);
  2542. }
  2543. void
  2544. setup_bin_paths(const char *argv0)
  2545. {
  2546. int ret;
  2547. if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
  2548. backend_exec)) < 0)
  2549. {
  2550. char full_path[MAXPGPATH];
  2551. if (find_my_exec(argv0, full_path) < 0)
  2552. strlcpy(full_path, progname, sizeof(full_path));
  2553. if (ret == -1)
  2554. fprintf(stderr,
  2555. _("The program \"postgres\" is needed by %s "
  2556. "but was not found in the\n"
  2557. "same directory as \"%s\".\n"
  2558. "Check your installation.\n"),
  2559. progname, full_path);
  2560. else
  2561. fprintf(stderr,
  2562. _("The program \"postgres\" was found by \"%s\"\n"
  2563. "but was not the same version as %s.\n"
  2564. "Check your installation.\n"),
  2565. full_path, progname);
  2566. exit(1);
  2567. }
  2568. /* store binary directory */
  2569. strcpy(bin_path, backend_exec);
  2570. *last_dir_separator(bin_path) = '\0';
  2571. canonicalize_path(bin_path);
  2572. if (!share_path)
  2573. {
  2574. share_path = pg_malloc(MAXPGPATH);
  2575. get_share_path(backend_exec, share_path);
  2576. }
  2577. else if (!is_absolute_path(share_path))
  2578. {
  2579. fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
  2580. exit(1);
  2581. }
  2582. canonicalize_path(share_path);
  2583. }
  2584. void
  2585. setup_locale_encoding(void)
  2586. {
  2587. int user_enc;
  2588. setlocales();
  2589. if (strcmp(lc_ctype, lc_collate) == 0 &&
  2590. strcmp(lc_ctype, lc_time) == 0 &&
  2591. strcmp(lc_ctype, lc_numeric) == 0 &&
  2592. strcmp(lc_ctype, lc_monetary) == 0 &&
  2593. strcmp(lc_ctype, lc_messages) == 0)
  2594. printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
  2595. else
  2596. {
  2597. printf(_("The database cluster will be initialized with locales\n"
  2598. " COLLATE: %s\n"
  2599. " CTYPE: %s\n"
  2600. " MESSAGES: %s\n"
  2601. " MONETARY: %s\n"
  2602. " NUMERIC: %s\n"
  2603. " TIME: %s\n"),
  2604. lc_collate,
  2605. lc_ctype,
  2606. lc_messages,
  2607. lc_monetary,
  2608. lc_numeric,
  2609. lc_time);
  2610. }
  2611. if (strlen(encoding) == 0)
  2612. {
  2613. int ctype_enc;
  2614. ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
  2615. if (ctype_enc == -1)
  2616. {
  2617. /* Couldn't recognize the locale's codeset */
  2618. fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"),
  2619. progname, lc_ctype);
  2620. fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
  2621. fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
  2622. progname);
  2623. exit(1);
  2624. }
  2625. else if (!pg_valid_server_encoding_id(ctype_enc))
  2626. {
  2627. /*
  2628. * We recognized it, but it's not a legal server encoding. On
  2629. * Windows, UTF-8 works with any locale, so we can fall back to
  2630. * UTF-8.
  2631. */
  2632. #ifdef WIN32
  2633. printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
  2634. "The default database encoding will be set to \"%s\" instead.\n"),
  2635. pg_encoding_to_char(ctype_enc),
  2636. pg_encoding_to_char(PG_UTF8));
  2637. ctype_enc = PG_UTF8;
  2638. encodingid = encodingid_to_string(ctype_enc);
  2639. #else
  2640. fprintf(stderr,
  2641. _("%s: locale \"%s\" requires unsupported encoding \"%s\"\n"),
  2642. progname, lc_ctype, pg_encoding_to_char(ctype_enc));
  2643. fprintf(stderr,
  2644. _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
  2645. "Rerun %s with a different locale selection.\n"),
  2646. pg_encoding_to_char(ctype_enc), progname);
  2647. exit(1);
  2648. #endif
  2649. }
  2650. else
  2651. {
  2652. encodingid = encodingid_to_string(ctype_enc);
  2653. printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
  2654. pg_encoding_to_char(ctype_enc));
  2655. }
  2656. }
  2657. else
  2658. encodingid = get_encoding_id(encoding);
  2659. user_enc = atoi(encodingid);
  2660. if (!check_locale_encoding(lc_ctype, user_enc) ||
  2661. !check_locale_encoding(lc_collate, user_enc))
  2662. exit(1); /* check_locale_encoding printed the error */
  2663. }
  2664. void
  2665. setup_data_file_paths(void)
  2666. {
  2667. set_input(&bki_file, "postgres.bki");
  2668. set_input(&desc_file, "postgres.description");
  2669. set_input(&shdesc_file, "postgres.shdescription");
  2670. set_input(&hba_file, "pg_hba.conf.sample");
  2671. set_input(&ident_file, "pg_ident.conf.sample");
  2672. set_input(&conf_file, "postgresql.conf.sample");
  2673. set_input(&conversion_file, "conversion_create.sql");
  2674. set_input(&dictionary_file, "snowball_create.sql");
  2675. set_input(&info_schema_file, "information_schema.sql");
  2676. set_input(&features_file, "sql_features.txt");
  2677. set_input(&system_views_file, "system_views.sql");
  2678. if (show_setting || debug)
  2679. {
  2680. fprintf(stderr,
  2681. "VERSION=%s\n"
  2682. "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
  2683. "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
  2684. "POSTGRES_DESCR=%s\nPOSTGRES_SHDESCR=%s\n"
  2685. "POSTGRESQL_CONF_SAMPLE=%s\n"
  2686. "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
  2687. PG_VERSION,
  2688. pg_data, share_path, bin_path,
  2689. username, bki_file,
  2690. desc_file, shdesc_file,
  2691. conf_file,
  2692. hba_file, ident_file);
  2693. if (show_setting)
  2694. exit(0);
  2695. }
  2696. check_input(bki_file);
  2697. check_input(desc_file);
  2698. check_input(shdesc_file);
  2699. check_input(hba_file);
  2700. check_input(ident_file);
  2701. check_input(conf_file);
  2702. check_input(conversion_file);
  2703. check_input(dictionary_file);
  2704. check_input(info_schema_file);
  2705. check_input(features_file);
  2706. check_input(system_views_file);
  2707. }
  2708. void
  2709. setup_text_search(void)
  2710. {
  2711. if (strlen(default_text_search_config) == 0)
  2712. {
  2713. default_text_search_config = find_matching_ts_config(lc_ctype);
  2714. if (default_text_search_config == NULL)
  2715. {
  2716. printf(_("%s: could not find suitable text search configuration for locale \"%s\"\n"),
  2717. progname, lc_ctype);
  2718. default_text_search_config = "simple";
  2719. }
  2720. }
  2721. else
  2722. {
  2723. const char *checkmatch = find_matching_ts_config(lc_ctype);
  2724. if (checkmatch == NULL)
  2725. {
  2726. printf(_("%s: warning: suitable text search configuration for locale \"%s\" is unknown\n"),
  2727. progname, lc_ctype);
  2728. }
  2729. else if (strcmp(checkmatch, default_text_search_config) != 0)
  2730. {
  2731. printf(_("%s: warning: specified text search configuration \"%s\" might not match locale \"%s\"\n"),
  2732. progname, default_text_search_config, lc_ctype);
  2733. }
  2734. }
  2735. printf(_("The default text search configuration will be set to \"%s\".\n"),
  2736. default_text_search_config);
  2737. }
  2738. void
  2739. setup_signals(void)
  2740. {
  2741. /* some of these are not valid on Windows */
  2742. #ifdef SIGHUP
  2743. pqsignal(SIGHUP, trapsig);
  2744. #endif
  2745. #ifdef SIGINT
  2746. pqsignal(SIGINT, trapsig);
  2747. #endif
  2748. #ifdef SIGQUIT
  2749. pqsignal(SIGQUIT, trapsig);
  2750. #endif
  2751. #ifdef SIGTERM
  2752. pqsignal(SIGTERM, trapsig);
  2753. #endif
  2754. /* Ignore SIGPIPE when writing to backend, so we can clean up */
  2755. #ifdef SIGPIPE
  2756. pqsignal(SIGPIPE, SIG_IGN);
  2757. #endif
  2758. /* Prevent SIGSYS so we can probe for kernel calls that might not work */
  2759. #ifdef SIGSYS
  2760. pqsignal(SIGSYS, SIG_IGN);
  2761. #endif
  2762. }
  2763. void
  2764. create_data_directory(void)
  2765. {
  2766. int ret;
  2767. switch ((ret = pg_check_dir(pg_data)))
  2768. {
  2769. case 0:
  2770. /* PGDATA not there, must create it */
  2771. printf(_("creating directory %s ... "),
  2772. pg_data);
  2773. fflush(stdout);
  2774. if (!mkdatadir(NULL))
  2775. exit_nicely();
  2776. else
  2777. check_ok();
  2778. made_new_pgdata = true;
  2779. break;
  2780. case 1:
  2781. /* Present but empty, fix permissions and use it */
  2782. printf(_("fixing permissions on existing directory %s ... "),
  2783. pg_data);
  2784. fflush(stdout);
  2785. if (chmod(pg_data, S_IRWXU) != 0)
  2786. {
  2787. fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
  2788. progname, pg_data, strerror(errno));
  2789. exit_nicely();
  2790. }
  2791. else
  2792. check_ok();
  2793. found_existing_pgdata = true;
  2794. break;
  2795. case 2:
  2796. case 3:
  2797. case 4:
  2798. /* Present and not empty */
  2799. fprintf(stderr,
  2800. _("%s: directory \"%s\" exists but is not empty\n"),
  2801. progname, pg_data);
  2802. if (ret != 4)
  2803. warn_on_mount_point(ret);
  2804. else
  2805. fprintf(stderr,
  2806. _("If you want to create a new database system, either remove or empty\n"
  2807. "the directory \"%s\" or run %s\n"
  2808. "with an argument other than \"%s\".\n"),
  2809. pg_data, progname, pg_data);
  2810. exit(1); /* no further message needed */
  2811. default:
  2812. /* Trouble accessing directory */
  2813. fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
  2814. progname, pg_data, strerror(errno));
  2815. exit_nicely();
  2816. }
  2817. }
  2818. void
  2819. create_xlog_symlink(void)
  2820. {
  2821. /* Create transaction log symlink, if required */
  2822. if (strcmp(xlog_dir, "") != 0)
  2823. {
  2824. char *linkloc;
  2825. int ret;
  2826. /* clean up xlog directory name, check it's absolute */
  2827. canonicalize_path(xlog_dir);
  2828. if (!is_absolute_path(xlog_dir))
  2829. {
  2830. fprintf(stderr, _("%s: transaction log directory location must be an absolute path\n"), progname);
  2831. exit_nicely();
  2832. }
  2833. /* check if the specified xlog directory exists/is empty */
  2834. switch ((ret = pg_check_dir(xlog_dir)))
  2835. {
  2836. case 0:
  2837. /* xlog directory not there, must create it */
  2838. printf(_("creating directory %s ... "),
  2839. xlog_dir);
  2840. fflush(stdout);
  2841. if (pg_mkdir_p(xlog_dir, S_IRWXU) != 0)
  2842. {
  2843. fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
  2844. progname, xlog_dir, strerror(errno));
  2845. exit_nicely();
  2846. }
  2847. else
  2848. check_ok();
  2849. made_new_xlogdir = true;
  2850. break;
  2851. case 1:
  2852. /* Present but empty, fix permissions and use it */
  2853. printf(_("fixing permissions on existing directory %s ... "),
  2854. xlog_dir);
  2855. fflush(stdout);
  2856. if (chmod(xlog_dir, S_IRWXU) != 0)
  2857. {
  2858. fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
  2859. progname, xlog_dir, strerror(errno));
  2860. exit_nicely();
  2861. }
  2862. else
  2863. check_ok();
  2864. found_existing_xlogdir = true;
  2865. break;
  2866. case 2:
  2867. case 3:
  2868. case 4:
  2869. /* Present and not empty */
  2870. fprintf(stderr,
  2871. _("%s: directory \"%s\" exists but is not empty\n"),
  2872. progname, xlog_dir);
  2873. if (ret != 4)
  2874. warn_on_mount_point(ret);
  2875. else
  2876. fprintf(stderr,
  2877. _("If you want to store the transaction log there, either\n"
  2878. "remove or empty the directory \"%s\".\n"),
  2879. xlog_dir);
  2880. exit_nicely();
  2881. default:
  2882. /* Trouble accessing directory */
  2883. fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
  2884. progname, xlog_dir, strerror(errno));
  2885. exit_nicely();
  2886. }
  2887. /* form name of the place where the symlink must go */
  2888. linkloc = psprintf("%s/pg_xlog", pg_data);
  2889. #ifdef HAVE_SYMLINK
  2890. if (symlink(xlog_dir, linkloc) != 0)
  2891. {
  2892. fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
  2893. progname, linkloc, strerror(errno));
  2894. exit_nicely();
  2895. }
  2896. #else
  2897. fprintf(stderr, _("%s: symlinks are not supported on this platform"));
  2898. exit_nicely();
  2899. #endif
  2900. free(linkloc);
  2901. }
  2902. }
  2903. void
  2904. warn_on_mount_point(int error)
  2905. {
  2906. if (error == 2)
  2907. fprintf(stderr,
  2908. _("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.\n"));
  2909. else if (error == 3)
  2910. fprintf(stderr,
  2911. _("It contains a lost+found directory, perhaps due to it being a mount point.\n"));
  2912. fprintf(stderr,
  2913. _("Using a mount point directly as the data directory is not recommended.\n"
  2914. "Create a subdirectory under the mount point.\n"));
  2915. }
  2916. void
  2917. initialize_data_directory(void)
  2918. {
  2919. int i;
  2920. setup_signals();
  2921. umask(S_IRWXG | S_IRWXO);
  2922. create_data_directory();
  2923. create_xlog_symlink();
  2924. /* Create required subdirectories */
  2925. printf(_("creating subdirectories ... "));
  2926. fflush(stdout);
  2927. for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
  2928. {
  2929. if (!mkdatadir(subdirs[i]))
  2930. exit_nicely();
  2931. }
  2932. check_ok();
  2933. /* Top level PG_VERSION is checked by bootstrapper, so make it first */
  2934. write_version_file(NULL);
  2935. /* Select suitable configuration settings */
  2936. set_null_conf();
  2937. test_config_settings();
  2938. /* Now create all the text config files */
  2939. setup_config();
  2940. /* Bootstrap template1 */
  2941. bootstrap_template1();
  2942. /*
  2943. * Make the per-database PG_VERSION for template1 only after init'ing it
  2944. */
  2945. write_version_file("base/1");
  2946. /* Create the stuff we don't need to use bootstrap mode for */
  2947. setup_auth();
  2948. if (pwprompt || pwfilename)
  2949. get_set_pwd();
  2950. setup_depend();
  2951. setup_sysviews();
  2952. setup_description();
  2953. setup_collation();
  2954. setup_conversion();
  2955. setup_dictionary();
  2956. setup_privileges();
  2957. setup_schema();
  2958. load_plpgsql();
  2959. vacuum_db();
  2960. make_template0();
  2961. make_postgres();
  2962. }
  2963. int
  2964. main(int argc, char *argv[])
  2965. {
  2966. static struct option long_options[] = {
  2967. {"pgdata", required_argument, NULL, 'D'},
  2968. {"encoding", required_argument, NULL, 'E'},
  2969. {"locale", required_argument, NULL, 1},
  2970. {"lc-collate", required_argument, NULL, 2},
  2971. {"lc-ctype", required_argument, NULL, 3},
  2972. {"lc-monetary", required_argument, NULL, 4},
  2973. {"lc-numeric", required_argument, NULL, 5},
  2974. {"lc-time", required_argument, NULL, 6},
  2975. {"lc-messages", required_argument, NULL, 7},
  2976. {"no-locale", no_argument, NULL, 8},
  2977. {"text-search-config", required_argument, NULL, 'T'},
  2978. {"auth", required_argument, NULL, 'A'},
  2979. {"auth-local", required_argument, NULL, 10},
  2980. {"auth-host", required_argument, NULL, 11},
  2981. {"pwprompt", no_argument, NULL, 'W'},
  2982. {"pwfile", required_argument, NULL, 9},
  2983. {"username", required_argument, NULL, 'U'},
  2984. {"help", no_argument, NULL, '?'},
  2985. {"version", no_argument, NULL, 'V'},
  2986. {"debug", no_argument, NULL, 'd'},
  2987. {"show", no_argument, NULL, 's'},
  2988. {"noclean", no_argument, NULL, 'n'},
  2989. {"nosync", no_argument, NULL, 'N'},
  2990. {"sync-only", no_argument, NULL, 'S'},
  2991. {"xlogdir", required_argument, NULL, 'X'},
  2992. {"data-checksums", no_argument, NULL, 'k'},
  2993. {NULL, 0, NULL, 0}
  2994. };
  2995. /*
  2996. * options with no short version return a low integer, the rest return
  2997. * their short version value
  2998. */
  2999. int c;
  3000. int option_index;
  3001. char *effective_user;
  3002. char bin_dir[MAXPGPATH];
  3003. /*
  3004. * Ensure that buffering behavior of stdout and stderr matches what it is
  3005. * in interactive usage (at least on most platforms). This prevents
  3006. * unexpected output ordering when, eg, output is redirected to a file.
  3007. * POSIX says we must do this before any other usage of these files.
  3008. */
  3009. setvbuf(stdout, NULL, PG_IOLBF, 0);
  3010. setvbuf(stderr, NULL, _IONBF, 0);
  3011. progname = get_progname(argv[0]);
  3012. set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
  3013. if (argc > 1)
  3014. {
  3015. if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
  3016. {
  3017. usage(progname);
  3018. exit(0);
  3019. }
  3020. if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
  3021. {
  3022. puts("initdb (PostgreSQL) " PG_VERSION);
  3023. exit(0);
  3024. }
  3025. }
  3026. /* process command-line options */
  3027. while ((c = getopt_long(argc, argv, "dD:E:kL:nNU:WA:sST:X:", long_options, &option_index)) != -1)
  3028. {
  3029. switch (c)
  3030. {
  3031. case 'A':
  3032. authmethodlocal = authmethodhost = pg_strdup(optarg);
  3033. /*
  3034. * When ident is specified, use peer for local connections.
  3035. * Mirrored, when peer is specified, use ident for TCP/IP
  3036. * connections.
  3037. */
  3038. if (strcmp(authmethodhost, "ident") == 0)
  3039. authmethodlocal = "peer";
  3040. else if (strcmp(authmethodlocal, "peer") == 0)
  3041. authmethodhost = "ident";
  3042. break;
  3043. case 10:
  3044. authmethodlocal = pg_strdup(optarg);
  3045. break;
  3046. case 11:
  3047. authmethodhost = pg_strdup(optarg);
  3048. break;
  3049. case 'D':
  3050. pg_data = pg_strdup(optarg);
  3051. break;
  3052. case 'E':
  3053. encoding = pg_strdup(optarg);
  3054. break;
  3055. case 'W':
  3056. pwprompt = true;
  3057. break;
  3058. case 'U':
  3059. username = pg_strdup(optarg);
  3060. break;
  3061. case 'd':
  3062. debug = true;
  3063. printf(_("Running in debug mode.\n"));
  3064. break;
  3065. case 'n':
  3066. noclean = true;
  3067. printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
  3068. break;
  3069. case 'N':
  3070. do_sync = false;
  3071. break;
  3072. case 'S':
  3073. sync_only = true;
  3074. break;
  3075. case 'k':
  3076. data_checksums = true;
  3077. break;
  3078. case 'L':
  3079. share_path = pg_strdup(optarg);
  3080. break;
  3081. case 1:
  3082. locale = pg_strdup(optarg);
  3083. break;
  3084. case 2:
  3085. lc_collate = pg_strdup(optarg);
  3086. break;
  3087. case 3:
  3088. lc_ctype = pg_strdup(optarg);
  3089. break;
  3090. case 4:
  3091. lc_monetary = pg_strdup(optarg);
  3092. break;
  3093. case 5:
  3094. lc_numeric = pg_strdup(optarg);
  3095. break;
  3096. case 6:
  3097. lc_time = pg_strdup(optarg);
  3098. break;
  3099. case 7:
  3100. lc_messages = pg_strdup(optarg);
  3101. break;
  3102. case 8:
  3103. locale = "C";
  3104. break;
  3105. case 9:
  3106. pwfilename = pg_strdup(optarg);
  3107. break;
  3108. case 's':
  3109. show_setting = true;
  3110. break;
  3111. case 'T':
  3112. default_text_search_config = pg_strdup(optarg);
  3113. break;
  3114. case 'X':
  3115. xlog_dir = pg_strdup(optarg);
  3116. break;
  3117. default:
  3118. /* getopt_long already emitted a complaint */
  3119. fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
  3120. progname);
  3121. exit(1);
  3122. }
  3123. }
  3124. /*
  3125. * Non-option argument specifies data directory as long as it wasn't
  3126. * already specified with -D / --pgdata
  3127. */
  3128. if (optind < argc && strlen(pg_data) == 0)
  3129. {
  3130. pg_data = pg_strdup(argv[optind]);
  3131. optind++;
  3132. }
  3133. if (optind < argc)
  3134. {
  3135. fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
  3136. progname, argv[optind]);
  3137. fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
  3138. progname);
  3139. exit(1);
  3140. }
  3141. /* If we only need to fsync, just to it and exit */
  3142. if (sync_only)
  3143. {
  3144. setup_pgdata();
  3145. perform_fsync();
  3146. return 0;
  3147. }
  3148. if (pwprompt && pwfilename)
  3149. {
  3150. fprintf(stderr, _("%s: password prompt and password file cannot be specified together\n"), progname);
  3151. exit(1);
  3152. }
  3153. check_authmethod_unspecified(&authmethodlocal);
  3154. check_authmethod_unspecified(&authmethodhost);
  3155. check_authmethod_valid(authmethodlocal, auth_methods_local, "local");
  3156. check_authmethod_valid(authmethodhost, auth_methods_host, "host");
  3157. check_need_password(authmethodlocal, authmethodhost);
  3158. get_restricted_token();
  3159. setup_pgdata();
  3160. setup_bin_paths(argv[0]);
  3161. effective_user = get_id();
  3162. if (strlen(username) == 0)
  3163. username = effective_user;
  3164. printf(_("The files belonging to this database system will be owned "
  3165. "by user \"%s\".\n"
  3166. "This user must also own the server process.\n\n"),
  3167. effective_user);
  3168. set_info_version();
  3169. setup_data_file_paths();
  3170. setup_locale_encoding();
  3171. setup_text_search();
  3172. printf("\n");
  3173. if (data_checksums)
  3174. printf(_("Data page checksums are enabled.\n"));
  3175. else
  3176. printf(_("Data page checksums are disabled.\n"));
  3177. printf("\n");
  3178. initialize_data_directory();
  3179. if (do_sync)
  3180. perform_fsync();
  3181. else
  3182. printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
  3183. if (authwarning != NULL)
  3184. fprintf(stderr, "%s", authwarning);
  3185. /* Get directory specification used to start this executable */
  3186. strlcpy(bin_dir, argv[0], sizeof(bin_dir));
  3187. get_parent_directory(bin_dir);
  3188. printf(_("\nSuccess. You can now start the database server using:\n\n"
  3189. " %s%s%spostgres%s -D %s%s%s\n"
  3190. "or\n"
  3191. " %s%s%spg_ctl%s -D %s%s%s -l logfile start\n\n"),
  3192. QUOTE_PATH, bin_dir, (strlen(bin_dir) > 0) ? DIR_SEP : "", QUOTE_PATH,
  3193. QUOTE_PATH, pgdata_native, QUOTE_PATH,
  3194. QUOTE_PATH, bin_dir, (strlen(bin_dir) > 0) ? DIR_SEP : "", QUOTE_PATH,
  3195. QUOTE_PATH, pgdata_native, QUOTE_PATH);
  3196. return 0;
  3197. }