1 /*-------------------------------------------------------------------------
2  *
3  * pg_ctl --- start/stops/restarts the PostgreSQL server
4  *
5  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
6  *
7  * src/bin/pg_ctl/pg_ctl.c
8  *
9  *-------------------------------------------------------------------------
10  */
11 
12 #ifdef WIN32
13 /*
14  * Need this to get defines for restricted tokens and jobs. And it
15  * has to be set before any header from the Win32 API is loaded.
16  */
17 #define _WIN32_WINNT 0x0501
18 #endif
19 
20 #include "postgres_fe.h"
21 
22 #include "libpq-fe.h"
23 #include "pqexpbuffer.h"
24 
25 #include <fcntl.h>
26 #include <locale.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 
34 #ifdef HAVE_SYS_RESOURCE_H
35 #include <sys/time.h>
36 #include <sys/resource.h>
37 #endif
38 
39 #include "getopt_long.h"
40 #include "miscadmin.h"
41 
42 /* PID can be negative for standalone backend */
43 typedef long pgpid_t;
44 
45 
46 typedef enum
47 {
48 	SMART_MODE,
49 	FAST_MODE,
50 	IMMEDIATE_MODE
51 } ShutdownMode;
52 
53 
54 typedef enum
55 {
56 	NO_COMMAND = 0,
57 	INIT_COMMAND,
58 	START_COMMAND,
59 	STOP_COMMAND,
60 	RESTART_COMMAND,
61 	RELOAD_COMMAND,
62 	STATUS_COMMAND,
63 	PROMOTE_COMMAND,
64 	KILL_COMMAND,
65 	REGISTER_COMMAND,
66 	UNREGISTER_COMMAND,
67 	RUN_AS_SERVICE_COMMAND
68 } CtlCommand;
69 
70 #define DEFAULT_WAIT	60
71 
72 static bool do_wait = false;
73 static bool wait_set = false;
74 static int	wait_seconds = DEFAULT_WAIT;
75 static bool wait_seconds_arg = false;
76 static bool silent_mode = false;
77 static ShutdownMode shutdown_mode = FAST_MODE;
78 static int	sig = SIGINT;		/* default */
79 static CtlCommand ctl_command = NO_COMMAND;
80 static char *pg_data = NULL;
81 static char *pg_config = NULL;
82 static char *pgdata_opt = NULL;
83 static char *post_opts = NULL;
84 static const char *progname;
85 static char *log_file = NULL;
86 static char *exec_path = NULL;
87 static char *event_source = NULL;
88 static char *register_servicename = "PostgreSQL";		/* FIXME: + version ID? */
89 static char *register_username = NULL;
90 static char *register_password = NULL;
91 static char *argv0 = NULL;
92 static bool allow_core_files = false;
93 static time_t start_time;
94 
95 static char postopts_file[MAXPGPATH];
96 static char version_file[MAXPGPATH];
97 static char pid_file[MAXPGPATH];
98 static char backup_file[MAXPGPATH];
99 static char recovery_file[MAXPGPATH];
100 static char promote_file[MAXPGPATH];
101 
102 #ifdef WIN32
103 static DWORD pgctl_start_type = SERVICE_AUTO_START;
104 static SERVICE_STATUS status;
105 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
106 static HANDLE shutdownHandles[2];
107 static pid_t postmasterPID = -1;
108 
109 #define shutdownEvent	  shutdownHandles[0]
110 #define postmasterProcess shutdownHandles[1]
111 #endif
112 
113 
114 static void write_stderr(const char *fmt,...) pg_attribute_printf(1, 2);
115 static void do_advice(void);
116 static void do_help(void);
117 static void set_mode(char *modeopt);
118 static void set_sig(char *signame);
119 static void do_init(void);
120 static void do_start(void);
121 static void do_stop(void);
122 static void do_restart(void);
123 static void do_reload(void);
124 static void do_status(void);
125 static void do_promote(void);
126 static void do_kill(pgpid_t pid);
127 static void print_msg(const char *msg);
128 static void adjust_data_dir(void);
129 
130 #ifdef WIN32
131 #if (_MSC_VER >= 1800)
132 #include <versionhelpers.h>
133 #else
134 static bool IsWindowsXPOrGreater(void);
135 static bool IsWindows7OrGreater(void);
136 #endif
137 static bool pgwin32_IsInstalled(SC_HANDLE);
138 static char *pgwin32_CommandLine(bool);
139 static void pgwin32_doRegister(void);
140 static void pgwin32_doUnregister(void);
141 static void pgwin32_SetServiceStatus(DWORD);
142 static void WINAPI pgwin32_ServiceHandler(DWORD);
143 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
144 static void pgwin32_doRunAsService(void);
145 static int	CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
146 #endif
147 
148 static pgpid_t get_pgpid(bool is_status_request);
149 static char **readfile(const char *path);
150 static void free_readfile(char **optlines);
151 static pgpid_t start_postmaster(void);
152 static void read_post_opts(void);
153 
154 static PGPing test_postmaster_connection(pgpid_t pm_pid, bool do_checkpoint);
155 static bool postmaster_is_alive(pid_t pid);
156 
157 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
158 static void unlimit_core_size(void);
159 #endif
160 
161 
162 #ifdef WIN32
163 static void
write_eventlog(int level,const char * line)164 write_eventlog(int level, const char *line)
165 {
166 	static HANDLE evtHandle = INVALID_HANDLE_VALUE;
167 
168 	if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
169 		return;
170 
171 	if (evtHandle == INVALID_HANDLE_VALUE)
172 	{
173 		evtHandle = RegisterEventSource(NULL,
174 						 event_source ? event_source : DEFAULT_EVENT_SOURCE);
175 		if (evtHandle == NULL)
176 		{
177 			evtHandle = INVALID_HANDLE_VALUE;
178 			return;
179 		}
180 	}
181 
182 	ReportEvent(evtHandle,
183 				level,
184 				0,
185 				0,				/* All events are Id 0 */
186 				NULL,
187 				1,
188 				0,
189 				&line,
190 				NULL);
191 }
192 #endif
193 
194 /*
195  * Write errors to stderr (or by equal means when stderr is
196  * not available).
197  */
198 static void
write_stderr(const char * fmt,...)199 write_stderr(const char *fmt,...)
200 {
201 	va_list		ap;
202 
203 	va_start(ap, fmt);
204 #ifndef WIN32
205 	/* On Unix, we just fprintf to stderr */
206 	vfprintf(stderr, fmt, ap);
207 #else
208 
209 	/*
210 	 * On Win32, we print to stderr if running on a console, or write to
211 	 * eventlog if running as a service
212 	 */
213 	if (pgwin32_is_service())	/* Running as a service */
214 	{
215 		char		errbuf[2048];		/* Arbitrary size? */
216 
217 		vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
218 
219 		write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
220 	}
221 	else
222 		/* Not running as service, write to stderr */
223 		vfprintf(stderr, fmt, ap);
224 #endif
225 	va_end(ap);
226 }
227 
228 /*
229  * Given an already-localized string, print it to stdout unless the
230  * user has specified that no messages should be printed.
231  */
232 static void
print_msg(const char * msg)233 print_msg(const char *msg)
234 {
235 	if (!silent_mode)
236 	{
237 		fputs(msg, stdout);
238 		fflush(stdout);
239 	}
240 }
241 
242 static pgpid_t
get_pgpid(bool is_status_request)243 get_pgpid(bool is_status_request)
244 {
245 	FILE	   *pidf;
246 	long		pid;
247 	struct stat statbuf;
248 
249 	if (stat(pg_data, &statbuf) != 0)
250 	{
251 		if (errno == ENOENT)
252 			write_stderr(_("%s: directory \"%s\" does not exist\n"), progname,
253 						 pg_data);
254 		else
255 			write_stderr(_("%s: could not access directory \"%s\": %s\n"), progname,
256 						 pg_data, strerror(errno));
257 
258 		/*
259 		 * The Linux Standard Base Core Specification 3.1 says this should
260 		 * return '4, program or service status is unknown'
261 		 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-g
262 		 * eneric/iniscrptact.html
263 		 */
264 		exit(is_status_request ? 4 : 1);
265 	}
266 
267 	if (stat(version_file, &statbuf) != 0 && errno == ENOENT)
268 	{
269 		write_stderr(_("%s: directory \"%s\" is not a database cluster directory\n"),
270 					 progname, pg_data);
271 		exit(is_status_request ? 4 : 1);
272 	}
273 
274 	pidf = fopen(pid_file, "r");
275 	if (pidf == NULL)
276 	{
277 		/* No pid file, not an error on startup */
278 		if (errno == ENOENT)
279 			return 0;
280 		else
281 		{
282 			write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
283 						 progname, pid_file, strerror(errno));
284 			exit(1);
285 		}
286 	}
287 	if (fscanf(pidf, "%ld", &pid) != 1)
288 	{
289 		/* Is the file empty? */
290 		if (ftell(pidf) == 0 && feof(pidf))
291 			write_stderr(_("%s: the PID file \"%s\" is empty\n"),
292 						 progname, pid_file);
293 		else
294 			write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
295 						 progname, pid_file);
296 		exit(1);
297 	}
298 	fclose(pidf);
299 	return (pgpid_t) pid;
300 }
301 
302 
303 /*
304  * get the lines from a text file - return NULL if file can't be opened
305  */
306 static char **
readfile(const char * path)307 readfile(const char *path)
308 {
309 	int			fd;
310 	int			nlines;
311 	char	  **result;
312 	char	   *buffer;
313 	char	   *linebegin;
314 	int			i;
315 	int			n;
316 	int			len;
317 	struct stat statbuf;
318 
319 	/*
320 	 * Slurp the file into memory.
321 	 *
322 	 * The file can change concurrently, so we read the whole file into memory
323 	 * with a single read() call. That's not guaranteed to get an atomic
324 	 * snapshot, but in practice, for a small file, it's close enough for the
325 	 * current use.
326 	 */
327 	fd = open(path, O_RDONLY | PG_BINARY, 0);
328 	if (fd < 0)
329 		return NULL;
330 	if (fstat(fd, &statbuf) < 0)
331 	{
332 		close(fd);
333 		return NULL;
334 	}
335 	if (statbuf.st_size == 0)
336 	{
337 		/* empty file */
338 		close(fd);
339 		result = (char **) pg_malloc(sizeof(char *));
340 		*result = NULL;
341 		return result;
342 	}
343 	buffer = pg_malloc(statbuf.st_size + 1);
344 
345 	len = read(fd, buffer, statbuf.st_size + 1);
346 	close(fd);
347 	if (len != statbuf.st_size)
348 	{
349 		/* oops, the file size changed between fstat and read */
350 		free(buffer);
351 		return NULL;
352 	}
353 
354 	/*
355 	 * Count newlines. We expect there to be a newline after each full line,
356 	 * including one at the end of file. If there isn't a newline at the end,
357 	 * any characters after the last newline will be ignored.
358 	 */
359 	nlines = 0;
360 	for (i = 0; i < len; i++)
361 	{
362 		if (buffer[i] == '\n')
363 			nlines++;
364 	}
365 
366 	/* set up the result buffer */
367 	result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
368 
369 	/* now split the buffer into lines */
370 	linebegin = buffer;
371 	n = 0;
372 	for (i = 0; i < len; i++)
373 	{
374 		if (buffer[i] == '\n')
375 		{
376 			int			slen = &buffer[i] - linebegin + 1;
377 			char	   *linebuf = pg_malloc(slen + 1);
378 
379 			memcpy(linebuf, linebegin, slen);
380 			linebuf[slen] = '\0';
381 			result[n++] = linebuf;
382 			linebegin = &buffer[i + 1];
383 		}
384 	}
385 	result[n] = NULL;
386 
387 	free(buffer);
388 
389 	return result;
390 }
391 
392 
393 /*
394  * Free memory allocated for optlines through readfile()
395  */
396 static void
free_readfile(char ** optlines)397 free_readfile(char **optlines)
398 {
399 	char	   *curr_line = NULL;
400 	int			i = 0;
401 
402 	if (!optlines)
403 		return;
404 
405 	while ((curr_line = optlines[i++]))
406 		free(curr_line);
407 
408 	free(optlines);
409 
410 	return;
411 }
412 
413 /*
414  * start/test/stop routines
415  */
416 
417 /*
418  * Start the postmaster and return its PID.
419  *
420  * Currently, on Windows what we return is the PID of the shell process
421  * that launched the postmaster (and, we trust, is waiting for it to exit).
422  * So the PID is usable for "is the postmaster still running" checks,
423  * but cannot be compared directly to postmaster.pid.
424  *
425  * On Windows, we also save aside a handle to the shell process in
426  * "postmasterProcess", which the caller should close when done with it.
427  */
428 static pgpid_t
start_postmaster(void)429 start_postmaster(void)
430 {
431 	char	   *cmd;
432 
433 #ifndef WIN32
434 	pgpid_t		pm_pid;
435 
436 	/* Flush stdio channels just before fork, to avoid double-output problems */
437 	fflush(stdout);
438 	fflush(stderr);
439 
440 	pm_pid = fork();
441 	if (pm_pid < 0)
442 	{
443 		/* fork failed */
444 		write_stderr(_("%s: could not start server: %s\n"),
445 					 progname, strerror(errno));
446 		exit(1);
447 	}
448 	if (pm_pid > 0)
449 	{
450 		/* fork succeeded, in parent */
451 		return pm_pid;
452 	}
453 
454 	/* fork succeeded, in child */
455 
456 	/*
457 	 * Since there might be quotes to handle here, it is easier simply to pass
458 	 * everything to a shell to process them.  Use exec so that the postmaster
459 	 * has the same PID as the current child process.
460 	 */
461 	if (log_file != NULL)
462 		cmd = psprintf("exec \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1",
463 					   exec_path, pgdata_opt, post_opts,
464 					   DEVNULL, log_file);
465 	else
466 		cmd = psprintf("exec \"%s\" %s%s < \"%s\" 2>&1",
467 					   exec_path, pgdata_opt, post_opts, DEVNULL);
468 
469 	(void) execl("/bin/sh", "/bin/sh", "-c", cmd, (char *) NULL);
470 
471 	/* exec failed */
472 	write_stderr(_("%s: could not start server: %s\n"),
473 				 progname, strerror(errno));
474 	exit(1);
475 
476 	return 0;					/* keep dumb compilers quiet */
477 
478 #else							/* WIN32 */
479 
480 	/*
481 	 * As with the Unix case, it's easiest to use the shell (CMD.EXE) to
482 	 * handle redirection etc.  Unfortunately CMD.EXE lacks any equivalent of
483 	 * "exec", so we don't get to find out the postmaster's PID immediately.
484 	 */
485 	PROCESS_INFORMATION pi;
486 
487 	if (log_file != NULL)
488 		cmd = psprintf("CMD /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
489 					   exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
490 	else
491 		cmd = psprintf("CMD /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
492 					   exec_path, pgdata_opt, post_opts, DEVNULL);
493 
494 	if (!CreateRestrictedProcess(cmd, &pi, false))
495 	{
496 		write_stderr(_("%s: could not start server: error code %lu\n"),
497 					 progname, (unsigned long) GetLastError());
498 		exit(1);
499 	}
500 	/* Don't close command process handle here; caller must do so */
501 	postmasterProcess = pi.hProcess;
502 	CloseHandle(pi.hThread);
503 	return pi.dwProcessId;		/* Shell's PID, not postmaster's! */
504 #endif   /* WIN32 */
505 }
506 
507 
508 
509 /*
510  * Find the pgport and try a connection
511  *
512  * On Unix, pm_pid is the PID of the just-launched postmaster.  On Windows,
513  * it may be the PID of an ancestor shell process, so we can't check the
514  * contents of postmaster.pid quite as carefully.
515  *
516  * On Windows, the static variable postmasterProcess is an implicit argument
517  * to this routine; it contains a handle to the postmaster process or an
518  * ancestor shell process thereof.
519  *
520  * Note that the checkpoint parameter enables a Windows service control
521  * manager checkpoint, it's got nothing to do with database checkpoints!!
522  */
523 static PGPing
test_postmaster_connection(pgpid_t pm_pid,bool do_checkpoint)524 test_postmaster_connection(pgpid_t pm_pid, bool do_checkpoint)
525 {
526 	PGPing		ret = PQPING_NO_RESPONSE;
527 	char		connstr[MAXPGPATH * 2 + 256];
528 	int			i;
529 
530 	/* if requested wait time is zero, return "still starting up" code */
531 	if (wait_seconds <= 0)
532 		return PQPING_REJECT;
533 
534 	connstr[0] = '\0';
535 
536 	for (i = 0; i < wait_seconds; i++)
537 	{
538 		/* Do we need a connection string? */
539 		if (connstr[0] == '\0')
540 		{
541 			/*----------
542 			 * The number of lines in postmaster.pid tells us several things:
543 			 *
544 			 * # of lines
545 			 *		0	lock file created but status not written
546 			 *		2	pre-9.1 server, shared memory not created
547 			 *		3	pre-9.1 server, shared memory created
548 			 *		5	9.1+ server, ports not opened
549 			 *		6	9.1+ server, shared memory not created
550 			 *		7	9.1+ server, shared memory created
551 			 *
552 			 * This code does not support pre-9.1 servers.  On Unix machines
553 			 * we could consider extracting the port number from the shmem
554 			 * key, but that (a) is not robust, and (b) doesn't help with
555 			 * finding out the socket directory.  And it wouldn't work anyway
556 			 * on Windows.
557 			 *
558 			 * If we see less than 6 lines in postmaster.pid, just keep
559 			 * waiting.
560 			 *----------
561 			 */
562 			char	  **optlines;
563 
564 			/* Try to read the postmaster.pid file */
565 			if ((optlines = readfile(pid_file)) != NULL &&
566 				optlines[0] != NULL &&
567 				optlines[1] != NULL &&
568 				optlines[2] != NULL)
569 			{
570 				if (optlines[3] == NULL)
571 				{
572 					/* File is exactly three lines, must be pre-9.1 */
573 					write_stderr(_("\n%s: -w option is not supported when starting a pre-9.1 server\n"),
574 								 progname);
575 					return PQPING_NO_ATTEMPT;
576 				}
577 				else if (optlines[4] != NULL &&
578 						 optlines[5] != NULL)
579 				{
580 					/* File is complete enough for us, parse it */
581 					pgpid_t		pmpid;
582 					time_t		pmstart;
583 
584 					/*
585 					 * Make sanity checks.  If it's for the wrong PID, or the
586 					 * recorded start time is before pg_ctl started, then
587 					 * either we are looking at the wrong data directory, or
588 					 * this is a pre-existing pidfile that hasn't (yet?) been
589 					 * overwritten by our child postmaster.  Allow 2 seconds
590 					 * slop for possible cross-process clock skew.
591 					 */
592 					pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
593 					pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
594 					if (pmstart >= start_time - 2 &&
595 #ifndef WIN32
596 						pmpid == pm_pid
597 #else
598 					/* Windows can only reject standalone-backend PIDs */
599 						pmpid > 0
600 #endif
601 						)
602 					{
603 						/*
604 						 * OK, seems to be a valid pidfile from our child.
605 						 */
606 						int			portnum;
607 						char	   *sockdir;
608 						char	   *hostaddr;
609 						char		host_str[MAXPGPATH];
610 
611 						/*
612 						 * Extract port number and host string to use. Prefer
613 						 * using Unix socket if available.
614 						 */
615 						portnum = atoi(optlines[LOCK_FILE_LINE_PORT - 1]);
616 						sockdir = optlines[LOCK_FILE_LINE_SOCKET_DIR - 1];
617 						hostaddr = optlines[LOCK_FILE_LINE_LISTEN_ADDR - 1];
618 
619 						/*
620 						 * While unix_socket_directories can accept relative
621 						 * directories, libpq's host parameter must have a
622 						 * leading slash to indicate a socket directory.  So,
623 						 * ignore sockdir if it's relative, and try to use TCP
624 						 * instead.
625 						 */
626 						if (sockdir[0] == '/')
627 							strlcpy(host_str, sockdir, sizeof(host_str));
628 						else
629 							strlcpy(host_str, hostaddr, sizeof(host_str));
630 
631 						/* remove trailing newline */
632 						if (strchr(host_str, '\n') != NULL)
633 							*strchr(host_str, '\n') = '\0';
634 
635 						/* Fail if couldn't get either sockdir or host addr */
636 						if (host_str[0] == '\0')
637 						{
638 							write_stderr(_("\n%s: -w option cannot use a relative socket directory specification\n"),
639 										 progname);
640 							return PQPING_NO_ATTEMPT;
641 						}
642 
643 						/*
644 						 * Map listen-only addresses to counterparts usable
645 						 * for establishing a connection.  connect() to "::"
646 						 * or "0.0.0.0" is not portable to OpenBSD 5.0 or to
647 						 * Windows Server 2008, and connect() to "::" is
648 						 * additionally not portable to NetBSD 6.0.  (Cygwin
649 						 * does handle both addresses, though.)
650 						 */
651 						if (strcmp(host_str, "*") == 0)
652 							strcpy(host_str, "localhost");
653 						else if (strcmp(host_str, "0.0.0.0") == 0)
654 							strcpy(host_str, "127.0.0.1");
655 						else if (strcmp(host_str, "::") == 0)
656 							strcpy(host_str, "::1");
657 
658 						/*
659 						 * We need to set connect_timeout otherwise on Windows
660 						 * the Service Control Manager (SCM) will probably
661 						 * timeout first.
662 						 */
663 						snprintf(connstr, sizeof(connstr),
664 						"dbname=postgres port=%d host='%s' connect_timeout=5",
665 								 portnum, host_str);
666 					}
667 				}
668 			}
669 
670 			/*
671 			 * Free the results of readfile.
672 			 *
673 			 * This is safe to call even if optlines is NULL.
674 			 */
675 			free_readfile(optlines);
676 		}
677 
678 		/* If we have a connection string, ping the server */
679 		if (connstr[0] != '\0')
680 		{
681 			ret = PQping(connstr);
682 			if (ret == PQPING_OK || ret == PQPING_NO_ATTEMPT)
683 				break;
684 		}
685 
686 		/*
687 		 * Check whether the child postmaster process is still alive.  This
688 		 * lets us exit early if the postmaster fails during startup.
689 		 *
690 		 * On Windows, we may be checking the postmaster's parent shell, but
691 		 * that's fine for this purpose.
692 		 */
693 #ifndef WIN32
694 		{
695 			int			exitstatus;
696 
697 			if (waitpid((pid_t) pm_pid, &exitstatus, WNOHANG) == (pid_t) pm_pid)
698 				return PQPING_NO_RESPONSE;
699 		}
700 #else
701 		if (WaitForSingleObject(postmasterProcess, 0) == WAIT_OBJECT_0)
702 			return PQPING_NO_RESPONSE;
703 #endif
704 
705 		/* No response, or startup still in process; wait */
706 #ifdef WIN32
707 		if (do_checkpoint)
708 		{
709 			/*
710 			 * Increment the wait hint by 6 secs (connection timeout + sleep)
711 			 * We must do this to indicate to the SCM that our startup time is
712 			 * changing, otherwise it'll usually send a stop signal after 20
713 			 * seconds, despite incrementing the checkpoint counter.
714 			 */
715 			status.dwWaitHint += 6000;
716 			status.dwCheckPoint++;
717 			SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
718 		}
719 		else
720 #endif
721 			print_msg(".");
722 
723 		pg_usleep(1000000);		/* 1 sec */
724 	}
725 
726 	/* return result of last call to PQping */
727 	return ret;
728 }
729 
730 
731 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
732 static void
unlimit_core_size(void)733 unlimit_core_size(void)
734 {
735 	struct rlimit lim;
736 
737 	getrlimit(RLIMIT_CORE, &lim);
738 	if (lim.rlim_max == 0)
739 	{
740 		write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
741 					 progname);
742 		return;
743 	}
744 	else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
745 	{
746 		lim.rlim_cur = lim.rlim_max;
747 		setrlimit(RLIMIT_CORE, &lim);
748 	}
749 }
750 #endif
751 
752 static void
read_post_opts(void)753 read_post_opts(void)
754 {
755 	if (post_opts == NULL)
756 	{
757 		post_opts = "";			/* default */
758 		if (ctl_command == RESTART_COMMAND)
759 		{
760 			char	  **optlines;
761 
762 			optlines = readfile(postopts_file);
763 			if (optlines == NULL)
764 			{
765 				write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
766 				exit(1);
767 			}
768 			else if (optlines[0] == NULL || optlines[1] != NULL)
769 			{
770 				write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
771 							 progname, postopts_file);
772 				exit(1);
773 			}
774 			else
775 			{
776 				int			len;
777 				char	   *optline;
778 				char	   *arg1;
779 
780 				optline = optlines[0];
781 				/* trim off line endings */
782 				len = strcspn(optline, "\r\n");
783 				optline[len] = '\0';
784 
785 				/*
786 				 * Are we at the first option, as defined by space and
787 				 * double-quote?
788 				 */
789 				if ((arg1 = strstr(optline, " \"")) != NULL)
790 				{
791 					*arg1 = '\0';		/* terminate so we get only program
792 										 * name */
793 					post_opts = pg_strdup(arg1 + 1);	/* point past whitespace */
794 				}
795 				if (exec_path == NULL)
796 					exec_path = pg_strdup(optline);
797 			}
798 
799 			/* Free the results of readfile. */
800 			free_readfile(optlines);
801 		}
802 	}
803 }
804 
805 static char *
find_other_exec_or_die(const char * argv0,const char * target,const char * versionstr)806 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
807 {
808 	int			ret;
809 	char	   *found_path;
810 
811 	found_path = pg_malloc(MAXPGPATH);
812 
813 	if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
814 	{
815 		char		full_path[MAXPGPATH];
816 
817 		if (find_my_exec(argv0, full_path) < 0)
818 			strlcpy(full_path, progname, sizeof(full_path));
819 
820 		if (ret == -1)
821 			write_stderr(_("The program \"%s\" is needed by %s "
822 						   "but was not found in the\n"
823 						   "same directory as \"%s\".\n"
824 						   "Check your installation.\n"),
825 						 target, progname, full_path);
826 		else
827 			write_stderr(_("The program \"%s\" was found by \"%s\"\n"
828 						   "but was not the same version as %s.\n"
829 						   "Check your installation.\n"),
830 						 target, full_path, progname);
831 		exit(1);
832 	}
833 
834 	return found_path;
835 }
836 
837 static void
do_init(void)838 do_init(void)
839 {
840 	char	   *cmd;
841 
842 	if (exec_path == NULL)
843 		exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
844 
845 	if (pgdata_opt == NULL)
846 		pgdata_opt = "";
847 
848 	if (post_opts == NULL)
849 		post_opts = "";
850 
851 	if (!silent_mode)
852 		cmd = psprintf("\"%s\" %s%s",
853 					   exec_path, pgdata_opt, post_opts);
854 	else
855 		cmd = psprintf("\"%s\" %s%s > \"%s\"",
856 					   exec_path, pgdata_opt, post_opts, DEVNULL);
857 
858 	if (system(cmd) != 0)
859 	{
860 		write_stderr(_("%s: database system initialization failed\n"), progname);
861 		exit(1);
862 	}
863 }
864 
865 static void
do_start(void)866 do_start(void)
867 {
868 	pgpid_t		old_pid = 0;
869 	pgpid_t		pm_pid;
870 
871 	if (ctl_command != RESTART_COMMAND)
872 	{
873 		old_pid = get_pgpid(false);
874 		if (old_pid != 0)
875 			write_stderr(_("%s: another server might be running; "
876 						   "trying to start server anyway\n"),
877 						 progname);
878 	}
879 
880 	read_post_opts();
881 
882 	/* No -D or -D already added during server start */
883 	if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
884 		pgdata_opt = "";
885 
886 	if (exec_path == NULL)
887 		exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
888 
889 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
890 	if (allow_core_files)
891 		unlimit_core_size();
892 #endif
893 
894 	/*
895 	 * If possible, tell the postmaster our parent shell's PID (see the
896 	 * comments in CreateLockFile() for motivation).  Windows hasn't got
897 	 * getppid() unfortunately.
898 	 */
899 #ifndef WIN32
900 	{
901 		static char env_var[32];
902 
903 		snprintf(env_var, sizeof(env_var), "PG_GRANDPARENT_PID=%d",
904 				 (int) getppid());
905 		putenv(env_var);
906 	}
907 #endif
908 
909 	pm_pid = start_postmaster();
910 
911 	if (do_wait)
912 	{
913 		print_msg(_("waiting for server to start..."));
914 
915 		switch (test_postmaster_connection(pm_pid, false))
916 		{
917 			case PQPING_OK:
918 				print_msg(_(" done\n"));
919 				print_msg(_("server started\n"));
920 				break;
921 			case PQPING_REJECT:
922 				print_msg(_(" stopped waiting\n"));
923 				print_msg(_("server is still starting up\n"));
924 				break;
925 			case PQPING_NO_RESPONSE:
926 				print_msg(_(" stopped waiting\n"));
927 				write_stderr(_("%s: could not start server\n"
928 							   "Examine the log output.\n"),
929 							 progname);
930 				exit(1);
931 				break;
932 			case PQPING_NO_ATTEMPT:
933 				print_msg(_(" failed\n"));
934 				write_stderr(_("%s: could not wait for server because of misconfiguration\n"),
935 							 progname);
936 				exit(1);
937 		}
938 	}
939 	else
940 		print_msg(_("server starting\n"));
941 
942 #ifdef WIN32
943 	/* Now we don't need the handle to the shell process anymore */
944 	CloseHandle(postmasterProcess);
945 	postmasterProcess = INVALID_HANDLE_VALUE;
946 #endif
947 }
948 
949 
950 static void
do_stop(void)951 do_stop(void)
952 {
953 	int			cnt;
954 	pgpid_t		pid;
955 	struct stat statbuf;
956 
957 	pid = get_pgpid(false);
958 
959 	if (pid == 0)				/* no pid file */
960 	{
961 		write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
962 		write_stderr(_("Is server running?\n"));
963 		exit(1);
964 	}
965 	else if (pid < 0)			/* standalone backend, not postmaster */
966 	{
967 		pid = -pid;
968 		write_stderr(_("%s: cannot stop server; "
969 					   "single-user server is running (PID: %ld)\n"),
970 					 progname, pid);
971 		exit(1);
972 	}
973 
974 	if (kill((pid_t) pid, sig) != 0)
975 	{
976 		write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
977 					 strerror(errno));
978 		exit(1);
979 	}
980 
981 	if (!do_wait)
982 	{
983 		print_msg(_("server shutting down\n"));
984 		return;
985 	}
986 	else
987 	{
988 		/*
989 		 * If backup_label exists, an online backup is running. Warn the user
990 		 * that smart shutdown will wait for it to finish. However, if
991 		 * recovery.conf is also present, we're recovering from an online
992 		 * backup instead of performing one.
993 		 */
994 		if (shutdown_mode == SMART_MODE &&
995 			stat(backup_file, &statbuf) == 0 &&
996 			stat(recovery_file, &statbuf) != 0)
997 		{
998 			print_msg(_("WARNING: online backup mode is active\n"
999 						"Shutdown will not complete until pg_stop_backup() is called.\n\n"));
1000 		}
1001 
1002 		print_msg(_("waiting for server to shut down..."));
1003 
1004 		for (cnt = 0; cnt < wait_seconds; cnt++)
1005 		{
1006 			if ((pid = get_pgpid(false)) != 0)
1007 			{
1008 				print_msg(".");
1009 				pg_usleep(1000000);		/* 1 sec */
1010 			}
1011 			else
1012 				break;
1013 		}
1014 
1015 		if (pid != 0)			/* pid file still exists */
1016 		{
1017 			print_msg(_(" failed\n"));
1018 
1019 			write_stderr(_("%s: server does not shut down\n"), progname);
1020 			if (shutdown_mode == SMART_MODE)
1021 				write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1022 						  "waiting for session-initiated disconnection.\n"));
1023 			exit(1);
1024 		}
1025 		print_msg(_(" done\n"));
1026 
1027 		print_msg(_("server stopped\n"));
1028 	}
1029 }
1030 
1031 
1032 /*
1033  *	restart/reload routines
1034  */
1035 
1036 static void
do_restart(void)1037 do_restart(void)
1038 {
1039 	int			cnt;
1040 	pgpid_t		pid;
1041 	struct stat statbuf;
1042 
1043 	pid = get_pgpid(false);
1044 
1045 	if (pid == 0)				/* no pid file */
1046 	{
1047 		write_stderr(_("%s: PID file \"%s\" does not exist\n"),
1048 					 progname, pid_file);
1049 		write_stderr(_("Is server running?\n"));
1050 		write_stderr(_("starting server anyway\n"));
1051 		do_start();
1052 		return;
1053 	}
1054 	else if (pid < 0)			/* standalone backend, not postmaster */
1055 	{
1056 		pid = -pid;
1057 		if (postmaster_is_alive((pid_t) pid))
1058 		{
1059 			write_stderr(_("%s: cannot restart server; "
1060 						   "single-user server is running (PID: %ld)\n"),
1061 						 progname, pid);
1062 			write_stderr(_("Please terminate the single-user server and try again.\n"));
1063 			exit(1);
1064 		}
1065 	}
1066 
1067 	if (postmaster_is_alive((pid_t) pid))
1068 	{
1069 		if (kill((pid_t) pid, sig) != 0)
1070 		{
1071 			write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
1072 						 strerror(errno));
1073 			exit(1);
1074 		}
1075 
1076 		/*
1077 		 * If backup_label exists, an online backup is running. Warn the user
1078 		 * that smart shutdown will wait for it to finish. However, if
1079 		 * recovery.conf is also present, we're recovering from an online
1080 		 * backup instead of performing one.
1081 		 */
1082 		if (shutdown_mode == SMART_MODE &&
1083 			stat(backup_file, &statbuf) == 0 &&
1084 			stat(recovery_file, &statbuf) != 0)
1085 		{
1086 			print_msg(_("WARNING: online backup mode is active\n"
1087 						"Shutdown will not complete until pg_stop_backup() is called.\n\n"));
1088 		}
1089 
1090 		print_msg(_("waiting for server to shut down..."));
1091 
1092 		/* always wait for restart */
1093 
1094 		for (cnt = 0; cnt < wait_seconds; cnt++)
1095 		{
1096 			if ((pid = get_pgpid(false)) != 0)
1097 			{
1098 				print_msg(".");
1099 				pg_usleep(1000000);		/* 1 sec */
1100 			}
1101 			else
1102 				break;
1103 		}
1104 
1105 		if (pid != 0)			/* pid file still exists */
1106 		{
1107 			print_msg(_(" failed\n"));
1108 
1109 			write_stderr(_("%s: server does not shut down\n"), progname);
1110 			if (shutdown_mode == SMART_MODE)
1111 				write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1112 						  "waiting for session-initiated disconnection.\n"));
1113 			exit(1);
1114 		}
1115 
1116 		print_msg(_(" done\n"));
1117 		print_msg(_("server stopped\n"));
1118 	}
1119 	else
1120 	{
1121 		write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1122 					 progname, pid);
1123 		write_stderr(_("starting server anyway\n"));
1124 	}
1125 
1126 	do_start();
1127 }
1128 
1129 static void
do_reload(void)1130 do_reload(void)
1131 {
1132 	pgpid_t		pid;
1133 
1134 	pid = get_pgpid(false);
1135 	if (pid == 0)				/* no pid file */
1136 	{
1137 		write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1138 		write_stderr(_("Is server running?\n"));
1139 		exit(1);
1140 	}
1141 	else if (pid < 0)			/* standalone backend, not postmaster */
1142 	{
1143 		pid = -pid;
1144 		write_stderr(_("%s: cannot reload server; "
1145 					   "single-user server is running (PID: %ld)\n"),
1146 					 progname, pid);
1147 		write_stderr(_("Please terminate the single-user server and try again.\n"));
1148 		exit(1);
1149 	}
1150 
1151 	if (kill((pid_t) pid, sig) != 0)
1152 	{
1153 		write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1154 					 progname, pid, strerror(errno));
1155 		exit(1);
1156 	}
1157 
1158 	print_msg(_("server signaled\n"));
1159 }
1160 
1161 
1162 /*
1163  * promote
1164  */
1165 
1166 static void
do_promote(void)1167 do_promote(void)
1168 {
1169 	FILE	   *prmfile;
1170 	pgpid_t		pid;
1171 	struct stat statbuf;
1172 
1173 	pid = get_pgpid(false);
1174 
1175 	if (pid == 0)				/* no pid file */
1176 	{
1177 		write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1178 		write_stderr(_("Is server running?\n"));
1179 		exit(1);
1180 	}
1181 	else if (pid < 0)			/* standalone backend, not postmaster */
1182 	{
1183 		pid = -pid;
1184 		write_stderr(_("%s: cannot promote server; "
1185 					   "single-user server is running (PID: %ld)\n"),
1186 					 progname, pid);
1187 		exit(1);
1188 	}
1189 
1190 	/* If recovery.conf doesn't exist, the server is not in standby mode */
1191 	if (stat(recovery_file, &statbuf) != 0)
1192 	{
1193 		write_stderr(_("%s: cannot promote server; "
1194 					   "server is not in standby mode\n"),
1195 					 progname);
1196 		exit(1);
1197 	}
1198 
1199 	/*
1200 	 * For 9.3 onwards, "fast" promotion is performed. Promotion with a full
1201 	 * checkpoint is still possible by writing a file called
1202 	 * "fallback_promote" instead of "promote"
1203 	 */
1204 	snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
1205 
1206 	if ((prmfile = fopen(promote_file, "w")) == NULL)
1207 	{
1208 		write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1209 					 progname, promote_file, strerror(errno));
1210 		exit(1);
1211 	}
1212 	if (fclose(prmfile))
1213 	{
1214 		write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1215 					 progname, promote_file, strerror(errno));
1216 		exit(1);
1217 	}
1218 
1219 	sig = SIGUSR1;
1220 	if (kill((pid_t) pid, sig) != 0)
1221 	{
1222 		write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1223 					 progname, pid, strerror(errno));
1224 		if (unlink(promote_file) != 0)
1225 			write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1226 						 progname, promote_file, strerror(errno));
1227 		exit(1);
1228 	}
1229 
1230 	print_msg(_("server promoting\n"));
1231 }
1232 
1233 
1234 /*
1235  *	utility routines
1236  */
1237 
1238 static bool
postmaster_is_alive(pid_t pid)1239 postmaster_is_alive(pid_t pid)
1240 {
1241 	/*
1242 	 * Test to see if the process is still there.  Note that we do not
1243 	 * consider an EPERM failure to mean that the process is still there;
1244 	 * EPERM must mean that the given PID belongs to some other userid, and
1245 	 * considering the permissions on $PGDATA, that means it's not the
1246 	 * postmaster we are after.
1247 	 *
1248 	 * Don't believe that our own PID or parent shell's PID is the postmaster,
1249 	 * either.  (Windows hasn't got getppid(), though.)
1250 	 */
1251 	if (pid == getpid())
1252 		return false;
1253 #ifndef WIN32
1254 	if (pid == getppid())
1255 		return false;
1256 #endif
1257 	if (kill(pid, 0) == 0)
1258 		return true;
1259 	return false;
1260 }
1261 
1262 static void
do_status(void)1263 do_status(void)
1264 {
1265 	pgpid_t		pid;
1266 
1267 	pid = get_pgpid(true);
1268 	/* Is there a pid file? */
1269 	if (pid != 0)
1270 	{
1271 		/* standalone backend? */
1272 		if (pid < 0)
1273 		{
1274 			pid = -pid;
1275 			if (postmaster_is_alive((pid_t) pid))
1276 			{
1277 				printf(_("%s: single-user server is running (PID: %ld)\n"),
1278 					   progname, pid);
1279 				return;
1280 			}
1281 		}
1282 		else
1283 			/* must be a postmaster */
1284 		{
1285 			if (postmaster_is_alive((pid_t) pid))
1286 			{
1287 				char	  **optlines;
1288 				char	  **curr_line;
1289 
1290 				printf(_("%s: server is running (PID: %ld)\n"),
1291 					   progname, pid);
1292 
1293 				optlines = readfile(postopts_file);
1294 				if (optlines != NULL)
1295 				{
1296 					for (curr_line = optlines; *curr_line != NULL; curr_line++)
1297 						fputs(*curr_line, stdout);
1298 
1299 					/* Free the results of readfile */
1300 					free_readfile(optlines);
1301 				}
1302 				return;
1303 			}
1304 		}
1305 	}
1306 	printf(_("%s: no server running\n"), progname);
1307 
1308 	/*
1309 	 * The Linux Standard Base Core Specification 3.1 says this should return
1310 	 * '3, program is not running'
1311 	 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-gener
1312 	 * ic/iniscrptact.html
1313 	 */
1314 	exit(3);
1315 }
1316 
1317 
1318 
1319 static void
do_kill(pgpid_t pid)1320 do_kill(pgpid_t pid)
1321 {
1322 	if (kill((pid_t) pid, sig) != 0)
1323 	{
1324 		write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1325 					 progname, sig, pid, strerror(errno));
1326 		exit(1);
1327 	}
1328 }
1329 
1330 #ifdef WIN32
1331 
1332 #if (_MSC_VER < 1800)
1333 static bool
IsWindowsXPOrGreater(void)1334 IsWindowsXPOrGreater(void)
1335 {
1336 	OSVERSIONINFO osv;
1337 
1338 	osv.dwOSVersionInfoSize = sizeof(osv);
1339 
1340 	/* Windows XP = Version 5.1 */
1341 	return (!GetVersionEx(&osv) ||		/* could not get version */
1342 			osv.dwMajorVersion > 5 || (osv.dwMajorVersion == 5 && osv.dwMinorVersion >= 1));
1343 }
1344 
1345 static bool
IsWindows7OrGreater(void)1346 IsWindows7OrGreater(void)
1347 {
1348 	OSVERSIONINFO osv;
1349 
1350 	osv.dwOSVersionInfoSize = sizeof(osv);
1351 
1352 	/* Windows 7 = Version 6.0 */
1353 	return (!GetVersionEx(&osv) ||		/* could not get version */
1354 			osv.dwMajorVersion > 6 || (osv.dwMajorVersion == 6 && osv.dwMinorVersion >= 0));
1355 }
1356 #endif
1357 
1358 static bool
pgwin32_IsInstalled(SC_HANDLE hSCM)1359 pgwin32_IsInstalled(SC_HANDLE hSCM)
1360 {
1361 	SC_HANDLE	hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1362 	bool		bResult = (hService != NULL);
1363 
1364 	if (bResult)
1365 		CloseServiceHandle(hService);
1366 	return bResult;
1367 }
1368 
1369 static char *
pgwin32_CommandLine(bool registration)1370 pgwin32_CommandLine(bool registration)
1371 {
1372 	PQExpBuffer cmdLine = createPQExpBuffer();
1373 	char		cmdPath[MAXPGPATH];
1374 	int			ret;
1375 
1376 	if (registration)
1377 	{
1378 		ret = find_my_exec(argv0, cmdPath);
1379 		if (ret != 0)
1380 		{
1381 			write_stderr(_("%s: could not find own program executable\n"), progname);
1382 			exit(1);
1383 		}
1384 	}
1385 	else
1386 	{
1387 		ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1388 							  cmdPath);
1389 		if (ret != 0)
1390 		{
1391 			write_stderr(_("%s: could not find postgres program executable\n"), progname);
1392 			exit(1);
1393 		}
1394 	}
1395 
1396 	/* if path does not end in .exe, append it */
1397 	if (strlen(cmdPath) < 4 ||
1398 		pg_strcasecmp(cmdPath + strlen(cmdPath) - 4, ".exe") != 0)
1399 		snprintf(cmdPath + strlen(cmdPath), sizeof(cmdPath) - strlen(cmdPath),
1400 				 ".exe");
1401 
1402 	/* use backslashes in path to avoid problems with some third-party tools */
1403 	make_native_path(cmdPath);
1404 
1405 	/* be sure to double-quote the executable's name in the command */
1406 	appendPQExpBuffer(cmdLine, "\"%s\"", cmdPath);
1407 
1408 	/* append assorted switches to the command line, as needed */
1409 
1410 	if (registration)
1411 		appendPQExpBuffer(cmdLine, " runservice -N \"%s\"",
1412 						  register_servicename);
1413 
1414 	if (pg_config)
1415 	{
1416 		/* We need the -D path to be absolute */
1417 		char	   *dataDir;
1418 
1419 		if ((dataDir = make_absolute_path(pg_config)) == NULL)
1420 		{
1421 			/* make_absolute_path already reported the error */
1422 			exit(1);
1423 		}
1424 		make_native_path(dataDir);
1425 		appendPQExpBuffer(cmdLine, " -D \"%s\"", dataDir);
1426 		free(dataDir);
1427 	}
1428 
1429 	if (registration && event_source != NULL)
1430 		appendPQExpBuffer(cmdLine, " -e \"%s\"", event_source);
1431 
1432 	if (registration && do_wait)
1433 		appendPQExpBuffer(cmdLine, " -w");
1434 
1435 	/* Don't propagate a value from an environment variable. */
1436 	if (registration && wait_seconds_arg && wait_seconds != DEFAULT_WAIT)
1437 		appendPQExpBuffer(cmdLine, " -t %d", wait_seconds);
1438 
1439 	if (registration && silent_mode)
1440 		appendPQExpBuffer(cmdLine, " -s");
1441 
1442 	if (post_opts)
1443 	{
1444 		if (registration)
1445 			appendPQExpBuffer(cmdLine, " -o \"%s\"", post_opts);
1446 		else
1447 			appendPQExpBuffer(cmdLine, " %s", post_opts);
1448 	}
1449 
1450 	return cmdLine->data;
1451 }
1452 
1453 static void
pgwin32_doRegister(void)1454 pgwin32_doRegister(void)
1455 {
1456 	SC_HANDLE	hService;
1457 	SC_HANDLE	hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1458 
1459 	if (hSCM == NULL)
1460 	{
1461 		write_stderr(_("%s: could not open service manager\n"), progname);
1462 		exit(1);
1463 	}
1464 	if (pgwin32_IsInstalled(hSCM))
1465 	{
1466 		CloseServiceHandle(hSCM);
1467 		write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1468 		exit(1);
1469 	}
1470 
1471 	if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1472 							   SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1473 								  pgctl_start_type, SERVICE_ERROR_NORMAL,
1474 								  pgwin32_CommandLine(true),
1475 	   NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1476 	{
1477 		CloseServiceHandle(hSCM);
1478 		write_stderr(_("%s: could not register service \"%s\": error code %lu\n"),
1479 					 progname, register_servicename,
1480 					 (unsigned long) GetLastError());
1481 		exit(1);
1482 	}
1483 	CloseServiceHandle(hService);
1484 	CloseServiceHandle(hSCM);
1485 }
1486 
1487 static void
pgwin32_doUnregister(void)1488 pgwin32_doUnregister(void)
1489 {
1490 	SC_HANDLE	hService;
1491 	SC_HANDLE	hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1492 
1493 	if (hSCM == NULL)
1494 	{
1495 		write_stderr(_("%s: could not open service manager\n"), progname);
1496 		exit(1);
1497 	}
1498 	if (!pgwin32_IsInstalled(hSCM))
1499 	{
1500 		CloseServiceHandle(hSCM);
1501 		write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1502 		exit(1);
1503 	}
1504 
1505 	if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1506 	{
1507 		CloseServiceHandle(hSCM);
1508 		write_stderr(_("%s: could not open service \"%s\": error code %lu\n"),
1509 					 progname, register_servicename,
1510 					 (unsigned long) GetLastError());
1511 		exit(1);
1512 	}
1513 	if (!DeleteService(hService))
1514 	{
1515 		CloseServiceHandle(hService);
1516 		CloseServiceHandle(hSCM);
1517 		write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"),
1518 					 progname, register_servicename,
1519 					 (unsigned long) GetLastError());
1520 		exit(1);
1521 	}
1522 	CloseServiceHandle(hService);
1523 	CloseServiceHandle(hSCM);
1524 }
1525 
1526 static void
pgwin32_SetServiceStatus(DWORD currentState)1527 pgwin32_SetServiceStatus(DWORD currentState)
1528 {
1529 	status.dwCurrentState = currentState;
1530 	SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1531 }
1532 
1533 static void WINAPI
pgwin32_ServiceHandler(DWORD request)1534 pgwin32_ServiceHandler(DWORD request)
1535 {
1536 	switch (request)
1537 	{
1538 		case SERVICE_CONTROL_STOP:
1539 		case SERVICE_CONTROL_SHUTDOWN:
1540 
1541 			/*
1542 			 * We only need a short wait hint here as it just needs to wait
1543 			 * for the next checkpoint. They occur every 5 seconds during
1544 			 * shutdown
1545 			 */
1546 			status.dwWaitHint = 10000;
1547 			pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1548 			SetEvent(shutdownEvent);
1549 			return;
1550 
1551 		case SERVICE_CONTROL_PAUSE:
1552 			/* Win32 config reloading */
1553 			status.dwWaitHint = 5000;
1554 			kill(postmasterPID, SIGHUP);
1555 			return;
1556 
1557 			/* FIXME: These could be used to replace other signals etc */
1558 		case SERVICE_CONTROL_CONTINUE:
1559 		case SERVICE_CONTROL_INTERROGATE:
1560 		default:
1561 			break;
1562 	}
1563 }
1564 
1565 static void WINAPI
pgwin32_ServiceMain(DWORD argc,LPTSTR * argv)1566 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1567 {
1568 	PROCESS_INFORMATION pi;
1569 	DWORD		ret;
1570 
1571 	/* Initialize variables */
1572 	status.dwWin32ExitCode = S_OK;
1573 	status.dwCheckPoint = 0;
1574 	status.dwWaitHint = 60000;
1575 	status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1576 	status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1577 	status.dwServiceSpecificExitCode = 0;
1578 	status.dwCurrentState = SERVICE_START_PENDING;
1579 
1580 	memset(&pi, 0, sizeof(pi));
1581 
1582 	read_post_opts();
1583 
1584 	/* Register the control request handler */
1585 	if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1586 		return;
1587 
1588 	if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1589 		return;
1590 
1591 	/* Start the postmaster */
1592 	pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1593 	if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1594 	{
1595 		pgwin32_SetServiceStatus(SERVICE_STOPPED);
1596 		return;
1597 	}
1598 	postmasterPID = pi.dwProcessId;
1599 	postmasterProcess = pi.hProcess;
1600 	CloseHandle(pi.hThread);
1601 
1602 	if (do_wait)
1603 	{
1604 		write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1605 		if (test_postmaster_connection(postmasterPID, true) != PQPING_OK)
1606 		{
1607 			write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1608 			pgwin32_SetServiceStatus(SERVICE_STOPPED);
1609 			return;
1610 		}
1611 		write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1612 	}
1613 
1614 	pgwin32_SetServiceStatus(SERVICE_RUNNING);
1615 
1616 	/* Wait for quit... */
1617 	ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1618 
1619 	pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1620 	switch (ret)
1621 	{
1622 		case WAIT_OBJECT_0:		/* shutdown event */
1623 			{
1624 				/*
1625 				 * status.dwCheckPoint can be incremented by
1626 				 * test_postmaster_connection(), so it might not start from 0.
1627 				 */
1628 				int			maxShutdownCheckPoint = status.dwCheckPoint + 12;
1629 
1630 				kill(postmasterPID, SIGINT);
1631 
1632 				/*
1633 				 * Increment the checkpoint and try again. Abort after 12
1634 				 * checkpoints as the postmaster has probably hung.
1635 				 */
1636 				while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < maxShutdownCheckPoint)
1637 				{
1638 					status.dwCheckPoint++;
1639 					SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1640 				}
1641 				break;
1642 			}
1643 
1644 		case (WAIT_OBJECT_0 + 1):		/* postmaster went down */
1645 			break;
1646 
1647 		default:
1648 			/* shouldn't get here? */
1649 			break;
1650 	}
1651 
1652 	CloseHandle(shutdownEvent);
1653 	CloseHandle(postmasterProcess);
1654 
1655 	pgwin32_SetServiceStatus(SERVICE_STOPPED);
1656 }
1657 
1658 static void
pgwin32_doRunAsService(void)1659 pgwin32_doRunAsService(void)
1660 {
1661 	SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1662 	{NULL, NULL}};
1663 
1664 	if (StartServiceCtrlDispatcher(st) == 0)
1665 	{
1666 		write_stderr(_("%s: could not start service \"%s\": error code %lu\n"),
1667 					 progname, register_servicename,
1668 					 (unsigned long) GetLastError());
1669 		exit(1);
1670 	}
1671 }
1672 
1673 
1674 /*
1675  * Mingw headers are incomplete, and so are the libraries. So we have to load
1676  * a whole lot of API functions dynamically. Since we have to do this anyway,
1677  * also load the couple of functions that *do* exist in minwg headers but not
1678  * on NT4. That way, we don't break on NT4.
1679  */
1680 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1681 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1682 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1683 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1684 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1685 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1686 
1687 /* Windows API define missing from some versions of MingW headers */
1688 #ifndef  DISABLE_MAX_PRIVILEGE
1689 #define DISABLE_MAX_PRIVILEGE	0x1
1690 #endif
1691 
1692 /*
1693  * Create a restricted token, a job object sandbox, and execute the specified
1694  * process with it.
1695  *
1696  * Returns 0 on success, non-zero on failure, same as CreateProcess().
1697  *
1698  * On NT4, or any other system not containing the required functions, will
1699  * launch the process under the current token without doing any modifications.
1700  *
1701  * NOTE! Job object will only work when running as a service, because it's
1702  * automatically destroyed when pg_ctl exits.
1703  */
1704 static int
CreateRestrictedProcess(char * cmd,PROCESS_INFORMATION * processInfo,bool as_service)1705 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1706 {
1707 	int			r;
1708 	BOOL		b;
1709 	STARTUPINFO si;
1710 	HANDLE		origToken;
1711 	HANDLE		restrictedToken;
1712 	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1713 	SID_AND_ATTRIBUTES dropSids[2];
1714 
1715 	/* Functions loaded dynamically */
1716 	__CreateRestrictedToken _CreateRestrictedToken = NULL;
1717 	__IsProcessInJob _IsProcessInJob = NULL;
1718 	__CreateJobObject _CreateJobObject = NULL;
1719 	__SetInformationJobObject _SetInformationJobObject = NULL;
1720 	__AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1721 	__QueryInformationJobObject _QueryInformationJobObject = NULL;
1722 	HANDLE		Kernel32Handle;
1723 	HANDLE		Advapi32Handle;
1724 
1725 	ZeroMemory(&si, sizeof(si));
1726 	si.cb = sizeof(si);
1727 
1728 	Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1729 	if (Advapi32Handle != NULL)
1730 	{
1731 		_CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1732 	}
1733 
1734 	if (_CreateRestrictedToken == NULL)
1735 	{
1736 		/*
1737 		 * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1738 		 * CreateProcess
1739 		 */
1740 		write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
1741 		if (Advapi32Handle != NULL)
1742 			FreeLibrary(Advapi32Handle);
1743 		return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1744 	}
1745 
1746 	/* Open the current token to use as a base for the restricted one */
1747 	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1748 	{
1749 		/*
1750 		 * Most Windows targets make DWORD a 32-bit unsigned long, but in case
1751 		 * it doesn't cast DWORD before printing.
1752 		 */
1753 		write_stderr(_("%s: could not open process token: error code %lu\n"),
1754 					 progname, (unsigned long) GetLastError());
1755 		return 0;
1756 	}
1757 
1758 	/* Allocate list of SIDs to remove */
1759 	ZeroMemory(&dropSids, sizeof(dropSids));
1760 	if (!AllocateAndInitializeSid(&NtAuthority, 2,
1761 		 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1762 								  0, &dropSids[0].Sid) ||
1763 		!AllocateAndInitializeSid(&NtAuthority, 2,
1764 	SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1765 								  0, &dropSids[1].Sid))
1766 	{
1767 		write_stderr(_("%s: could not allocate SIDs: error code %lu\n"),
1768 					 progname, (unsigned long) GetLastError());
1769 		return 0;
1770 	}
1771 
1772 	b = _CreateRestrictedToken(origToken,
1773 							   DISABLE_MAX_PRIVILEGE,
1774 							   sizeof(dropSids) / sizeof(dropSids[0]),
1775 							   dropSids,
1776 							   0, NULL,
1777 							   0, NULL,
1778 							   &restrictedToken);
1779 
1780 	FreeSid(dropSids[1].Sid);
1781 	FreeSid(dropSids[0].Sid);
1782 	CloseHandle(origToken);
1783 	FreeLibrary(Advapi32Handle);
1784 
1785 	if (!b)
1786 	{
1787 		write_stderr(_("%s: could not create restricted token: error code %lu\n"),
1788 					 progname, (unsigned long) GetLastError());
1789 		return 0;
1790 	}
1791 
1792 	AddUserToTokenDacl(restrictedToken);
1793 	r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1794 
1795 	Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1796 	if (Kernel32Handle != NULL)
1797 	{
1798 		_IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1799 		_CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1800 		_SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1801 		_AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1802 		_QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1803 	}
1804 
1805 	/* Verify that we found all functions */
1806 	if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1807 	{
1808 		/*
1809 		 * IsProcessInJob() is not available on < WinXP, so there is no need
1810 		 * to log the error every time in that case
1811 		 */
1812 		if (IsWindowsXPOrGreater())
1813 
1814 			/*
1815 			 * Log error if we can't get version, or if we're on WinXP/2003 or
1816 			 * newer
1817 			 */
1818 			write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname);
1819 	}
1820 	else
1821 	{
1822 		BOOL		inJob;
1823 
1824 		if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1825 		{
1826 			if (!inJob)
1827 			{
1828 				/*
1829 				 * Job objects are working, and the new process isn't in one,
1830 				 * so we can create one safely. If any problems show up when
1831 				 * setting it, we're going to ignore them.
1832 				 */
1833 				HANDLE		job;
1834 				char		jobname[128];
1835 
1836 				sprintf(jobname, "PostgreSQL_%lu",
1837 						(unsigned long) processInfo->dwProcessId);
1838 
1839 				job = _CreateJobObject(NULL, jobname);
1840 				if (job)
1841 				{
1842 					JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1843 					JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1844 					JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1845 
1846 					ZeroMemory(&basicLimit, sizeof(basicLimit));
1847 					ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1848 					ZeroMemory(&securityLimit, sizeof(securityLimit));
1849 
1850 					basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1851 					basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1852 					_SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1853 
1854 					uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1855 						JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1856 						JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1857 
1858 					if (as_service)
1859 					{
1860 						if (!IsWindows7OrGreater())
1861 						{
1862 							/*
1863 							 * On Windows 7 (and presumably later),
1864 							 * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1865 							 * starting as a service. So we only enable it on
1866 							 * Vista and earlier (version <= 6.0)
1867 							 */
1868 							uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1869 						}
1870 					}
1871 					_SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1872 
1873 					securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1874 					securityLimit.JobToken = restrictedToken;
1875 					_SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1876 
1877 					_AssignProcessToJobObject(job, processInfo->hProcess);
1878 				}
1879 			}
1880 		}
1881 	}
1882 
1883 
1884 	CloseHandle(restrictedToken);
1885 
1886 	ResumeThread(processInfo->hThread);
1887 
1888 	FreeLibrary(Kernel32Handle);
1889 
1890 	/*
1891 	 * We intentionally don't close the job object handle, because we want the
1892 	 * object to live on until pg_ctl shuts down.
1893 	 */
1894 	return r;
1895 }
1896 #endif   /* WIN32 */
1897 
1898 static void
do_advice(void)1899 do_advice(void)
1900 {
1901 	write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1902 }
1903 
1904 
1905 
1906 static void
do_help(void)1907 do_help(void)
1908 {
1909 	printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1910 	printf(_("Usage:\n"));
1911 	printf(_("  %s init[db]               [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1912 	printf(_("  %s start   [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1913 	printf(_("  %s stop    [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1914 	printf(_("  %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1915 			 "                 [-o \"OPTIONS\"]\n"), progname);
1916 	printf(_("  %s reload  [-D DATADIR] [-s]\n"), progname);
1917 	printf(_("  %s status  [-D DATADIR]\n"), progname);
1918 	printf(_("  %s promote [-D DATADIR] [-s]\n"), progname);
1919 	printf(_("  %s kill    SIGNALNAME PID\n"), progname);
1920 #ifdef WIN32
1921 	printf(_("  %s register   [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1922 			 "                    [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1923 	printf(_("  %s unregister [-N SERVICENAME]\n"), progname);
1924 #endif
1925 
1926 	printf(_("\nCommon options:\n"));
1927 	printf(_("  -D, --pgdata=DATADIR   location of the database storage area\n"));
1928 #ifdef WIN32
1929 	printf(_("  -e SOURCE              event source for logging when running as a service\n"));
1930 #endif
1931 	printf(_("  -s, --silent           only print errors, no informational messages\n"));
1932 	printf(_("  -t, --timeout=SECS     seconds to wait when using -w option\n"));
1933 	printf(_("  -V, --version          output version information, then exit\n"));
1934 	printf(_("  -w                     wait until operation completes\n"));
1935 	printf(_("  -W                     do not wait until operation completes\n"));
1936 	printf(_("  -?, --help             show this help, then exit\n"));
1937 	printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1938 	printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1939 
1940 	printf(_("\nOptions for start or restart:\n"));
1941 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1942 	printf(_("  -c, --core-files       allow postgres to produce core files\n"));
1943 #else
1944 	printf(_("  -c, --core-files       not applicable on this platform\n"));
1945 #endif
1946 	printf(_("  -l, --log=FILENAME     write (or append) server log to FILENAME\n"));
1947 	printf(_("  -o OPTIONS             command line options to pass to postgres\n"
1948 	 "                         (PostgreSQL server executable) or initdb\n"));
1949 	printf(_("  -p PATH-TO-POSTGRES    normally not necessary\n"));
1950 	printf(_("\nOptions for stop or restart:\n"));
1951 	printf(_("  -m, --mode=MODE        MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
1952 
1953 	printf(_("\nShutdown modes are:\n"));
1954 	printf(_("  smart       quit after all clients have disconnected\n"));
1955 	printf(_("  fast        quit directly, with proper shutdown\n"));
1956 	printf(_("  immediate   quit without complete shutdown; will lead to recovery on restart\n"));
1957 
1958 	printf(_("\nAllowed signal names for kill:\n"));
1959 	printf("  ABRT HUP INT QUIT TERM USR1 USR2\n");
1960 
1961 #ifdef WIN32
1962 	printf(_("\nOptions for register and unregister:\n"));
1963 	printf(_("  -N SERVICENAME  service name with which to register PostgreSQL server\n"));
1964 	printf(_("  -P PASSWORD     password of account to register PostgreSQL server\n"));
1965 	printf(_("  -U USERNAME     user name of account to register PostgreSQL server\n"));
1966 	printf(_("  -S START-TYPE   service start type to register PostgreSQL server\n"));
1967 
1968 	printf(_("\nStart types are:\n"));
1969 	printf(_("  auto       start service automatically during system startup (default)\n"));
1970 	printf(_("  demand     start service on demand\n"));
1971 #endif
1972 
1973 	printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1974 }
1975 
1976 
1977 
1978 static void
set_mode(char * modeopt)1979 set_mode(char *modeopt)
1980 {
1981 	if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1982 	{
1983 		shutdown_mode = SMART_MODE;
1984 		sig = SIGTERM;
1985 	}
1986 	else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1987 	{
1988 		shutdown_mode = FAST_MODE;
1989 		sig = SIGINT;
1990 	}
1991 	else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1992 	{
1993 		shutdown_mode = IMMEDIATE_MODE;
1994 		sig = SIGQUIT;
1995 	}
1996 	else
1997 	{
1998 		write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1999 		do_advice();
2000 		exit(1);
2001 	}
2002 }
2003 
2004 
2005 
2006 static void
set_sig(char * signame)2007 set_sig(char *signame)
2008 {
2009 	if (strcmp(signame, "HUP") == 0)
2010 		sig = SIGHUP;
2011 	else if (strcmp(signame, "INT") == 0)
2012 		sig = SIGINT;
2013 	else if (strcmp(signame, "QUIT") == 0)
2014 		sig = SIGQUIT;
2015 	else if (strcmp(signame, "ABRT") == 0)
2016 		sig = SIGABRT;
2017 #if 0
2018 	/* probably should NOT provide SIGKILL */
2019 	else if (strcmp(signame, "KILL") == 0)
2020 		sig = SIGKILL;
2021 #endif
2022 	else if (strcmp(signame, "TERM") == 0)
2023 		sig = SIGTERM;
2024 	else if (strcmp(signame, "USR1") == 0)
2025 		sig = SIGUSR1;
2026 	else if (strcmp(signame, "USR2") == 0)
2027 		sig = SIGUSR2;
2028 	else
2029 	{
2030 		write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
2031 		do_advice();
2032 		exit(1);
2033 	}
2034 }
2035 
2036 
2037 #ifdef WIN32
2038 static void
set_starttype(char * starttypeopt)2039 set_starttype(char *starttypeopt)
2040 {
2041 	if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
2042 		pgctl_start_type = SERVICE_AUTO_START;
2043 	else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
2044 		pgctl_start_type = SERVICE_DEMAND_START;
2045 	else
2046 	{
2047 		write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
2048 		do_advice();
2049 		exit(1);
2050 	}
2051 }
2052 #endif
2053 
2054 /*
2055  * adjust_data_dir
2056  *
2057  * If a configuration-only directory was specified, find the real data dir.
2058  */
2059 static void
adjust_data_dir(void)2060 adjust_data_dir(void)
2061 {
2062 	char		filename[MAXPGPATH];
2063 	char	   *my_exec_path,
2064 			   *cmd;
2065 	FILE	   *fd;
2066 
2067 	/* do nothing if we're working without knowledge of data dir */
2068 	if (pg_config == NULL)
2069 		return;
2070 
2071 	/* If there is no postgresql.conf, it can't be a config-only dir */
2072 	snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
2073 	if ((fd = fopen(filename, "r")) == NULL)
2074 		return;
2075 	fclose(fd);
2076 
2077 	/* If PG_VERSION exists, it can't be a config-only dir */
2078 	snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
2079 	if ((fd = fopen(filename, "r")) != NULL)
2080 	{
2081 		fclose(fd);
2082 		return;
2083 	}
2084 
2085 	/* Must be a configuration directory, so find the data directory */
2086 
2087 	/* we use a private my_exec_path to avoid interfering with later uses */
2088 	if (exec_path == NULL)
2089 		my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
2090 	else
2091 		my_exec_path = pg_strdup(exec_path);
2092 
2093 	/* it's important for -C to be the first option, see main.c */
2094 	cmd = psprintf("\"%s\" -C data_directory %s%s",
2095 				   my_exec_path,
2096 				   pgdata_opt ? pgdata_opt : "",
2097 				   post_opts ? post_opts : "");
2098 
2099 	fd = popen(cmd, "r");
2100 	if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
2101 	{
2102 		write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
2103 		exit(1);
2104 	}
2105 	pclose(fd);
2106 	free(my_exec_path);
2107 
2108 	/* Remove trailing newline */
2109 	if (strchr(filename, '\n') != NULL)
2110 		*strchr(filename, '\n') = '\0';
2111 
2112 	free(pg_data);
2113 	pg_data = pg_strdup(filename);
2114 	canonicalize_path(pg_data);
2115 }
2116 
2117 
2118 int
main(int argc,char ** argv)2119 main(int argc, char **argv)
2120 {
2121 	static struct option long_options[] = {
2122 		{"help", no_argument, NULL, '?'},
2123 		{"version", no_argument, NULL, 'V'},
2124 		{"log", required_argument, NULL, 'l'},
2125 		{"mode", required_argument, NULL, 'm'},
2126 		{"pgdata", required_argument, NULL, 'D'},
2127 		{"silent", no_argument, NULL, 's'},
2128 		{"timeout", required_argument, NULL, 't'},
2129 		{"core-files", no_argument, NULL, 'c'},
2130 		{NULL, 0, NULL, 0}
2131 	};
2132 
2133 	char	   *env_wait;
2134 	int			option_index;
2135 	int			c;
2136 	pgpid_t		killproc = 0;
2137 
2138 #ifdef WIN32
2139 	setvbuf(stderr, NULL, _IONBF, 0);
2140 #endif
2141 
2142 	progname = get_progname(argv[0]);
2143 	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
2144 	start_time = time(NULL);
2145 
2146 	/*
2147 	 * save argv[0] so do_start() can look for the postmaster if necessary. we
2148 	 * don't look for postmaster here because in many cases we won't need it.
2149 	 */
2150 	argv0 = argv[0];
2151 
2152 	umask(S_IRWXG | S_IRWXO);
2153 
2154 	/* support --help and --version even if invoked as root */
2155 	if (argc > 1)
2156 	{
2157 		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2158 		{
2159 			do_help();
2160 			exit(0);
2161 		}
2162 		else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2163 		{
2164 			puts("pg_ctl (PostgreSQL) " PG_VERSION);
2165 			exit(0);
2166 		}
2167 	}
2168 
2169 	/*
2170 	 * Disallow running as root, to forestall any possible security holes.
2171 	 */
2172 #ifndef WIN32
2173 	if (geteuid() == 0)
2174 	{
2175 		write_stderr(_("%s: cannot be run as root\n"
2176 					   "Please log in (using, e.g., \"su\") as the "
2177 					   "(unprivileged) user that will\n"
2178 					   "own the server process.\n"),
2179 					 progname);
2180 		exit(1);
2181 	}
2182 #endif
2183 
2184 	env_wait = getenv("PGCTLTIMEOUT");
2185 	if (env_wait != NULL)
2186 		wait_seconds = atoi(env_wait);
2187 
2188 	/*
2189 	 * 'Action' can be before or after args so loop over both. Some
2190 	 * getopt_long() implementations will reorder argv[] to place all flags
2191 	 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2192 	 * that.
2193 	 */
2194 	optind = 1;
2195 
2196 	/* process command-line options */
2197 	while (optind < argc)
2198 	{
2199 		while ((c = getopt_long(argc, argv, "cD:e:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
2200 		{
2201 			switch (c)
2202 			{
2203 				case 'D':
2204 					{
2205 						char	   *pgdata_D;
2206 						char	   *env_var;
2207 
2208 						pgdata_D = pg_strdup(optarg);
2209 						canonicalize_path(pgdata_D);
2210 						env_var = psprintf("PGDATA=%s", pgdata_D);
2211 						putenv(env_var);
2212 
2213 						/*
2214 						 * We could pass PGDATA just in an environment
2215 						 * variable but we do -D too for clearer postmaster
2216 						 * 'ps' display
2217 						 */
2218 						pgdata_opt = psprintf("-D \"%s\" ", pgdata_D);
2219 						break;
2220 					}
2221 				case 'e':
2222 					event_source = pg_strdup(optarg);
2223 					break;
2224 				case 'l':
2225 					log_file = pg_strdup(optarg);
2226 					break;
2227 				case 'm':
2228 					set_mode(optarg);
2229 					break;
2230 				case 'N':
2231 					register_servicename = pg_strdup(optarg);
2232 					break;
2233 				case 'o':
2234 					/* append option? */
2235 					if (!post_opts)
2236 						post_opts = pg_strdup(optarg);
2237 					else
2238 					{
2239 						char	   *old_post_opts = post_opts;
2240 
2241 						post_opts = psprintf("%s %s", old_post_opts, optarg);
2242 						free(old_post_opts);
2243 					}
2244 					break;
2245 				case 'p':
2246 					exec_path = pg_strdup(optarg);
2247 					break;
2248 				case 'P':
2249 					register_password = pg_strdup(optarg);
2250 					break;
2251 				case 's':
2252 					silent_mode = true;
2253 					break;
2254 				case 'S':
2255 #ifdef WIN32
2256 					set_starttype(optarg);
2257 #else
2258 					write_stderr(_("%s: -S option not supported on this platform\n"),
2259 								 progname);
2260 					exit(1);
2261 #endif
2262 					break;
2263 				case 't':
2264 					wait_seconds = atoi(optarg);
2265 					wait_seconds_arg = true;
2266 					break;
2267 				case 'U':
2268 					if (strchr(optarg, '\\'))
2269 						register_username = pg_strdup(optarg);
2270 					else
2271 						/* Prepend .\ for local accounts */
2272 						register_username = psprintf(".\\%s", optarg);
2273 					break;
2274 				case 'w':
2275 					do_wait = true;
2276 					wait_set = true;
2277 					break;
2278 				case 'W':
2279 					do_wait = false;
2280 					wait_set = true;
2281 					break;
2282 				case 'c':
2283 					allow_core_files = true;
2284 					break;
2285 				default:
2286 					/* getopt_long already issued a suitable error message */
2287 					do_advice();
2288 					exit(1);
2289 			}
2290 		}
2291 
2292 		/* Process an action */
2293 		if (optind < argc)
2294 		{
2295 			if (ctl_command != NO_COMMAND)
2296 			{
2297 				write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2298 				do_advice();
2299 				exit(1);
2300 			}
2301 
2302 			if (strcmp(argv[optind], "init") == 0
2303 				|| strcmp(argv[optind], "initdb") == 0)
2304 				ctl_command = INIT_COMMAND;
2305 			else if (strcmp(argv[optind], "start") == 0)
2306 				ctl_command = START_COMMAND;
2307 			else if (strcmp(argv[optind], "stop") == 0)
2308 				ctl_command = STOP_COMMAND;
2309 			else if (strcmp(argv[optind], "restart") == 0)
2310 				ctl_command = RESTART_COMMAND;
2311 			else if (strcmp(argv[optind], "reload") == 0)
2312 				ctl_command = RELOAD_COMMAND;
2313 			else if (strcmp(argv[optind], "status") == 0)
2314 				ctl_command = STATUS_COMMAND;
2315 			else if (strcmp(argv[optind], "promote") == 0)
2316 				ctl_command = PROMOTE_COMMAND;
2317 			else if (strcmp(argv[optind], "kill") == 0)
2318 			{
2319 				if (argc - optind < 3)
2320 				{
2321 					write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2322 					do_advice();
2323 					exit(1);
2324 				}
2325 				ctl_command = KILL_COMMAND;
2326 				set_sig(argv[++optind]);
2327 				killproc = atol(argv[++optind]);
2328 			}
2329 #ifdef WIN32
2330 			else if (strcmp(argv[optind], "register") == 0)
2331 				ctl_command = REGISTER_COMMAND;
2332 			else if (strcmp(argv[optind], "unregister") == 0)
2333 				ctl_command = UNREGISTER_COMMAND;
2334 			else if (strcmp(argv[optind], "runservice") == 0)
2335 				ctl_command = RUN_AS_SERVICE_COMMAND;
2336 #endif
2337 			else
2338 			{
2339 				write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2340 				do_advice();
2341 				exit(1);
2342 			}
2343 			optind++;
2344 		}
2345 	}
2346 
2347 	if (ctl_command == NO_COMMAND)
2348 	{
2349 		write_stderr(_("%s: no operation specified\n"), progname);
2350 		do_advice();
2351 		exit(1);
2352 	}
2353 
2354 	/* Note we put any -D switch into the env var above */
2355 	pg_config = getenv("PGDATA");
2356 	if (pg_config)
2357 	{
2358 		pg_config = pg_strdup(pg_config);
2359 		canonicalize_path(pg_config);
2360 		pg_data = pg_strdup(pg_config);
2361 	}
2362 
2363 	/* -D might point at config-only directory; if so find the real PGDATA */
2364 	adjust_data_dir();
2365 
2366 	/* Complain if -D needed and not provided */
2367 	if (pg_config == NULL &&
2368 		ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2369 	{
2370 		write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2371 					 progname);
2372 		do_advice();
2373 		exit(1);
2374 	}
2375 
2376 	if (!wait_set)
2377 	{
2378 		switch (ctl_command)
2379 		{
2380 			case RESTART_COMMAND:
2381 			case START_COMMAND:
2382 				do_wait = false;
2383 				break;
2384 			case STOP_COMMAND:
2385 				do_wait = true;
2386 				break;
2387 			default:
2388 				break;
2389 		}
2390 	}
2391 
2392 	if (ctl_command == RELOAD_COMMAND)
2393 	{
2394 		sig = SIGHUP;
2395 		do_wait = false;
2396 	}
2397 
2398 	if (pg_data)
2399 	{
2400 		snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2401 		snprintf(version_file, MAXPGPATH, "%s/PG_VERSION", pg_data);
2402 		snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2403 		snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2404 		snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2405 	}
2406 
2407 	switch (ctl_command)
2408 	{
2409 		case INIT_COMMAND:
2410 			do_init();
2411 			break;
2412 		case STATUS_COMMAND:
2413 			do_status();
2414 			break;
2415 		case START_COMMAND:
2416 			do_start();
2417 			break;
2418 		case STOP_COMMAND:
2419 			do_stop();
2420 			break;
2421 		case RESTART_COMMAND:
2422 			do_restart();
2423 			break;
2424 		case RELOAD_COMMAND:
2425 			do_reload();
2426 			break;
2427 		case PROMOTE_COMMAND:
2428 			do_promote();
2429 			break;
2430 		case KILL_COMMAND:
2431 			do_kill(killproc);
2432 			break;
2433 #ifdef WIN32
2434 		case REGISTER_COMMAND:
2435 			pgwin32_doRegister();
2436 			break;
2437 		case UNREGISTER_COMMAND:
2438 			pgwin32_doUnregister();
2439 			break;
2440 		case RUN_AS_SERVICE_COMMAND:
2441 			pgwin32_doRunAsService();
2442 			break;
2443 #endif
2444 		default:
2445 			break;
2446 	}
2447 
2448 	exit(0);
2449 }
2450