PageRenderTime 67ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/src/bin/initdb/initdb.c

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