Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * main.c
4 : * Stub main() routine for the postgres executable.
5 : *
6 : * This does some essential startup tasks for any incarnation of postgres
7 : * (postmaster, standalone backend, standalone bootstrap process, or a
8 : * separately exec'd child of a postmaster) and then dispatches to the
9 : * proper FooMain() routine for the incarnation.
10 : *
11 : *
12 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
13 : * Portions Copyright (c) 1994, Regents of the University of California
14 : *
15 : *
16 : * IDENTIFICATION
17 : * src/backend/main/main.c
18 : *
19 : *-------------------------------------------------------------------------
20 : */
21 : #include "postgres.h"
22 :
23 : #include <unistd.h>
24 :
25 : #if defined(WIN32)
26 : #include <crtdbg.h>
27 : #endif
28 :
29 : #if defined(__NetBSD__)
30 : #include <sys/param.h>
31 : #endif
32 :
33 : #include "bootstrap/bootstrap.h"
34 : #include "common/username.h"
35 : #include "postmaster/postmaster.h"
36 : #include "tcop/tcopprot.h"
37 : #include "utils/help_config.h"
38 : #include "utils/memutils.h"
39 : #include "utils/pg_locale.h"
40 : #include "utils/ps_status.h"
41 :
42 :
43 : const char *progname;
44 : static bool reached_main = false;
45 :
46 :
47 : static void startup_hacks(const char *progname);
48 : static void init_locale(const char *categoryname, int category, const char *locale);
49 : static void help(const char *progname);
50 : static void check_root(const char *progname);
51 :
52 :
53 : /*
54 : * Any Postgres server process begins execution here.
55 : */
56 : int
57 3280 : main(int argc, char *argv[])
58 : {
59 3280 : bool do_check_root = true;
60 :
61 3280 : reached_main = true;
62 :
63 : /*
64 : * If supported on the current platform, set up a handler to be called if
65 : * the backend/postmaster crashes with a fatal signal or exception.
66 : */
67 : #if defined(WIN32)
68 : pgwin32_install_crashdump_handler();
69 : #endif
70 :
71 3280 : progname = get_progname(argv[0]);
72 :
73 : /*
74 : * Platform-specific startup hacks
75 : */
76 3280 : startup_hacks(progname);
77 :
78 : /*
79 : * Remember the physical location of the initially given argv[] array for
80 : * possible use by ps display. On some platforms, the argv[] storage must
81 : * be overwritten in order to set the process title for ps. In such cases
82 : * save_ps_display_args makes and returns a new copy of the argv[] array.
83 : *
84 : * save_ps_display_args may also move the environment strings to make
85 : * extra room. Therefore this should be done as early as possible during
86 : * startup, to avoid entanglements with code that might save a getenv()
87 : * result pointer.
88 : */
89 3280 : argv = save_ps_display_args(argc, argv);
90 :
91 : /*
92 : * Fire up essential subsystems: error and memory management
93 : *
94 : * Code after this point is allowed to use elog/ereport, though
95 : * localization of messages may not work right away, and messages won't go
96 : * anywhere but stderr until GUC settings get loaded.
97 : */
98 3280 : MemoryContextInit();
99 :
100 : /*
101 : * Set up locale information
102 : */
103 3280 : set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("postgres"));
104 :
105 : /*
106 : * In the postmaster, absorb the environment values for LC_COLLATE and
107 : * LC_CTYPE. Individual backends will change these later to settings
108 : * taken from pg_database, but the postmaster cannot do that. If we leave
109 : * these set to "C" then message localization might not work well in the
110 : * postmaster.
111 : */
112 3280 : init_locale("LC_COLLATE", LC_COLLATE, "");
113 3280 : init_locale("LC_CTYPE", LC_CTYPE, "");
114 :
115 : /*
116 : * LC_MESSAGES will get set later during GUC option processing, but we set
117 : * it here to allow startup error messages to be localized.
118 : */
119 : #ifdef LC_MESSAGES
120 3280 : init_locale("LC_MESSAGES", LC_MESSAGES, "");
121 : #endif
122 :
123 : /*
124 : * We keep these set to "C" always, except transiently in pg_locale.c; see
125 : * that file for explanations.
126 : */
127 3280 : init_locale("LC_MONETARY", LC_MONETARY, "C");
128 3280 : init_locale("LC_NUMERIC", LC_NUMERIC, "C");
129 3280 : init_locale("LC_TIME", LC_TIME, "C");
130 :
131 : /*
132 : * Now that we have absorbed as much as we wish to from the locale
133 : * environment, remove any LC_ALL setting, so that the environment
134 : * variables installed by pg_perm_setlocale have force.
135 : */
136 3280 : unsetenv("LC_ALL");
137 :
138 : /*
139 : * Catch standard options before doing much else, in particular before we
140 : * insist on not being root.
141 : */
142 3280 : if (argc > 1)
143 : {
144 3280 : if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
145 : {
146 0 : help(progname);
147 0 : exit(0);
148 : }
149 3280 : if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
150 : {
151 1314 : fputs(PG_BACKEND_VERSIONSTR, stdout);
152 1314 : exit(0);
153 : }
154 :
155 : /*
156 : * In addition to the above, we allow "--describe-config" and "-C var"
157 : * to be called by root. This is reasonably safe since these are
158 : * read-only activities. The -C case is important because pg_ctl may
159 : * try to invoke it while still holding administrator privileges on
160 : * Windows. Note that while -C can normally be in any argv position,
161 : * if you want to bypass the root check you must put it first. This
162 : * reduces the risk that we might misinterpret some other mode's -C
163 : * switch as being the postmaster/postgres one.
164 : */
165 1966 : if (strcmp(argv[1], "--describe-config") == 0)
166 0 : do_check_root = false;
167 1966 : else if (argc > 2 && strcmp(argv[1], "-C") == 0)
168 0 : do_check_root = false;
169 : }
170 :
171 : /*
172 : * Make sure we are not running as root, unless it's safe for the selected
173 : * option.
174 : */
175 1966 : if (do_check_root)
176 1966 : check_root(progname);
177 :
178 : /*
179 : * Dispatch to one of various subprograms depending on first argument.
180 : */
181 :
182 1966 : if (argc > 1 && strcmp(argv[1], "--check") == 0)
183 228 : BootstrapModeMain(argc, argv, true);
184 1738 : else if (argc > 1 && strcmp(argv[1], "--boot") == 0)
185 92 : BootstrapModeMain(argc, argv, false);
186 : #ifdef EXEC_BACKEND
187 : else if (argc > 1 && strncmp(argv[1], "--forkchild", 11) == 0)
188 : SubPostmasterMain(argc, argv);
189 : #endif
190 1646 : else if (argc > 1 && strcmp(argv[1], "--describe-config") == 0)
191 0 : GucInfoMain();
192 1646 : else if (argc > 1 && strcmp(argv[1], "--single") == 0)
193 112 : PostgresSingleUserMain(argc, argv,
194 112 : strdup(get_user_name_or_exit(progname)));
195 : else
196 1534 : PostmasterMain(argc, argv);
197 : /* the functions above should not return */
198 : abort();
199 : }
200 :
201 :
202 :
203 : /*
204 : * Place platform-specific startup hacks here. This is the right
205 : * place to put code that must be executed early in the launch of any new
206 : * server process. Note that this code will NOT be executed when a backend
207 : * or sub-bootstrap process is forked, unless we are in a fork/exec
208 : * environment (ie EXEC_BACKEND is defined).
209 : *
210 : * XXX The need for code here is proof that the platform in question
211 : * is too brain-dead to provide a standard C execution environment
212 : * without help. Avoid adding more here, if you can.
213 : */
214 : static void
215 3280 : startup_hacks(const char *progname)
216 : {
217 : /*
218 : * Windows-specific execution environment hacking.
219 : */
220 : #ifdef WIN32
221 : {
222 : WSADATA wsaData;
223 : int err;
224 :
225 : /* Make output streams unbuffered by default */
226 : setvbuf(stdout, NULL, _IONBF, 0);
227 : setvbuf(stderr, NULL, _IONBF, 0);
228 :
229 : /* Prepare Winsock */
230 : err = WSAStartup(MAKEWORD(2, 2), &wsaData);
231 : if (err != 0)
232 : {
233 : write_stderr("%s: WSAStartup failed: %d\n",
234 : progname, err);
235 : exit(1);
236 : }
237 :
238 : /*
239 : * By default abort() only generates a crash-dump in *non* debug
240 : * builds. As our Assert() / ExceptionalCondition() uses abort(),
241 : * leaving the default in place would make debugging harder.
242 : *
243 : * MINGW's own C runtime doesn't have _set_abort_behavior(). When
244 : * targeting Microsoft's UCRT with mingw, it never links to the debug
245 : * version of the library and thus doesn't need the call to
246 : * _set_abort_behavior() either.
247 : */
248 : #if !defined(__MINGW32__) && !defined(__MINGW64__)
249 : _set_abort_behavior(_CALL_REPORTFAULT | _WRITE_ABORT_MSG,
250 : _CALL_REPORTFAULT | _WRITE_ABORT_MSG);
251 : #endif /* !defined(__MINGW32__) &&
252 : * !defined(__MINGW64__) */
253 :
254 : /*
255 : * SEM_FAILCRITICALERRORS causes more errors to be reported to
256 : * callers.
257 : *
258 : * We used to also specify SEM_NOGPFAULTERRORBOX, but that prevents
259 : * windows crash reporting from working. Which includes registered
260 : * just-in-time debuggers, making it unnecessarily hard to debug
261 : * problems on windows. Now we try to disable sources of popups
262 : * separately below (note that SEM_NOGPFAULTERRORBOX did not actually
263 : * prevent all sources of such popups).
264 : */
265 : SetErrorMode(SEM_FAILCRITICALERRORS);
266 :
267 : /*
268 : * Show errors on stderr instead of popup box (note this doesn't
269 : * affect errors originating in the C runtime, see below).
270 : */
271 : _set_error_mode(_OUT_TO_STDERR);
272 :
273 : /*
274 : * In DEBUG builds, errors, including assertions, C runtime errors are
275 : * reported via _CrtDbgReport. By default such errors are displayed
276 : * with a popup (even with NOGPFAULTERRORBOX), preventing forward
277 : * progress. Instead report such errors stderr (and the debugger).
278 : * This is C runtime specific and thus the above incantations aren't
279 : * sufficient to suppress these popups.
280 : */
281 : _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
282 : _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
283 : _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
284 : _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
285 : _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
286 : _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
287 : }
288 : #endif /* WIN32 */
289 3280 : }
290 :
291 :
292 : /*
293 : * Make the initial permanent setting for a locale category. If that fails,
294 : * perhaps due to LC_foo=invalid in the environment, use locale C. If even
295 : * that fails, perhaps due to out-of-memory, the entire startup fails with it.
296 : * When this returns, we are guaranteed to have a setting for the given
297 : * category's environment variable.
298 : */
299 : static void
300 19680 : init_locale(const char *categoryname, int category, const char *locale)
301 : {
302 19680 : if (pg_perm_setlocale(category, locale) == NULL &&
303 0 : pg_perm_setlocale(category, "C") == NULL)
304 0 : elog(FATAL, "could not adopt \"%s\" locale nor C locale for %s",
305 : locale, categoryname);
306 19680 : }
307 :
308 :
309 :
310 : /*
311 : * Help display should match the options accepted by PostmasterMain()
312 : * and PostgresMain().
313 : *
314 : * XXX On Windows, non-ASCII localizations of these messages only display
315 : * correctly if the console output code page covers the necessary characters.
316 : * Messages emitted in write_console() do not exhibit this problem.
317 : */
318 : static void
319 0 : help(const char *progname)
320 : {
321 0 : printf(_("%s is the PostgreSQL server.\n\n"), progname);
322 0 : printf(_("Usage:\n %s [OPTION]...\n\n"), progname);
323 0 : printf(_("Options:\n"));
324 0 : printf(_(" -B NBUFFERS number of shared buffers\n"));
325 0 : printf(_(" -c NAME=VALUE set run-time parameter\n"));
326 0 : printf(_(" -C NAME print value of run-time parameter, then exit\n"));
327 0 : printf(_(" -d 1-5 debugging level\n"));
328 0 : printf(_(" -D DATADIR database directory\n"));
329 0 : printf(_(" -e use European date input format (DMY)\n"));
330 0 : printf(_(" -F turn fsync off\n"));
331 0 : printf(_(" -h HOSTNAME host name or IP address to listen on\n"));
332 0 : printf(_(" -i enable TCP/IP connections (deprecated)\n"));
333 0 : printf(_(" -k DIRECTORY Unix-domain socket location\n"));
334 : #ifdef USE_SSL
335 0 : printf(_(" -l enable SSL connections\n"));
336 : #endif
337 0 : printf(_(" -N MAX-CONNECT maximum number of allowed connections\n"));
338 0 : printf(_(" -p PORT port number to listen on\n"));
339 0 : printf(_(" -s show statistics after each query\n"));
340 0 : printf(_(" -S WORK-MEM set amount of memory for sorts (in kB)\n"));
341 0 : printf(_(" -V, --version output version information, then exit\n"));
342 0 : printf(_(" --NAME=VALUE set run-time parameter\n"));
343 0 : printf(_(" --describe-config describe configuration parameters, then exit\n"));
344 0 : printf(_(" -?, --help show this help, then exit\n"));
345 :
346 0 : printf(_("\nDeveloper options:\n"));
347 0 : printf(_(" -f s|i|o|b|t|n|m|h forbid use of some plan types\n"));
348 0 : printf(_(" -O allow system table structure changes\n"));
349 0 : printf(_(" -P disable system indexes\n"));
350 0 : printf(_(" -t pa|pl|ex show timings after each query\n"));
351 0 : printf(_(" -T send SIGABRT to all backend processes if one dies\n"));
352 0 : printf(_(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
353 :
354 0 : printf(_("\nOptions for single-user mode:\n"));
355 0 : printf(_(" --single selects single-user mode (must be first argument)\n"));
356 0 : printf(_(" DBNAME database name (defaults to user name)\n"));
357 0 : printf(_(" -d 0-5 override debugging level\n"));
358 0 : printf(_(" -E echo statement before execution\n"));
359 0 : printf(_(" -j do not use newline as interactive query delimiter\n"));
360 0 : printf(_(" -r FILENAME send stdout and stderr to given file\n"));
361 :
362 0 : printf(_("\nOptions for bootstrapping mode:\n"));
363 0 : printf(_(" --boot selects bootstrapping mode (must be first argument)\n"));
364 0 : printf(_(" --check selects check mode (must be first argument)\n"));
365 0 : printf(_(" DBNAME database name (mandatory argument in bootstrapping mode)\n"));
366 0 : printf(_(" -r FILENAME send stdout and stderr to given file\n"));
367 :
368 0 : printf(_("\nPlease read the documentation for the complete list of run-time\n"
369 : "configuration settings and how to set them on the command line or in\n"
370 : "the configuration file.\n\n"
371 : "Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
372 0 : printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
373 0 : }
374 :
375 :
376 :
377 : static void
378 1966 : check_root(const char *progname)
379 : {
380 : #ifndef WIN32
381 1966 : if (geteuid() == 0)
382 : {
383 0 : write_stderr("\"root\" execution of the PostgreSQL server is not permitted.\n"
384 : "The server must be started under an unprivileged user ID to prevent\n"
385 : "possible system security compromise. See the documentation for\n"
386 : "more information on how to properly start the server.\n");
387 0 : exit(1);
388 : }
389 :
390 : /*
391 : * Also make sure that real and effective uids are the same. Executing as
392 : * a setuid program from a root shell is a security hole, since on many
393 : * platforms a nefarious subroutine could setuid back to root if real uid
394 : * is root. (Since nobody actually uses postgres as a setuid program,
395 : * trying to actively fix this situation seems more trouble than it's
396 : * worth; we'll just expend the effort to check for it.)
397 : */
398 1966 : if (getuid() != geteuid())
399 : {
400 0 : write_stderr("%s: real and effective user IDs must match\n",
401 : progname);
402 0 : exit(1);
403 : }
404 : #else /* WIN32 */
405 : if (pgwin32_is_admin())
406 : {
407 : write_stderr("Execution of PostgreSQL by a user with administrative permissions is not\n"
408 : "permitted.\n"
409 : "The server must be started under an unprivileged user ID to prevent\n"
410 : "possible system security compromises. See the documentation for\n"
411 : "more information on how to properly start the server.\n");
412 : exit(1);
413 : }
414 : #endif /* WIN32 */
415 1966 : }
416 :
417 : /*
418 : * At least on linux, set_ps_display() breaks /proc/$pid/environ. The
419 : * sanitizer library uses /proc/$pid/environ to implement getenv() as it wants
420 : * to work independent of libc. When just using undefined and alignment
421 : * sanitizers, the sanitizer library is only initialized when the first error
422 : * occurs, by which time we've often already called set_ps_display(),
423 : * preventing the sanitizer libraries from seeing the options.
424 : *
425 : * We can work around that by defining __ubsan_default_options, a weak symbol
426 : * libsanitizer uses to get defaults from the application, and return
427 : * getenv("UBSAN_OPTIONS"). But only if main already was reached, so that we
428 : * don't end up relying on a not-yet-working getenv().
429 : *
430 : * As this function won't get called when not running a sanitizer, it doesn't
431 : * seem necessary to only compile it conditionally.
432 : */
433 : const char *__ubsan_default_options(void);
434 : const char *
435 0 : __ubsan_default_options(void)
436 : {
437 : /* don't call libc before it's guaranteed to be initialized */
438 0 : if (!reached_main)
439 0 : return "";
440 :
441 0 : return getenv("UBSAN_OPTIONS");
442 : }
|