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